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::{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::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, 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 std::iter::Peekable;
  117use task::{ResolvedTask, TaskTemplate, TaskVariables};
  118
  119use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  120pub use lsp::CompletionContext;
  121use lsp::{
  122    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  123    LanguageServerId, LanguageServerName,
  124};
  125
  126use language::BufferSnapshot;
  127use movement::TextLayoutDetails;
  128pub use multi_buffer::{
  129    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  130    ToOffset, ToPoint,
  131};
  132use multi_buffer::{
  133    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  134    ToOffsetUtf16,
  135};
  136use project::{
  137    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  138    project_settings::{GitGutterSetting, ProjectSettings},
  139    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  140    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  141};
  142use rand::prelude::*;
  143use rpc::{proto::*, ErrorExt};
  144use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  145use selections_collection::{
  146    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  147};
  148use serde::{Deserialize, Serialize};
  149use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  150use smallvec::SmallVec;
  151use snippet::Snippet;
  152use std::{
  153    any::TypeId,
  154    borrow::Cow,
  155    cell::RefCell,
  156    cmp::{self, Ordering, Reverse},
  157    mem,
  158    num::NonZeroU32,
  159    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  160    path::{Path, PathBuf},
  161    rc::Rc,
  162    sync::Arc,
  163    time::{Duration, Instant},
  164};
  165pub use sum_tree::Bias;
  166use sum_tree::TreeMap;
  167use text::{BufferId, OffsetUtf16, Rope};
  168use theme::{
  169    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  170    ThemeColors, ThemeSettings,
  171};
  172use ui::{
  173    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  174    Tooltip,
  175};
  176use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  177use workspace::{
  178    item::{ItemHandle, PreviewTabsSettings},
  179    ItemId, RestoreOnStartupBehavior,
  180};
  181use workspace::{
  182    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  183    WorkspaceSettings,
  184};
  185use workspace::{
  186    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  187};
  188use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  189
  190use crate::hover_links::{find_url, find_url_from_range};
  191use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  192
  193pub const FILE_HEADER_HEIGHT: u32 = 2;
  194pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  195pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  196pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  197const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  198const MAX_LINE_LEN: usize = 1024;
  199const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  200const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  201pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  202#[doc(hidden)]
  203pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  204
  205pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  206pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  207
  208pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  209pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  210
  211const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  212    alt: true,
  213    shift: true,
  214    control: false,
  215    platform: false,
  216    function: false,
  217};
  218
  219#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  220pub enum InlayId {
  221    InlineCompletion(usize),
  222    Hint(usize),
  223}
  224
  225impl InlayId {
  226    fn id(&self) -> usize {
  227        match self {
  228            Self::InlineCompletion(id) => *id,
  229            Self::Hint(id) => *id,
  230        }
  231    }
  232}
  233
  234enum DocumentHighlightRead {}
  235enum DocumentHighlightWrite {}
  236enum InputComposition {}
  237enum SelectedTextHighlight {}
  238
  239#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  240pub enum Navigated {
  241    Yes,
  242    No,
  243}
  244
  245impl Navigated {
  246    pub fn from_bool(yes: bool) -> Navigated {
  247        if yes {
  248            Navigated::Yes
  249        } else {
  250            Navigated::No
  251        }
  252    }
  253}
  254
  255pub fn init_settings(cx: &mut App) {
  256    EditorSettings::register(cx);
  257}
  258
  259pub fn init(cx: &mut App) {
  260    init_settings(cx);
  261
  262    workspace::register_project_item::<Editor>(cx);
  263    workspace::FollowableViewRegistry::register::<Editor>(cx);
  264    workspace::register_serializable_item::<Editor>(cx);
  265
  266    cx.observe_new(
  267        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  268            workspace.register_action(Editor::new_file);
  269            workspace.register_action(Editor::new_file_vertical);
  270            workspace.register_action(Editor::new_file_horizontal);
  271            workspace.register_action(Editor::cancel_language_server_work);
  272        },
  273    )
  274    .detach();
  275
  276    cx.on_action(move |_: &workspace::NewFile, cx| {
  277        let app_state = workspace::AppState::global(cx);
  278        if let Some(app_state) = app_state.upgrade() {
  279            workspace::open_new(
  280                Default::default(),
  281                app_state,
  282                cx,
  283                |workspace, window, cx| {
  284                    Editor::new_file(workspace, &Default::default(), window, cx)
  285                },
  286            )
  287            .detach();
  288        }
  289    });
  290    cx.on_action(move |_: &workspace::NewWindow, cx| {
  291        let app_state = workspace::AppState::global(cx);
  292        if let Some(app_state) = app_state.upgrade() {
  293            workspace::open_new(
  294                Default::default(),
  295                app_state,
  296                cx,
  297                |workspace, window, cx| {
  298                    cx.activate(true);
  299                    Editor::new_file(workspace, &Default::default(), window, cx)
  300                },
  301            )
  302            .detach();
  303        }
  304    });
  305}
  306
  307pub struct SearchWithinRange;
  308
  309trait InvalidationRegion {
  310    fn ranges(&self) -> &[Range<Anchor>];
  311}
  312
  313#[derive(Clone, Debug, PartialEq)]
  314pub enum SelectPhase {
  315    Begin {
  316        position: DisplayPoint,
  317        add: bool,
  318        click_count: usize,
  319    },
  320    BeginColumnar {
  321        position: DisplayPoint,
  322        reset: bool,
  323        goal_column: u32,
  324    },
  325    Extend {
  326        position: DisplayPoint,
  327        click_count: usize,
  328    },
  329    Update {
  330        position: DisplayPoint,
  331        goal_column: u32,
  332        scroll_delta: gpui::Point<f32>,
  333    },
  334    End,
  335}
  336
  337#[derive(Clone, Debug)]
  338pub enum SelectMode {
  339    Character,
  340    Word(Range<Anchor>),
  341    Line(Range<Anchor>),
  342    All,
  343}
  344
  345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  346pub enum EditorMode {
  347    SingleLine { auto_width: bool },
  348    AutoHeight { max_lines: usize },
  349    Full,
  350}
  351
  352#[derive(Copy, Clone, Debug)]
  353pub enum SoftWrap {
  354    /// Prefer not to wrap at all.
  355    ///
  356    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  357    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  358    GitDiff,
  359    /// Prefer a single line generally, unless an overly long line is encountered.
  360    None,
  361    /// Soft wrap lines that exceed the editor width.
  362    EditorWidth,
  363    /// Soft wrap lines at the preferred line length.
  364    Column(u32),
  365    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  366    Bounded(u32),
  367}
  368
  369#[derive(Clone)]
  370pub struct EditorStyle {
  371    pub background: Hsla,
  372    pub local_player: PlayerColor,
  373    pub text: TextStyle,
  374    pub scrollbar_width: Pixels,
  375    pub syntax: Arc<SyntaxTheme>,
  376    pub status: StatusColors,
  377    pub inlay_hints_style: HighlightStyle,
  378    pub inline_completion_styles: InlineCompletionStyles,
  379    pub unnecessary_code_fade: f32,
  380}
  381
  382impl Default for EditorStyle {
  383    fn default() -> Self {
  384        Self {
  385            background: Hsla::default(),
  386            local_player: PlayerColor::default(),
  387            text: TextStyle::default(),
  388            scrollbar_width: Pixels::default(),
  389            syntax: Default::default(),
  390            // HACK: Status colors don't have a real default.
  391            // We should look into removing the status colors from the editor
  392            // style and retrieve them directly from the theme.
  393            status: StatusColors::dark(),
  394            inlay_hints_style: HighlightStyle::default(),
  395            inline_completion_styles: InlineCompletionStyles {
  396                insertion: HighlightStyle::default(),
  397                whitespace: HighlightStyle::default(),
  398            },
  399            unnecessary_code_fade: Default::default(),
  400        }
  401    }
  402}
  403
  404pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  405    let show_background = language_settings::language_settings(None, None, cx)
  406        .inlay_hints
  407        .show_background;
  408
  409    HighlightStyle {
  410        color: Some(cx.theme().status().hint),
  411        background_color: show_background.then(|| cx.theme().status().hint_background),
  412        ..HighlightStyle::default()
  413    }
  414}
  415
  416pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  417    InlineCompletionStyles {
  418        insertion: HighlightStyle {
  419            color: Some(cx.theme().status().predictive),
  420            ..HighlightStyle::default()
  421        },
  422        whitespace: HighlightStyle {
  423            background_color: Some(cx.theme().status().created_background),
  424            ..HighlightStyle::default()
  425        },
  426    }
  427}
  428
  429type CompletionId = usize;
  430
  431pub(crate) enum EditDisplayMode {
  432    TabAccept,
  433    DiffPopover,
  434    Inline,
  435}
  436
  437enum InlineCompletion {
  438    Edit {
  439        edits: Vec<(Range<Anchor>, String)>,
  440        edit_preview: Option<EditPreview>,
  441        display_mode: EditDisplayMode,
  442        snapshot: BufferSnapshot,
  443    },
  444    Move {
  445        target: Anchor,
  446        snapshot: BufferSnapshot,
  447    },
  448}
  449
  450struct InlineCompletionState {
  451    inlay_ids: Vec<InlayId>,
  452    completion: InlineCompletion,
  453    completion_id: Option<SharedString>,
  454    invalidation_range: Range<Anchor>,
  455}
  456
  457enum EditPredictionSettings {
  458    Disabled,
  459    Enabled {
  460        show_in_menu: bool,
  461        preview_requires_modifier: bool,
  462    },
  463}
  464
  465enum InlineCompletionHighlight {}
  466
  467pub enum MenuInlineCompletionsPolicy {
  468    Never,
  469    ByProvider,
  470}
  471
  472pub enum EditPredictionPreview {
  473    /// Modifier is not pressed
  474    Inactive,
  475    /// Modifier pressed
  476    Active {
  477        previous_scroll_position: Option<ScrollAnchor>,
  478    },
  479}
  480
  481#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  482struct EditorActionId(usize);
  483
  484impl EditorActionId {
  485    pub fn post_inc(&mut self) -> Self {
  486        let answer = self.0;
  487
  488        *self = Self(answer + 1);
  489
  490        Self(answer)
  491    }
  492}
  493
  494// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  495// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  496
  497type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  498type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  499
  500#[derive(Default)]
  501struct ScrollbarMarkerState {
  502    scrollbar_size: Size<Pixels>,
  503    dirty: bool,
  504    markers: Arc<[PaintQuad]>,
  505    pending_refresh: Option<Task<Result<()>>>,
  506}
  507
  508impl ScrollbarMarkerState {
  509    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  510        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  511    }
  512}
  513
  514#[derive(Clone, Debug)]
  515struct RunnableTasks {
  516    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  517    offset: MultiBufferOffset,
  518    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  519    column: u32,
  520    // Values of all named captures, including those starting with '_'
  521    extra_variables: HashMap<String, String>,
  522    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  523    context_range: Range<BufferOffset>,
  524}
  525
  526impl RunnableTasks {
  527    fn resolve<'a>(
  528        &'a self,
  529        cx: &'a task::TaskContext,
  530    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  531        self.templates.iter().filter_map(|(kind, template)| {
  532            template
  533                .resolve_task(&kind.to_id_base(), cx)
  534                .map(|task| (kind.clone(), task))
  535        })
  536    }
  537}
  538
  539#[derive(Clone)]
  540struct ResolvedTasks {
  541    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  542    position: Anchor,
  543}
  544#[derive(Copy, Clone, Debug)]
  545struct MultiBufferOffset(usize);
  546#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  547struct BufferOffset(usize);
  548
  549// Addons allow storing per-editor state in other crates (e.g. Vim)
  550pub trait Addon: 'static {
  551    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  552
  553    fn render_buffer_header_controls(
  554        &self,
  555        _: &ExcerptInfo,
  556        _: &Window,
  557        _: &App,
  558    ) -> Option<AnyElement> {
  559        None
  560    }
  561
  562    fn to_any(&self) -> &dyn std::any::Any;
  563}
  564
  565#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  566pub enum IsVimMode {
  567    Yes,
  568    No,
  569}
  570
  571/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  572///
  573/// See the [module level documentation](self) for more information.
  574pub struct Editor {
  575    focus_handle: FocusHandle,
  576    last_focused_descendant: Option<WeakFocusHandle>,
  577    /// The text buffer being edited
  578    buffer: Entity<MultiBuffer>,
  579    /// Map of how text in the buffer should be displayed.
  580    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  581    pub display_map: Entity<DisplayMap>,
  582    pub selections: SelectionsCollection,
  583    pub scroll_manager: ScrollManager,
  584    /// When inline assist editors are linked, they all render cursors because
  585    /// typing enters text into each of them, even the ones that aren't focused.
  586    pub(crate) show_cursor_when_unfocused: bool,
  587    columnar_selection_tail: Option<Anchor>,
  588    add_selections_state: Option<AddSelectionsState>,
  589    select_next_state: Option<SelectNextState>,
  590    select_prev_state: Option<SelectNextState>,
  591    selection_history: SelectionHistory,
  592    autoclose_regions: Vec<AutocloseRegion>,
  593    snippet_stack: InvalidationStack<SnippetState>,
  594    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  595    ime_transaction: Option<TransactionId>,
  596    active_diagnostics: Option<ActiveDiagnosticGroup>,
  597    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  598
  599    // TODO: make this a access method
  600    pub project: Option<Entity<Project>>,
  601    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  602    completion_provider: Option<Box<dyn CompletionProvider>>,
  603    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  604    blink_manager: Entity<BlinkManager>,
  605    show_cursor_names: bool,
  606    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  607    pub show_local_selections: bool,
  608    mode: EditorMode,
  609    show_breadcrumbs: bool,
  610    show_gutter: bool,
  611    show_scrollbars: bool,
  612    show_line_numbers: Option<bool>,
  613    use_relative_line_numbers: Option<bool>,
  614    show_git_diff_gutter: Option<bool>,
  615    show_code_actions: Option<bool>,
  616    show_runnables: Option<bool>,
  617    show_wrap_guides: Option<bool>,
  618    show_indent_guides: Option<bool>,
  619    placeholder_text: Option<Arc<str>>,
  620    highlight_order: usize,
  621    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  622    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  623    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  624    scrollbar_marker_state: ScrollbarMarkerState,
  625    active_indent_guides_state: ActiveIndentGuidesState,
  626    nav_history: Option<ItemNavHistory>,
  627    context_menu: RefCell<Option<CodeContextMenu>>,
  628    mouse_context_menu: Option<MouseContextMenu>,
  629    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  630    signature_help_state: SignatureHelpState,
  631    auto_signature_help: Option<bool>,
  632    find_all_references_task_sources: Vec<Anchor>,
  633    next_completion_id: CompletionId,
  634    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  635    code_actions_task: Option<Task<Result<()>>>,
  636    selection_highlight_task: Option<Task<()>>,
  637    document_highlights_task: Option<Task<()>>,
  638    linked_editing_range_task: Option<Task<Option<()>>>,
  639    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  640    pending_rename: Option<RenameState>,
  641    searchable: bool,
  642    cursor_shape: CursorShape,
  643    current_line_highlight: Option<CurrentLineHighlight>,
  644    collapse_matches: bool,
  645    autoindent_mode: Option<AutoindentMode>,
  646    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  647    input_enabled: bool,
  648    use_modal_editing: bool,
  649    read_only: bool,
  650    leader_peer_id: Option<PeerId>,
  651    remote_id: Option<ViewId>,
  652    hover_state: HoverState,
  653    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  654    gutter_hovered: bool,
  655    hovered_link_state: Option<HoveredLinkState>,
  656    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  657    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  658    active_inline_completion: Option<InlineCompletionState>,
  659    /// Used to prevent flickering as the user types while the menu is open
  660    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  661    edit_prediction_settings: EditPredictionSettings,
  662    inline_completions_hidden_for_vim_mode: bool,
  663    show_inline_completions_override: Option<bool>,
  664    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  665    edit_prediction_preview: EditPredictionPreview,
  666    edit_prediction_cursor_on_leading_whitespace: bool,
  667    edit_prediction_requires_modifier_in_leading_space: bool,
  668    inlay_hint_cache: InlayHintCache,
  669    next_inlay_id: usize,
  670    _subscriptions: Vec<Subscription>,
  671    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  672    gutter_dimensions: GutterDimensions,
  673    style: Option<EditorStyle>,
  674    text_style_refinement: Option<TextStyleRefinement>,
  675    next_editor_action_id: EditorActionId,
  676    editor_actions:
  677        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  678    use_autoclose: bool,
  679    use_auto_surround: bool,
  680    auto_replace_emoji_shortcode: bool,
  681    show_git_blame_gutter: bool,
  682    show_git_blame_inline: bool,
  683    show_git_blame_inline_delay_task: Option<Task<()>>,
  684    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  685    distinguish_unstaged_diff_hunks: bool,
  686    git_blame_inline_enabled: bool,
  687    serialize_dirty_buffers: bool,
  688    show_selection_menu: Option<bool>,
  689    blame: Option<Entity<GitBlame>>,
  690    blame_subscription: Option<Subscription>,
  691    custom_context_menu: Option<
  692        Box<
  693            dyn 'static
  694                + Fn(
  695                    &mut Self,
  696                    DisplayPoint,
  697                    &mut Window,
  698                    &mut Context<Self>,
  699                ) -> Option<Entity<ui::ContextMenu>>,
  700        >,
  701    >,
  702    last_bounds: Option<Bounds<Pixels>>,
  703    last_position_map: Option<Rc<PositionMap>>,
  704    expect_bounds_change: Option<Bounds<Pixels>>,
  705    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  706    tasks_update_task: Option<Task<()>>,
  707    in_project_search: bool,
  708    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  709    breadcrumb_header: Option<String>,
  710    focused_block: Option<FocusedBlock>,
  711    next_scroll_position: NextScrollCursorCenterTopBottom,
  712    addons: HashMap<TypeId, Box<dyn Addon>>,
  713    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  714    load_diff_task: Option<Shared<Task<()>>>,
  715    selection_mark_mode: bool,
  716    toggle_fold_multiple_buffers: Task<()>,
  717    _scroll_cursor_center_top_bottom_task: Task<()>,
  718    serialize_selections: Task<()>,
  719}
  720
  721#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  722enum NextScrollCursorCenterTopBottom {
  723    #[default]
  724    Center,
  725    Top,
  726    Bottom,
  727}
  728
  729impl NextScrollCursorCenterTopBottom {
  730    fn next(&self) -> Self {
  731        match self {
  732            Self::Center => Self::Top,
  733            Self::Top => Self::Bottom,
  734            Self::Bottom => Self::Center,
  735        }
  736    }
  737}
  738
  739#[derive(Clone)]
  740pub struct EditorSnapshot {
  741    pub mode: EditorMode,
  742    show_gutter: bool,
  743    show_line_numbers: Option<bool>,
  744    show_git_diff_gutter: Option<bool>,
  745    show_code_actions: Option<bool>,
  746    show_runnables: Option<bool>,
  747    git_blame_gutter_max_author_length: Option<usize>,
  748    pub display_snapshot: DisplaySnapshot,
  749    pub placeholder_text: Option<Arc<str>>,
  750    is_focused: bool,
  751    scroll_anchor: ScrollAnchor,
  752    ongoing_scroll: OngoingScroll,
  753    current_line_highlight: CurrentLineHighlight,
  754    gutter_hovered: bool,
  755}
  756
  757const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  758
  759#[derive(Default, Debug, Clone, Copy)]
  760pub struct GutterDimensions {
  761    pub left_padding: Pixels,
  762    pub right_padding: Pixels,
  763    pub width: Pixels,
  764    pub margin: Pixels,
  765    pub git_blame_entries_width: Option<Pixels>,
  766}
  767
  768impl GutterDimensions {
  769    /// The full width of the space taken up by the gutter.
  770    pub fn full_width(&self) -> Pixels {
  771        self.margin + self.width
  772    }
  773
  774    /// The width of the space reserved for the fold indicators,
  775    /// use alongside 'justify_end' and `gutter_width` to
  776    /// right align content with the line numbers
  777    pub fn fold_area_width(&self) -> Pixels {
  778        self.margin + self.right_padding
  779    }
  780}
  781
  782#[derive(Debug)]
  783pub struct RemoteSelection {
  784    pub replica_id: ReplicaId,
  785    pub selection: Selection<Anchor>,
  786    pub cursor_shape: CursorShape,
  787    pub peer_id: PeerId,
  788    pub line_mode: bool,
  789    pub participant_index: Option<ParticipantIndex>,
  790    pub user_name: Option<SharedString>,
  791}
  792
  793#[derive(Clone, Debug)]
  794struct SelectionHistoryEntry {
  795    selections: Arc<[Selection<Anchor>]>,
  796    select_next_state: Option<SelectNextState>,
  797    select_prev_state: Option<SelectNextState>,
  798    add_selections_state: Option<AddSelectionsState>,
  799}
  800
  801enum SelectionHistoryMode {
  802    Normal,
  803    Undoing,
  804    Redoing,
  805}
  806
  807#[derive(Clone, PartialEq, Eq, Hash)]
  808struct HoveredCursor {
  809    replica_id: u16,
  810    selection_id: usize,
  811}
  812
  813impl Default for SelectionHistoryMode {
  814    fn default() -> Self {
  815        Self::Normal
  816    }
  817}
  818
  819#[derive(Default)]
  820struct SelectionHistory {
  821    #[allow(clippy::type_complexity)]
  822    selections_by_transaction:
  823        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  824    mode: SelectionHistoryMode,
  825    undo_stack: VecDeque<SelectionHistoryEntry>,
  826    redo_stack: VecDeque<SelectionHistoryEntry>,
  827}
  828
  829impl SelectionHistory {
  830    fn insert_transaction(
  831        &mut self,
  832        transaction_id: TransactionId,
  833        selections: Arc<[Selection<Anchor>]>,
  834    ) {
  835        self.selections_by_transaction
  836            .insert(transaction_id, (selections, None));
  837    }
  838
  839    #[allow(clippy::type_complexity)]
  840    fn transaction(
  841        &self,
  842        transaction_id: TransactionId,
  843    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  844        self.selections_by_transaction.get(&transaction_id)
  845    }
  846
  847    #[allow(clippy::type_complexity)]
  848    fn transaction_mut(
  849        &mut self,
  850        transaction_id: TransactionId,
  851    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  852        self.selections_by_transaction.get_mut(&transaction_id)
  853    }
  854
  855    fn push(&mut self, entry: SelectionHistoryEntry) {
  856        if !entry.selections.is_empty() {
  857            match self.mode {
  858                SelectionHistoryMode::Normal => {
  859                    self.push_undo(entry);
  860                    self.redo_stack.clear();
  861                }
  862                SelectionHistoryMode::Undoing => self.push_redo(entry),
  863                SelectionHistoryMode::Redoing => self.push_undo(entry),
  864            }
  865        }
  866    }
  867
  868    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  869        if self
  870            .undo_stack
  871            .back()
  872            .map_or(true, |e| e.selections != entry.selections)
  873        {
  874            self.undo_stack.push_back(entry);
  875            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  876                self.undo_stack.pop_front();
  877            }
  878        }
  879    }
  880
  881    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  882        if self
  883            .redo_stack
  884            .back()
  885            .map_or(true, |e| e.selections != entry.selections)
  886        {
  887            self.redo_stack.push_back(entry);
  888            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  889                self.redo_stack.pop_front();
  890            }
  891        }
  892    }
  893}
  894
  895struct RowHighlight {
  896    index: usize,
  897    range: Range<Anchor>,
  898    color: Hsla,
  899    should_autoscroll: bool,
  900}
  901
  902#[derive(Clone, Debug)]
  903struct AddSelectionsState {
  904    above: bool,
  905    stack: Vec<usize>,
  906}
  907
  908#[derive(Clone)]
  909struct SelectNextState {
  910    query: AhoCorasick,
  911    wordwise: bool,
  912    done: bool,
  913}
  914
  915impl std::fmt::Debug for SelectNextState {
  916    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  917        f.debug_struct(std::any::type_name::<Self>())
  918            .field("wordwise", &self.wordwise)
  919            .field("done", &self.done)
  920            .finish()
  921    }
  922}
  923
  924#[derive(Debug)]
  925struct AutocloseRegion {
  926    selection_id: usize,
  927    range: Range<Anchor>,
  928    pair: BracketPair,
  929}
  930
  931#[derive(Debug)]
  932struct SnippetState {
  933    ranges: Vec<Vec<Range<Anchor>>>,
  934    active_index: usize,
  935    choices: Vec<Option<Vec<String>>>,
  936}
  937
  938#[doc(hidden)]
  939pub struct RenameState {
  940    pub range: Range<Anchor>,
  941    pub old_name: Arc<str>,
  942    pub editor: Entity<Editor>,
  943    block_id: CustomBlockId,
  944}
  945
  946struct InvalidationStack<T>(Vec<T>);
  947
  948struct RegisteredInlineCompletionProvider {
  949    provider: Arc<dyn InlineCompletionProviderHandle>,
  950    _subscription: Subscription,
  951}
  952
  953#[derive(Debug)]
  954struct ActiveDiagnosticGroup {
  955    primary_range: Range<Anchor>,
  956    primary_message: String,
  957    group_id: usize,
  958    blocks: HashMap<CustomBlockId, Diagnostic>,
  959    is_valid: bool,
  960}
  961
  962#[derive(Serialize, Deserialize, Clone, Debug)]
  963pub struct ClipboardSelection {
  964    pub len: usize,
  965    pub is_entire_line: bool,
  966    pub first_line_indent: u32,
  967}
  968
  969#[derive(Debug)]
  970pub(crate) struct NavigationData {
  971    cursor_anchor: Anchor,
  972    cursor_position: Point,
  973    scroll_anchor: ScrollAnchor,
  974    scroll_top_row: u32,
  975}
  976
  977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  978pub enum GotoDefinitionKind {
  979    Symbol,
  980    Declaration,
  981    Type,
  982    Implementation,
  983}
  984
  985#[derive(Debug, Clone)]
  986enum InlayHintRefreshReason {
  987    Toggle(bool),
  988    SettingsChange(InlayHintSettings),
  989    NewLinesShown,
  990    BufferEdited(HashSet<Arc<Language>>),
  991    RefreshRequested,
  992    ExcerptsRemoved(Vec<ExcerptId>),
  993}
  994
  995impl InlayHintRefreshReason {
  996    fn description(&self) -> &'static str {
  997        match self {
  998            Self::Toggle(_) => "toggle",
  999            Self::SettingsChange(_) => "settings change",
 1000            Self::NewLinesShown => "new lines shown",
 1001            Self::BufferEdited(_) => "buffer edited",
 1002            Self::RefreshRequested => "refresh requested",
 1003            Self::ExcerptsRemoved(_) => "excerpts removed",
 1004        }
 1005    }
 1006}
 1007
 1008pub enum FormatTarget {
 1009    Buffers,
 1010    Ranges(Vec<Range<MultiBufferPoint>>),
 1011}
 1012
 1013pub(crate) struct FocusedBlock {
 1014    id: BlockId,
 1015    focus_handle: WeakFocusHandle,
 1016}
 1017
 1018#[derive(Clone)]
 1019enum JumpData {
 1020    MultiBufferRow {
 1021        row: MultiBufferRow,
 1022        line_offset_from_top: u32,
 1023    },
 1024    MultiBufferPoint {
 1025        excerpt_id: ExcerptId,
 1026        position: Point,
 1027        anchor: text::Anchor,
 1028        line_offset_from_top: u32,
 1029    },
 1030}
 1031
 1032pub enum MultibufferSelectionMode {
 1033    First,
 1034    All,
 1035}
 1036
 1037impl Editor {
 1038    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1039        let buffer = cx.new(|cx| Buffer::local("", cx));
 1040        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1041        Self::new(
 1042            EditorMode::SingleLine { auto_width: false },
 1043            buffer,
 1044            None,
 1045            false,
 1046            window,
 1047            cx,
 1048        )
 1049    }
 1050
 1051    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1052        let buffer = cx.new(|cx| Buffer::local("", cx));
 1053        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1054        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1055    }
 1056
 1057    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1058        let buffer = cx.new(|cx| Buffer::local("", cx));
 1059        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1060        Self::new(
 1061            EditorMode::SingleLine { auto_width: true },
 1062            buffer,
 1063            None,
 1064            false,
 1065            window,
 1066            cx,
 1067        )
 1068    }
 1069
 1070    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1071        let buffer = cx.new(|cx| Buffer::local("", cx));
 1072        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1073        Self::new(
 1074            EditorMode::AutoHeight { max_lines },
 1075            buffer,
 1076            None,
 1077            false,
 1078            window,
 1079            cx,
 1080        )
 1081    }
 1082
 1083    pub fn for_buffer(
 1084        buffer: Entity<Buffer>,
 1085        project: Option<Entity<Project>>,
 1086        window: &mut Window,
 1087        cx: &mut Context<Self>,
 1088    ) -> Self {
 1089        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1090        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1091    }
 1092
 1093    pub fn for_multibuffer(
 1094        buffer: Entity<MultiBuffer>,
 1095        project: Option<Entity<Project>>,
 1096        show_excerpt_controls: bool,
 1097        window: &mut Window,
 1098        cx: &mut Context<Self>,
 1099    ) -> Self {
 1100        Self::new(
 1101            EditorMode::Full,
 1102            buffer,
 1103            project,
 1104            show_excerpt_controls,
 1105            window,
 1106            cx,
 1107        )
 1108    }
 1109
 1110    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1111        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1112        let mut clone = Self::new(
 1113            self.mode,
 1114            self.buffer.clone(),
 1115            self.project.clone(),
 1116            show_excerpt_controls,
 1117            window,
 1118            cx,
 1119        );
 1120        self.display_map.update(cx, |display_map, cx| {
 1121            let snapshot = display_map.snapshot(cx);
 1122            clone.display_map.update(cx, |display_map, cx| {
 1123                display_map.set_state(&snapshot, cx);
 1124            });
 1125        });
 1126        clone.selections.clone_state(&self.selections);
 1127        clone.scroll_manager.clone_state(&self.scroll_manager);
 1128        clone.searchable = self.searchable;
 1129        clone
 1130    }
 1131
 1132    pub fn new(
 1133        mode: EditorMode,
 1134        buffer: Entity<MultiBuffer>,
 1135        project: Option<Entity<Project>>,
 1136        show_excerpt_controls: bool,
 1137        window: &mut Window,
 1138        cx: &mut Context<Self>,
 1139    ) -> Self {
 1140        let style = window.text_style();
 1141        let font_size = style.font_size.to_pixels(window.rem_size());
 1142        let editor = cx.entity().downgrade();
 1143        let fold_placeholder = FoldPlaceholder {
 1144            constrain_width: true,
 1145            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1146                let editor = editor.clone();
 1147                div()
 1148                    .id(fold_id)
 1149                    .bg(cx.theme().colors().ghost_element_background)
 1150                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1151                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1152                    .rounded_sm()
 1153                    .size_full()
 1154                    .cursor_pointer()
 1155                    .child("")
 1156                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1157                    .on_click(move |_, _window, cx| {
 1158                        editor
 1159                            .update(cx, |editor, cx| {
 1160                                editor.unfold_ranges(
 1161                                    &[fold_range.start..fold_range.end],
 1162                                    true,
 1163                                    false,
 1164                                    cx,
 1165                                );
 1166                                cx.stop_propagation();
 1167                            })
 1168                            .ok();
 1169                    })
 1170                    .into_any()
 1171            }),
 1172            merge_adjacent: true,
 1173            ..Default::default()
 1174        };
 1175        let display_map = cx.new(|cx| {
 1176            DisplayMap::new(
 1177                buffer.clone(),
 1178                style.font(),
 1179                font_size,
 1180                None,
 1181                show_excerpt_controls,
 1182                FILE_HEADER_HEIGHT,
 1183                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1184                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1185                fold_placeholder,
 1186                cx,
 1187            )
 1188        });
 1189
 1190        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1191
 1192        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1193
 1194        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1195            .then(|| language_settings::SoftWrap::None);
 1196
 1197        let mut project_subscriptions = Vec::new();
 1198        if mode == EditorMode::Full {
 1199            if let Some(project) = project.as_ref() {
 1200                if buffer.read(cx).is_singleton() {
 1201                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1202                        cx.emit(EditorEvent::TitleChanged);
 1203                    }));
 1204                }
 1205                project_subscriptions.push(cx.subscribe_in(
 1206                    project,
 1207                    window,
 1208                    |editor, _, event, window, cx| {
 1209                        if let project::Event::RefreshInlayHints = event {
 1210                            editor
 1211                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1212                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1213                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1214                                let focus_handle = editor.focus_handle(cx);
 1215                                if focus_handle.is_focused(window) {
 1216                                    let snapshot = buffer.read(cx).snapshot();
 1217                                    for (range, snippet) in snippet_edits {
 1218                                        let editor_range =
 1219                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1220                                        editor
 1221                                            .insert_snippet(
 1222                                                &[editor_range],
 1223                                                snippet.clone(),
 1224                                                window,
 1225                                                cx,
 1226                                            )
 1227                                            .ok();
 1228                                    }
 1229                                }
 1230                            }
 1231                        }
 1232                    },
 1233                ));
 1234                if let Some(task_inventory) = project
 1235                    .read(cx)
 1236                    .task_store()
 1237                    .read(cx)
 1238                    .task_inventory()
 1239                    .cloned()
 1240                {
 1241                    project_subscriptions.push(cx.observe_in(
 1242                        &task_inventory,
 1243                        window,
 1244                        |editor, _, window, cx| {
 1245                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1246                        },
 1247                    ));
 1248                }
 1249            }
 1250        }
 1251
 1252        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1253
 1254        let inlay_hint_settings =
 1255            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1256        let focus_handle = cx.focus_handle();
 1257        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1258            .detach();
 1259        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1260            .detach();
 1261        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1262            .detach();
 1263        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1264            .detach();
 1265
 1266        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1267            Some(false)
 1268        } else {
 1269            None
 1270        };
 1271
 1272        let mut code_action_providers = Vec::new();
 1273        let mut load_uncommitted_diff = None;
 1274        if let Some(project) = project.clone() {
 1275            load_uncommitted_diff = Some(
 1276                get_uncommitted_diff_for_buffer(
 1277                    &project,
 1278                    buffer.read(cx).all_buffers(),
 1279                    buffer.clone(),
 1280                    cx,
 1281                )
 1282                .shared(),
 1283            );
 1284            code_action_providers.push(Rc::new(project) as Rc<_>);
 1285        }
 1286
 1287        let mut this = Self {
 1288            focus_handle,
 1289            show_cursor_when_unfocused: false,
 1290            last_focused_descendant: None,
 1291            buffer: buffer.clone(),
 1292            display_map: display_map.clone(),
 1293            selections,
 1294            scroll_manager: ScrollManager::new(cx),
 1295            columnar_selection_tail: None,
 1296            add_selections_state: None,
 1297            select_next_state: None,
 1298            select_prev_state: None,
 1299            selection_history: Default::default(),
 1300            autoclose_regions: Default::default(),
 1301            snippet_stack: Default::default(),
 1302            select_larger_syntax_node_stack: Vec::new(),
 1303            ime_transaction: Default::default(),
 1304            active_diagnostics: None,
 1305            soft_wrap_mode_override,
 1306            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1307            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1308            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1309            project,
 1310            blink_manager: blink_manager.clone(),
 1311            show_local_selections: true,
 1312            show_scrollbars: true,
 1313            mode,
 1314            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1315            show_gutter: mode == EditorMode::Full,
 1316            show_line_numbers: None,
 1317            use_relative_line_numbers: None,
 1318            show_git_diff_gutter: None,
 1319            show_code_actions: None,
 1320            show_runnables: None,
 1321            show_wrap_guides: None,
 1322            show_indent_guides,
 1323            placeholder_text: None,
 1324            highlight_order: 0,
 1325            highlighted_rows: HashMap::default(),
 1326            background_highlights: Default::default(),
 1327            gutter_highlights: TreeMap::default(),
 1328            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1329            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1330            nav_history: None,
 1331            context_menu: RefCell::new(None),
 1332            mouse_context_menu: None,
 1333            completion_tasks: Default::default(),
 1334            signature_help_state: SignatureHelpState::default(),
 1335            auto_signature_help: None,
 1336            find_all_references_task_sources: Vec::new(),
 1337            next_completion_id: 0,
 1338            next_inlay_id: 0,
 1339            code_action_providers,
 1340            available_code_actions: Default::default(),
 1341            code_actions_task: Default::default(),
 1342            selection_highlight_task: Default::default(),
 1343            document_highlights_task: Default::default(),
 1344            linked_editing_range_task: Default::default(),
 1345            pending_rename: Default::default(),
 1346            searchable: true,
 1347            cursor_shape: EditorSettings::get_global(cx)
 1348                .cursor_shape
 1349                .unwrap_or_default(),
 1350            current_line_highlight: None,
 1351            autoindent_mode: Some(AutoindentMode::EachLine),
 1352            collapse_matches: false,
 1353            workspace: None,
 1354            input_enabled: true,
 1355            use_modal_editing: mode == EditorMode::Full,
 1356            read_only: false,
 1357            use_autoclose: true,
 1358            use_auto_surround: true,
 1359            auto_replace_emoji_shortcode: false,
 1360            leader_peer_id: None,
 1361            remote_id: None,
 1362            hover_state: Default::default(),
 1363            pending_mouse_down: None,
 1364            hovered_link_state: Default::default(),
 1365            edit_prediction_provider: None,
 1366            active_inline_completion: None,
 1367            stale_inline_completion_in_menu: None,
 1368            edit_prediction_preview: EditPredictionPreview::Inactive,
 1369            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1370
 1371            gutter_hovered: false,
 1372            pixel_position_of_newest_cursor: None,
 1373            last_bounds: None,
 1374            last_position_map: None,
 1375            expect_bounds_change: None,
 1376            gutter_dimensions: GutterDimensions::default(),
 1377            style: None,
 1378            show_cursor_names: false,
 1379            hovered_cursors: Default::default(),
 1380            next_editor_action_id: EditorActionId::default(),
 1381            editor_actions: Rc::default(),
 1382            inline_completions_hidden_for_vim_mode: false,
 1383            show_inline_completions_override: None,
 1384            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1385            edit_prediction_settings: EditPredictionSettings::Disabled,
 1386            edit_prediction_cursor_on_leading_whitespace: false,
 1387            edit_prediction_requires_modifier_in_leading_space: true,
 1388            custom_context_menu: None,
 1389            show_git_blame_gutter: false,
 1390            show_git_blame_inline: false,
 1391            distinguish_unstaged_diff_hunks: false,
 1392            show_selection_menu: None,
 1393            show_git_blame_inline_delay_task: None,
 1394            git_blame_inline_tooltip: None,
 1395            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1396            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1397                .session
 1398                .restore_unsaved_buffers,
 1399            blame: None,
 1400            blame_subscription: None,
 1401            tasks: Default::default(),
 1402            _subscriptions: vec![
 1403                cx.observe(&buffer, Self::on_buffer_changed),
 1404                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1405                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1406                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1407                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1408                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1409                cx.observe_window_activation(window, |editor, window, cx| {
 1410                    let active = window.is_window_active();
 1411                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1412                        if active {
 1413                            blink_manager.enable(cx);
 1414                        } else {
 1415                            blink_manager.disable(cx);
 1416                        }
 1417                    });
 1418                }),
 1419            ],
 1420            tasks_update_task: None,
 1421            linked_edit_ranges: Default::default(),
 1422            in_project_search: false,
 1423            previous_search_ranges: None,
 1424            breadcrumb_header: None,
 1425            focused_block: None,
 1426            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1427            addons: HashMap::default(),
 1428            registered_buffers: HashMap::default(),
 1429            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1430            selection_mark_mode: false,
 1431            toggle_fold_multiple_buffers: Task::ready(()),
 1432            serialize_selections: Task::ready(()),
 1433            text_style_refinement: None,
 1434            load_diff_task: load_uncommitted_diff,
 1435        };
 1436        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1437        this._subscriptions.extend(project_subscriptions);
 1438
 1439        this.end_selection(window, cx);
 1440        this.scroll_manager.show_scrollbar(window, cx);
 1441
 1442        if mode == EditorMode::Full {
 1443            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1444            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1445
 1446            if this.git_blame_inline_enabled {
 1447                this.git_blame_inline_enabled = true;
 1448                this.start_git_blame_inline(false, window, cx);
 1449            }
 1450
 1451            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1452                if let Some(project) = this.project.as_ref() {
 1453                    let handle = project.update(cx, |project, cx| {
 1454                        project.register_buffer_with_language_servers(&buffer, cx)
 1455                    });
 1456                    this.registered_buffers
 1457                        .insert(buffer.read(cx).remote_id(), handle);
 1458                }
 1459            }
 1460        }
 1461
 1462        this.report_editor_event("Editor Opened", None, cx);
 1463        this
 1464    }
 1465
 1466    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1467        self.mouse_context_menu
 1468            .as_ref()
 1469            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1470    }
 1471
 1472    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1473        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1474    }
 1475
 1476    fn key_context_internal(
 1477        &self,
 1478        has_active_edit_prediction: bool,
 1479        window: &Window,
 1480        cx: &App,
 1481    ) -> KeyContext {
 1482        let mut key_context = KeyContext::new_with_defaults();
 1483        key_context.add("Editor");
 1484        let mode = match self.mode {
 1485            EditorMode::SingleLine { .. } => "single_line",
 1486            EditorMode::AutoHeight { .. } => "auto_height",
 1487            EditorMode::Full => "full",
 1488        };
 1489
 1490        if EditorSettings::jupyter_enabled(cx) {
 1491            key_context.add("jupyter");
 1492        }
 1493
 1494        key_context.set("mode", mode);
 1495        if self.pending_rename.is_some() {
 1496            key_context.add("renaming");
 1497        }
 1498
 1499        match self.context_menu.borrow().as_ref() {
 1500            Some(CodeContextMenu::Completions(_)) => {
 1501                key_context.add("menu");
 1502                key_context.add("showing_completions");
 1503            }
 1504            Some(CodeContextMenu::CodeActions(_)) => {
 1505                key_context.add("menu");
 1506                key_context.add("showing_code_actions")
 1507            }
 1508            None => {}
 1509        }
 1510
 1511        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1512        if !self.focus_handle(cx).contains_focused(window, cx)
 1513            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1514        {
 1515            for addon in self.addons.values() {
 1516                addon.extend_key_context(&mut key_context, cx)
 1517            }
 1518        }
 1519
 1520        if let Some(extension) = self
 1521            .buffer
 1522            .read(cx)
 1523            .as_singleton()
 1524            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1525        {
 1526            key_context.set("extension", extension.to_string());
 1527        }
 1528
 1529        if has_active_edit_prediction {
 1530            if self.edit_prediction_in_conflict() {
 1531                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1532            } else {
 1533                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1534                key_context.add("copilot_suggestion");
 1535            }
 1536        }
 1537
 1538        if self.selection_mark_mode {
 1539            key_context.add("selection_mode");
 1540        }
 1541
 1542        key_context
 1543    }
 1544
 1545    pub fn edit_prediction_in_conflict(&self) -> bool {
 1546        if !self.show_edit_predictions_in_menu() {
 1547            return false;
 1548        }
 1549
 1550        let showing_completions = self
 1551            .context_menu
 1552            .borrow()
 1553            .as_ref()
 1554            .map_or(false, |context| {
 1555                matches!(context, CodeContextMenu::Completions(_))
 1556            });
 1557
 1558        showing_completions
 1559            || self.edit_prediction_requires_modifier()
 1560            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1561            // bindings to insert tab characters.
 1562            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1563    }
 1564
 1565    pub fn accept_edit_prediction_keybind(
 1566        &self,
 1567        window: &Window,
 1568        cx: &App,
 1569    ) -> AcceptEditPredictionBinding {
 1570        let key_context = self.key_context_internal(true, window, cx);
 1571        let in_conflict = self.edit_prediction_in_conflict();
 1572
 1573        AcceptEditPredictionBinding(
 1574            window
 1575                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1576                .into_iter()
 1577                .filter(|binding| {
 1578                    !in_conflict
 1579                        || binding
 1580                            .keystrokes()
 1581                            .first()
 1582                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1583                })
 1584                .rev()
 1585                .min_by_key(|binding| {
 1586                    binding
 1587                        .keystrokes()
 1588                        .first()
 1589                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1590                }),
 1591        )
 1592    }
 1593
 1594    pub fn new_file(
 1595        workspace: &mut Workspace,
 1596        _: &workspace::NewFile,
 1597        window: &mut Window,
 1598        cx: &mut Context<Workspace>,
 1599    ) {
 1600        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1601            "Failed to create buffer",
 1602            window,
 1603            cx,
 1604            |e, _, _| match e.error_code() {
 1605                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1606                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1607                e.error_tag("required").unwrap_or("the latest version")
 1608            )),
 1609                _ => None,
 1610            },
 1611        );
 1612    }
 1613
 1614    pub fn new_in_workspace(
 1615        workspace: &mut Workspace,
 1616        window: &mut Window,
 1617        cx: &mut Context<Workspace>,
 1618    ) -> Task<Result<Entity<Editor>>> {
 1619        let project = workspace.project().clone();
 1620        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1621
 1622        cx.spawn_in(window, |workspace, mut cx| async move {
 1623            let buffer = create.await?;
 1624            workspace.update_in(&mut cx, |workspace, window, cx| {
 1625                let editor =
 1626                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1627                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1628                editor
 1629            })
 1630        })
 1631    }
 1632
 1633    fn new_file_vertical(
 1634        workspace: &mut Workspace,
 1635        _: &workspace::NewFileSplitVertical,
 1636        window: &mut Window,
 1637        cx: &mut Context<Workspace>,
 1638    ) {
 1639        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1640    }
 1641
 1642    fn new_file_horizontal(
 1643        workspace: &mut Workspace,
 1644        _: &workspace::NewFileSplitHorizontal,
 1645        window: &mut Window,
 1646        cx: &mut Context<Workspace>,
 1647    ) {
 1648        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1649    }
 1650
 1651    fn new_file_in_direction(
 1652        workspace: &mut Workspace,
 1653        direction: SplitDirection,
 1654        window: &mut Window,
 1655        cx: &mut Context<Workspace>,
 1656    ) {
 1657        let project = workspace.project().clone();
 1658        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1659
 1660        cx.spawn_in(window, |workspace, mut cx| async move {
 1661            let buffer = create.await?;
 1662            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1663                workspace.split_item(
 1664                    direction,
 1665                    Box::new(
 1666                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1667                    ),
 1668                    window,
 1669                    cx,
 1670                )
 1671            })?;
 1672            anyhow::Ok(())
 1673        })
 1674        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1675            match e.error_code() {
 1676                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1677                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1678                e.error_tag("required").unwrap_or("the latest version")
 1679            )),
 1680                _ => None,
 1681            }
 1682        });
 1683    }
 1684
 1685    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1686        self.leader_peer_id
 1687    }
 1688
 1689    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1690        &self.buffer
 1691    }
 1692
 1693    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1694        self.workspace.as_ref()?.0.upgrade()
 1695    }
 1696
 1697    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1698        self.buffer().read(cx).title(cx)
 1699    }
 1700
 1701    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1702        let git_blame_gutter_max_author_length = self
 1703            .render_git_blame_gutter(cx)
 1704            .then(|| {
 1705                if let Some(blame) = self.blame.as_ref() {
 1706                    let max_author_length =
 1707                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1708                    Some(max_author_length)
 1709                } else {
 1710                    None
 1711                }
 1712            })
 1713            .flatten();
 1714
 1715        EditorSnapshot {
 1716            mode: self.mode,
 1717            show_gutter: self.show_gutter,
 1718            show_line_numbers: self.show_line_numbers,
 1719            show_git_diff_gutter: self.show_git_diff_gutter,
 1720            show_code_actions: self.show_code_actions,
 1721            show_runnables: self.show_runnables,
 1722            git_blame_gutter_max_author_length,
 1723            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1724            scroll_anchor: self.scroll_manager.anchor(),
 1725            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1726            placeholder_text: self.placeholder_text.clone(),
 1727            is_focused: self.focus_handle.is_focused(window),
 1728            current_line_highlight: self
 1729                .current_line_highlight
 1730                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1731            gutter_hovered: self.gutter_hovered,
 1732        }
 1733    }
 1734
 1735    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1736        self.buffer.read(cx).language_at(point, cx)
 1737    }
 1738
 1739    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1740        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1741    }
 1742
 1743    pub fn active_excerpt(
 1744        &self,
 1745        cx: &App,
 1746    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1747        self.buffer
 1748            .read(cx)
 1749            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1750    }
 1751
 1752    pub fn mode(&self) -> EditorMode {
 1753        self.mode
 1754    }
 1755
 1756    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1757        self.collaboration_hub.as_deref()
 1758    }
 1759
 1760    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1761        self.collaboration_hub = Some(hub);
 1762    }
 1763
 1764    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1765        self.in_project_search = in_project_search;
 1766    }
 1767
 1768    pub fn set_custom_context_menu(
 1769        &mut self,
 1770        f: impl 'static
 1771            + Fn(
 1772                &mut Self,
 1773                DisplayPoint,
 1774                &mut Window,
 1775                &mut Context<Self>,
 1776            ) -> Option<Entity<ui::ContextMenu>>,
 1777    ) {
 1778        self.custom_context_menu = Some(Box::new(f))
 1779    }
 1780
 1781    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1782        self.completion_provider = provider;
 1783    }
 1784
 1785    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1786        self.semantics_provider.clone()
 1787    }
 1788
 1789    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1790        self.semantics_provider = provider;
 1791    }
 1792
 1793    pub fn set_edit_prediction_provider<T>(
 1794        &mut self,
 1795        provider: Option<Entity<T>>,
 1796        window: &mut Window,
 1797        cx: &mut Context<Self>,
 1798    ) where
 1799        T: EditPredictionProvider,
 1800    {
 1801        self.edit_prediction_provider =
 1802            provider.map(|provider| RegisteredInlineCompletionProvider {
 1803                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1804                    if this.focus_handle.is_focused(window) {
 1805                        this.update_visible_inline_completion(window, cx);
 1806                    }
 1807                }),
 1808                provider: Arc::new(provider),
 1809            });
 1810        self.refresh_inline_completion(false, false, window, cx);
 1811    }
 1812
 1813    pub fn placeholder_text(&self) -> Option<&str> {
 1814        self.placeholder_text.as_deref()
 1815    }
 1816
 1817    pub fn set_placeholder_text(
 1818        &mut self,
 1819        placeholder_text: impl Into<Arc<str>>,
 1820        cx: &mut Context<Self>,
 1821    ) {
 1822        let placeholder_text = Some(placeholder_text.into());
 1823        if self.placeholder_text != placeholder_text {
 1824            self.placeholder_text = placeholder_text;
 1825            cx.notify();
 1826        }
 1827    }
 1828
 1829    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1830        self.cursor_shape = cursor_shape;
 1831
 1832        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1833        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1834
 1835        cx.notify();
 1836    }
 1837
 1838    pub fn set_current_line_highlight(
 1839        &mut self,
 1840        current_line_highlight: Option<CurrentLineHighlight>,
 1841    ) {
 1842        self.current_line_highlight = current_line_highlight;
 1843    }
 1844
 1845    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1846        self.collapse_matches = collapse_matches;
 1847    }
 1848
 1849    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1850        let buffers = self.buffer.read(cx).all_buffers();
 1851        let Some(project) = self.project.as_ref() else {
 1852            return;
 1853        };
 1854        project.update(cx, |project, cx| {
 1855            for buffer in buffers {
 1856                self.registered_buffers
 1857                    .entry(buffer.read(cx).remote_id())
 1858                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1859            }
 1860        })
 1861    }
 1862
 1863    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1864        if self.collapse_matches {
 1865            return range.start..range.start;
 1866        }
 1867        range.clone()
 1868    }
 1869
 1870    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1871        if self.display_map.read(cx).clip_at_line_ends != clip {
 1872            self.display_map
 1873                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1874        }
 1875    }
 1876
 1877    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1878        self.input_enabled = input_enabled;
 1879    }
 1880
 1881    pub fn set_inline_completions_hidden_for_vim_mode(
 1882        &mut self,
 1883        hidden: bool,
 1884        window: &mut Window,
 1885        cx: &mut Context<Self>,
 1886    ) {
 1887        if hidden != self.inline_completions_hidden_for_vim_mode {
 1888            self.inline_completions_hidden_for_vim_mode = hidden;
 1889            if hidden {
 1890                self.update_visible_inline_completion(window, cx);
 1891            } else {
 1892                self.refresh_inline_completion(true, false, window, cx);
 1893            }
 1894        }
 1895    }
 1896
 1897    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1898        self.menu_inline_completions_policy = value;
 1899    }
 1900
 1901    pub fn set_autoindent(&mut self, autoindent: bool) {
 1902        if autoindent {
 1903            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1904        } else {
 1905            self.autoindent_mode = None;
 1906        }
 1907    }
 1908
 1909    pub fn read_only(&self, cx: &App) -> bool {
 1910        self.read_only || self.buffer.read(cx).read_only()
 1911    }
 1912
 1913    pub fn set_read_only(&mut self, read_only: bool) {
 1914        self.read_only = read_only;
 1915    }
 1916
 1917    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1918        self.use_autoclose = autoclose;
 1919    }
 1920
 1921    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1922        self.use_auto_surround = auto_surround;
 1923    }
 1924
 1925    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1926        self.auto_replace_emoji_shortcode = auto_replace;
 1927    }
 1928
 1929    pub fn toggle_inline_completions(
 1930        &mut self,
 1931        _: &ToggleEditPrediction,
 1932        window: &mut Window,
 1933        cx: &mut Context<Self>,
 1934    ) {
 1935        if self.show_inline_completions_override.is_some() {
 1936            self.set_show_edit_predictions(None, window, cx);
 1937        } else {
 1938            let show_edit_predictions = !self.edit_predictions_enabled();
 1939            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1940        }
 1941    }
 1942
 1943    pub fn set_show_edit_predictions(
 1944        &mut self,
 1945        show_edit_predictions: Option<bool>,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        self.show_inline_completions_override = show_edit_predictions;
 1950        self.refresh_inline_completion(false, true, window, cx);
 1951    }
 1952
 1953    fn inline_completions_disabled_in_scope(
 1954        &self,
 1955        buffer: &Entity<Buffer>,
 1956        buffer_position: language::Anchor,
 1957        cx: &App,
 1958    ) -> bool {
 1959        let snapshot = buffer.read(cx).snapshot();
 1960        let settings = snapshot.settings_at(buffer_position, cx);
 1961
 1962        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1963            return false;
 1964        };
 1965
 1966        scope.override_name().map_or(false, |scope_name| {
 1967            settings
 1968                .edit_predictions_disabled_in
 1969                .iter()
 1970                .any(|s| s == scope_name)
 1971        })
 1972    }
 1973
 1974    pub fn set_use_modal_editing(&mut self, to: bool) {
 1975        self.use_modal_editing = to;
 1976    }
 1977
 1978    pub fn use_modal_editing(&self) -> bool {
 1979        self.use_modal_editing
 1980    }
 1981
 1982    fn selections_did_change(
 1983        &mut self,
 1984        local: bool,
 1985        old_cursor_position: &Anchor,
 1986        show_completions: bool,
 1987        window: &mut Window,
 1988        cx: &mut Context<Self>,
 1989    ) {
 1990        window.invalidate_character_coordinates();
 1991
 1992        // Copy selections to primary selection buffer
 1993        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1994        if local {
 1995            let selections = self.selections.all::<usize>(cx);
 1996            let buffer_handle = self.buffer.read(cx).read(cx);
 1997
 1998            let mut text = String::new();
 1999            for (index, selection) in selections.iter().enumerate() {
 2000                let text_for_selection = buffer_handle
 2001                    .text_for_range(selection.start..selection.end)
 2002                    .collect::<String>();
 2003
 2004                text.push_str(&text_for_selection);
 2005                if index != selections.len() - 1 {
 2006                    text.push('\n');
 2007                }
 2008            }
 2009
 2010            if !text.is_empty() {
 2011                cx.write_to_primary(ClipboardItem::new_string(text));
 2012            }
 2013        }
 2014
 2015        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2016            self.buffer.update(cx, |buffer, cx| {
 2017                buffer.set_active_selections(
 2018                    &self.selections.disjoint_anchors(),
 2019                    self.selections.line_mode,
 2020                    self.cursor_shape,
 2021                    cx,
 2022                )
 2023            });
 2024        }
 2025        let display_map = self
 2026            .display_map
 2027            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2028        let buffer = &display_map.buffer_snapshot;
 2029        self.add_selections_state = None;
 2030        self.select_next_state = None;
 2031        self.select_prev_state = None;
 2032        self.select_larger_syntax_node_stack.clear();
 2033        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2034        self.snippet_stack
 2035            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2036        self.take_rename(false, window, cx);
 2037
 2038        let new_cursor_position = self.selections.newest_anchor().head();
 2039
 2040        self.push_to_nav_history(
 2041            *old_cursor_position,
 2042            Some(new_cursor_position.to_point(buffer)),
 2043            cx,
 2044        );
 2045
 2046        if local {
 2047            let new_cursor_position = self.selections.newest_anchor().head();
 2048            let mut context_menu = self.context_menu.borrow_mut();
 2049            let completion_menu = match context_menu.as_ref() {
 2050                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2051                _ => {
 2052                    *context_menu = None;
 2053                    None
 2054                }
 2055            };
 2056            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2057                if !self.registered_buffers.contains_key(&buffer_id) {
 2058                    if let Some(project) = self.project.as_ref() {
 2059                        project.update(cx, |project, cx| {
 2060                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2061                                return;
 2062                            };
 2063                            self.registered_buffers.insert(
 2064                                buffer_id,
 2065                                project.register_buffer_with_language_servers(&buffer, cx),
 2066                            );
 2067                        })
 2068                    }
 2069                }
 2070            }
 2071
 2072            if let Some(completion_menu) = completion_menu {
 2073                let cursor_position = new_cursor_position.to_offset(buffer);
 2074                let (word_range, kind) =
 2075                    buffer.surrounding_word(completion_menu.initial_position, true);
 2076                if kind == Some(CharKind::Word)
 2077                    && word_range.to_inclusive().contains(&cursor_position)
 2078                {
 2079                    let mut completion_menu = completion_menu.clone();
 2080                    drop(context_menu);
 2081
 2082                    let query = Self::completion_query(buffer, cursor_position);
 2083                    cx.spawn(move |this, mut cx| async move {
 2084                        completion_menu
 2085                            .filter(query.as_deref(), cx.background_executor().clone())
 2086                            .await;
 2087
 2088                        this.update(&mut cx, |this, cx| {
 2089                            let mut context_menu = this.context_menu.borrow_mut();
 2090                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2091                            else {
 2092                                return;
 2093                            };
 2094
 2095                            if menu.id > completion_menu.id {
 2096                                return;
 2097                            }
 2098
 2099                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2100                            drop(context_menu);
 2101                            cx.notify();
 2102                        })
 2103                    })
 2104                    .detach();
 2105
 2106                    if show_completions {
 2107                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2108                    }
 2109                } else {
 2110                    drop(context_menu);
 2111                    self.hide_context_menu(window, cx);
 2112                }
 2113            } else {
 2114                drop(context_menu);
 2115            }
 2116
 2117            hide_hover(self, cx);
 2118
 2119            if old_cursor_position.to_display_point(&display_map).row()
 2120                != new_cursor_position.to_display_point(&display_map).row()
 2121            {
 2122                self.available_code_actions.take();
 2123            }
 2124            self.refresh_code_actions(window, cx);
 2125            self.refresh_document_highlights(cx);
 2126            self.refresh_selected_text_highlights(window, cx);
 2127            refresh_matching_bracket_highlights(self, window, cx);
 2128            self.update_visible_inline_completion(window, cx);
 2129            self.edit_prediction_requires_modifier_in_leading_space = true;
 2130            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2131            if self.git_blame_inline_enabled {
 2132                self.start_inline_blame_timer(window, cx);
 2133            }
 2134        }
 2135
 2136        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2137        cx.emit(EditorEvent::SelectionsChanged { local });
 2138
 2139        let selections = &self.selections.disjoint;
 2140        if selections.len() == 1 {
 2141            cx.emit(SearchEvent::ActiveMatchChanged)
 2142        }
 2143        if local
 2144            && self.is_singleton(cx)
 2145            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2146        {
 2147            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2148                let background_executor = cx.background_executor().clone();
 2149                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2150                let snapshot = self.buffer().read(cx).snapshot(cx);
 2151                let selections = selections.clone();
 2152                self.serialize_selections = cx.background_spawn(async move {
 2153                    background_executor.timer(Duration::from_millis(100)).await;
 2154                    let selections = selections
 2155                        .iter()
 2156                        .map(|selection| {
 2157                            (
 2158                                selection.start.to_offset(&snapshot),
 2159                                selection.end.to_offset(&snapshot),
 2160                            )
 2161                        })
 2162                        .collect();
 2163                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2164                        .await
 2165                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2166                        .log_err();
 2167                });
 2168            }
 2169        }
 2170
 2171        cx.notify();
 2172    }
 2173
 2174    pub fn change_selections<R>(
 2175        &mut self,
 2176        autoscroll: Option<Autoscroll>,
 2177        window: &mut Window,
 2178        cx: &mut Context<Self>,
 2179        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2180    ) -> R {
 2181        self.change_selections_inner(autoscroll, true, window, cx, change)
 2182    }
 2183
 2184    fn change_selections_inner<R>(
 2185        &mut self,
 2186        autoscroll: Option<Autoscroll>,
 2187        request_completions: bool,
 2188        window: &mut Window,
 2189        cx: &mut Context<Self>,
 2190        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2191    ) -> R {
 2192        let old_cursor_position = self.selections.newest_anchor().head();
 2193        self.push_to_selection_history();
 2194
 2195        let (changed, result) = self.selections.change_with(cx, change);
 2196
 2197        if changed {
 2198            if let Some(autoscroll) = autoscroll {
 2199                self.request_autoscroll(autoscroll, cx);
 2200            }
 2201            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2202
 2203            if self.should_open_signature_help_automatically(
 2204                &old_cursor_position,
 2205                self.signature_help_state.backspace_pressed(),
 2206                cx,
 2207            ) {
 2208                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2209            }
 2210            self.signature_help_state.set_backspace_pressed(false);
 2211        }
 2212
 2213        result
 2214    }
 2215
 2216    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2217    where
 2218        I: IntoIterator<Item = (Range<S>, T)>,
 2219        S: ToOffset,
 2220        T: Into<Arc<str>>,
 2221    {
 2222        if self.read_only(cx) {
 2223            return;
 2224        }
 2225
 2226        self.buffer
 2227            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2228    }
 2229
 2230    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2231    where
 2232        I: IntoIterator<Item = (Range<S>, T)>,
 2233        S: ToOffset,
 2234        T: Into<Arc<str>>,
 2235    {
 2236        if self.read_only(cx) {
 2237            return;
 2238        }
 2239
 2240        self.buffer.update(cx, |buffer, cx| {
 2241            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2242        });
 2243    }
 2244
 2245    pub fn edit_with_block_indent<I, S, T>(
 2246        &mut self,
 2247        edits: I,
 2248        original_indent_columns: Vec<u32>,
 2249        cx: &mut Context<Self>,
 2250    ) where
 2251        I: IntoIterator<Item = (Range<S>, T)>,
 2252        S: ToOffset,
 2253        T: Into<Arc<str>>,
 2254    {
 2255        if self.read_only(cx) {
 2256            return;
 2257        }
 2258
 2259        self.buffer.update(cx, |buffer, cx| {
 2260            buffer.edit(
 2261                edits,
 2262                Some(AutoindentMode::Block {
 2263                    original_indent_columns,
 2264                }),
 2265                cx,
 2266            )
 2267        });
 2268    }
 2269
 2270    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2271        self.hide_context_menu(window, cx);
 2272
 2273        match phase {
 2274            SelectPhase::Begin {
 2275                position,
 2276                add,
 2277                click_count,
 2278            } => self.begin_selection(position, add, click_count, window, cx),
 2279            SelectPhase::BeginColumnar {
 2280                position,
 2281                goal_column,
 2282                reset,
 2283            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2284            SelectPhase::Extend {
 2285                position,
 2286                click_count,
 2287            } => self.extend_selection(position, click_count, window, cx),
 2288            SelectPhase::Update {
 2289                position,
 2290                goal_column,
 2291                scroll_delta,
 2292            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2293            SelectPhase::End => self.end_selection(window, cx),
 2294        }
 2295    }
 2296
 2297    fn extend_selection(
 2298        &mut self,
 2299        position: DisplayPoint,
 2300        click_count: usize,
 2301        window: &mut Window,
 2302        cx: &mut Context<Self>,
 2303    ) {
 2304        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2305        let tail = self.selections.newest::<usize>(cx).tail();
 2306        self.begin_selection(position, false, click_count, window, cx);
 2307
 2308        let position = position.to_offset(&display_map, Bias::Left);
 2309        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2310
 2311        let mut pending_selection = self
 2312            .selections
 2313            .pending_anchor()
 2314            .expect("extend_selection not called with pending selection");
 2315        if position >= tail {
 2316            pending_selection.start = tail_anchor;
 2317        } else {
 2318            pending_selection.end = tail_anchor;
 2319            pending_selection.reversed = true;
 2320        }
 2321
 2322        let mut pending_mode = self.selections.pending_mode().unwrap();
 2323        match &mut pending_mode {
 2324            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2325            _ => {}
 2326        }
 2327
 2328        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2329            s.set_pending(pending_selection, pending_mode)
 2330        });
 2331    }
 2332
 2333    fn begin_selection(
 2334        &mut self,
 2335        position: DisplayPoint,
 2336        add: bool,
 2337        click_count: usize,
 2338        window: &mut Window,
 2339        cx: &mut Context<Self>,
 2340    ) {
 2341        if !self.focus_handle.is_focused(window) {
 2342            self.last_focused_descendant = None;
 2343            window.focus(&self.focus_handle);
 2344        }
 2345
 2346        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2347        let buffer = &display_map.buffer_snapshot;
 2348        let newest_selection = self.selections.newest_anchor().clone();
 2349        let position = display_map.clip_point(position, Bias::Left);
 2350
 2351        let start;
 2352        let end;
 2353        let mode;
 2354        let mut auto_scroll;
 2355        match click_count {
 2356            1 => {
 2357                start = buffer.anchor_before(position.to_point(&display_map));
 2358                end = start;
 2359                mode = SelectMode::Character;
 2360                auto_scroll = true;
 2361            }
 2362            2 => {
 2363                let range = movement::surrounding_word(&display_map, position);
 2364                start = buffer.anchor_before(range.start.to_point(&display_map));
 2365                end = buffer.anchor_before(range.end.to_point(&display_map));
 2366                mode = SelectMode::Word(start..end);
 2367                auto_scroll = true;
 2368            }
 2369            3 => {
 2370                let position = display_map
 2371                    .clip_point(position, Bias::Left)
 2372                    .to_point(&display_map);
 2373                let line_start = display_map.prev_line_boundary(position).0;
 2374                let next_line_start = buffer.clip_point(
 2375                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2376                    Bias::Left,
 2377                );
 2378                start = buffer.anchor_before(line_start);
 2379                end = buffer.anchor_before(next_line_start);
 2380                mode = SelectMode::Line(start..end);
 2381                auto_scroll = true;
 2382            }
 2383            _ => {
 2384                start = buffer.anchor_before(0);
 2385                end = buffer.anchor_before(buffer.len());
 2386                mode = SelectMode::All;
 2387                auto_scroll = false;
 2388            }
 2389        }
 2390        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2391
 2392        let point_to_delete: Option<usize> = {
 2393            let selected_points: Vec<Selection<Point>> =
 2394                self.selections.disjoint_in_range(start..end, cx);
 2395
 2396            if !add || click_count > 1 {
 2397                None
 2398            } else if !selected_points.is_empty() {
 2399                Some(selected_points[0].id)
 2400            } else {
 2401                let clicked_point_already_selected =
 2402                    self.selections.disjoint.iter().find(|selection| {
 2403                        selection.start.to_point(buffer) == start.to_point(buffer)
 2404                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2405                    });
 2406
 2407                clicked_point_already_selected.map(|selection| selection.id)
 2408            }
 2409        };
 2410
 2411        let selections_count = self.selections.count();
 2412
 2413        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2414            if let Some(point_to_delete) = point_to_delete {
 2415                s.delete(point_to_delete);
 2416
 2417                if selections_count == 1 {
 2418                    s.set_pending_anchor_range(start..end, mode);
 2419                }
 2420            } else {
 2421                if !add {
 2422                    s.clear_disjoint();
 2423                } else if click_count > 1 {
 2424                    s.delete(newest_selection.id)
 2425                }
 2426
 2427                s.set_pending_anchor_range(start..end, mode);
 2428            }
 2429        });
 2430    }
 2431
 2432    fn begin_columnar_selection(
 2433        &mut self,
 2434        position: DisplayPoint,
 2435        goal_column: u32,
 2436        reset: bool,
 2437        window: &mut Window,
 2438        cx: &mut Context<Self>,
 2439    ) {
 2440        if !self.focus_handle.is_focused(window) {
 2441            self.last_focused_descendant = None;
 2442            window.focus(&self.focus_handle);
 2443        }
 2444
 2445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2446
 2447        if reset {
 2448            let pointer_position = display_map
 2449                .buffer_snapshot
 2450                .anchor_before(position.to_point(&display_map));
 2451
 2452            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2453                s.clear_disjoint();
 2454                s.set_pending_anchor_range(
 2455                    pointer_position..pointer_position,
 2456                    SelectMode::Character,
 2457                );
 2458            });
 2459        }
 2460
 2461        let tail = self.selections.newest::<Point>(cx).tail();
 2462        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2463
 2464        if !reset {
 2465            self.select_columns(
 2466                tail.to_display_point(&display_map),
 2467                position,
 2468                goal_column,
 2469                &display_map,
 2470                window,
 2471                cx,
 2472            );
 2473        }
 2474    }
 2475
 2476    fn update_selection(
 2477        &mut self,
 2478        position: DisplayPoint,
 2479        goal_column: u32,
 2480        scroll_delta: gpui::Point<f32>,
 2481        window: &mut Window,
 2482        cx: &mut Context<Self>,
 2483    ) {
 2484        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2485
 2486        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2487            let tail = tail.to_display_point(&display_map);
 2488            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2489        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2490            let buffer = self.buffer.read(cx).snapshot(cx);
 2491            let head;
 2492            let tail;
 2493            let mode = self.selections.pending_mode().unwrap();
 2494            match &mode {
 2495                SelectMode::Character => {
 2496                    head = position.to_point(&display_map);
 2497                    tail = pending.tail().to_point(&buffer);
 2498                }
 2499                SelectMode::Word(original_range) => {
 2500                    let original_display_range = original_range.start.to_display_point(&display_map)
 2501                        ..original_range.end.to_display_point(&display_map);
 2502                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2503                        ..original_display_range.end.to_point(&display_map);
 2504                    if movement::is_inside_word(&display_map, position)
 2505                        || original_display_range.contains(&position)
 2506                    {
 2507                        let word_range = movement::surrounding_word(&display_map, position);
 2508                        if word_range.start < original_display_range.start {
 2509                            head = word_range.start.to_point(&display_map);
 2510                        } else {
 2511                            head = word_range.end.to_point(&display_map);
 2512                        }
 2513                    } else {
 2514                        head = position.to_point(&display_map);
 2515                    }
 2516
 2517                    if head <= original_buffer_range.start {
 2518                        tail = original_buffer_range.end;
 2519                    } else {
 2520                        tail = original_buffer_range.start;
 2521                    }
 2522                }
 2523                SelectMode::Line(original_range) => {
 2524                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2525
 2526                    let position = display_map
 2527                        .clip_point(position, Bias::Left)
 2528                        .to_point(&display_map);
 2529                    let line_start = display_map.prev_line_boundary(position).0;
 2530                    let next_line_start = buffer.clip_point(
 2531                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2532                        Bias::Left,
 2533                    );
 2534
 2535                    if line_start < original_range.start {
 2536                        head = line_start
 2537                    } else {
 2538                        head = next_line_start
 2539                    }
 2540
 2541                    if head <= original_range.start {
 2542                        tail = original_range.end;
 2543                    } else {
 2544                        tail = original_range.start;
 2545                    }
 2546                }
 2547                SelectMode::All => {
 2548                    return;
 2549                }
 2550            };
 2551
 2552            if head < tail {
 2553                pending.start = buffer.anchor_before(head);
 2554                pending.end = buffer.anchor_before(tail);
 2555                pending.reversed = true;
 2556            } else {
 2557                pending.start = buffer.anchor_before(tail);
 2558                pending.end = buffer.anchor_before(head);
 2559                pending.reversed = false;
 2560            }
 2561
 2562            self.change_selections(None, window, cx, |s| {
 2563                s.set_pending(pending, mode);
 2564            });
 2565        } else {
 2566            log::error!("update_selection dispatched with no pending selection");
 2567            return;
 2568        }
 2569
 2570        self.apply_scroll_delta(scroll_delta, window, cx);
 2571        cx.notify();
 2572    }
 2573
 2574    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2575        self.columnar_selection_tail.take();
 2576        if self.selections.pending_anchor().is_some() {
 2577            let selections = self.selections.all::<usize>(cx);
 2578            self.change_selections(None, window, cx, |s| {
 2579                s.select(selections);
 2580                s.clear_pending();
 2581            });
 2582        }
 2583    }
 2584
 2585    fn select_columns(
 2586        &mut self,
 2587        tail: DisplayPoint,
 2588        head: DisplayPoint,
 2589        goal_column: u32,
 2590        display_map: &DisplaySnapshot,
 2591        window: &mut Window,
 2592        cx: &mut Context<Self>,
 2593    ) {
 2594        let start_row = cmp::min(tail.row(), head.row());
 2595        let end_row = cmp::max(tail.row(), head.row());
 2596        let start_column = cmp::min(tail.column(), goal_column);
 2597        let end_column = cmp::max(tail.column(), goal_column);
 2598        let reversed = start_column < tail.column();
 2599
 2600        let selection_ranges = (start_row.0..=end_row.0)
 2601            .map(DisplayRow)
 2602            .filter_map(|row| {
 2603                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2604                    let start = display_map
 2605                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2606                        .to_point(display_map);
 2607                    let end = display_map
 2608                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2609                        .to_point(display_map);
 2610                    if reversed {
 2611                        Some(end..start)
 2612                    } else {
 2613                        Some(start..end)
 2614                    }
 2615                } else {
 2616                    None
 2617                }
 2618            })
 2619            .collect::<Vec<_>>();
 2620
 2621        self.change_selections(None, window, cx, |s| {
 2622            s.select_ranges(selection_ranges);
 2623        });
 2624        cx.notify();
 2625    }
 2626
 2627    pub fn has_pending_nonempty_selection(&self) -> bool {
 2628        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2629            Some(Selection { start, end, .. }) => start != end,
 2630            None => false,
 2631        };
 2632
 2633        pending_nonempty_selection
 2634            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2635    }
 2636
 2637    pub fn has_pending_selection(&self) -> bool {
 2638        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2639    }
 2640
 2641    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2642        self.selection_mark_mode = false;
 2643
 2644        if self.clear_expanded_diff_hunks(cx) {
 2645            cx.notify();
 2646            return;
 2647        }
 2648        if self.dismiss_menus_and_popups(true, window, cx) {
 2649            return;
 2650        }
 2651
 2652        if self.mode == EditorMode::Full
 2653            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2654        {
 2655            return;
 2656        }
 2657
 2658        cx.propagate();
 2659    }
 2660
 2661    pub fn dismiss_menus_and_popups(
 2662        &mut self,
 2663        is_user_requested: bool,
 2664        window: &mut Window,
 2665        cx: &mut Context<Self>,
 2666    ) -> bool {
 2667        if self.take_rename(false, window, cx).is_some() {
 2668            return true;
 2669        }
 2670
 2671        if hide_hover(self, cx) {
 2672            return true;
 2673        }
 2674
 2675        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2676            return true;
 2677        }
 2678
 2679        if self.hide_context_menu(window, cx).is_some() {
 2680            return true;
 2681        }
 2682
 2683        if self.mouse_context_menu.take().is_some() {
 2684            return true;
 2685        }
 2686
 2687        if is_user_requested && self.discard_inline_completion(true, cx) {
 2688            return true;
 2689        }
 2690
 2691        if self.snippet_stack.pop().is_some() {
 2692            return true;
 2693        }
 2694
 2695        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2696            self.dismiss_diagnostics(cx);
 2697            return true;
 2698        }
 2699
 2700        false
 2701    }
 2702
 2703    fn linked_editing_ranges_for(
 2704        &self,
 2705        selection: Range<text::Anchor>,
 2706        cx: &App,
 2707    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2708        if self.linked_edit_ranges.is_empty() {
 2709            return None;
 2710        }
 2711        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2712            selection.end.buffer_id.and_then(|end_buffer_id| {
 2713                if selection.start.buffer_id != Some(end_buffer_id) {
 2714                    return None;
 2715                }
 2716                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2717                let snapshot = buffer.read(cx).snapshot();
 2718                self.linked_edit_ranges
 2719                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2720                    .map(|ranges| (ranges, snapshot, buffer))
 2721            })?;
 2722        use text::ToOffset as TO;
 2723        // find offset from the start of current range to current cursor position
 2724        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2725
 2726        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2727        let start_difference = start_offset - start_byte_offset;
 2728        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2729        let end_difference = end_offset - start_byte_offset;
 2730        // Current range has associated linked ranges.
 2731        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2732        for range in linked_ranges.iter() {
 2733            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2734            let end_offset = start_offset + end_difference;
 2735            let start_offset = start_offset + start_difference;
 2736            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2737                continue;
 2738            }
 2739            if self.selections.disjoint_anchor_ranges().any(|s| {
 2740                if s.start.buffer_id != selection.start.buffer_id
 2741                    || s.end.buffer_id != selection.end.buffer_id
 2742                {
 2743                    return false;
 2744                }
 2745                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2746                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2747            }) {
 2748                continue;
 2749            }
 2750            let start = buffer_snapshot.anchor_after(start_offset);
 2751            let end = buffer_snapshot.anchor_after(end_offset);
 2752            linked_edits
 2753                .entry(buffer.clone())
 2754                .or_default()
 2755                .push(start..end);
 2756        }
 2757        Some(linked_edits)
 2758    }
 2759
 2760    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2761        let text: Arc<str> = text.into();
 2762
 2763        if self.read_only(cx) {
 2764            return;
 2765        }
 2766
 2767        let selections = self.selections.all_adjusted(cx);
 2768        let mut bracket_inserted = false;
 2769        let mut edits = Vec::new();
 2770        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2771        let mut new_selections = Vec::with_capacity(selections.len());
 2772        let mut new_autoclose_regions = Vec::new();
 2773        let snapshot = self.buffer.read(cx).read(cx);
 2774
 2775        for (selection, autoclose_region) in
 2776            self.selections_with_autoclose_regions(selections, &snapshot)
 2777        {
 2778            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2779                // Determine if the inserted text matches the opening or closing
 2780                // bracket of any of this language's bracket pairs.
 2781                let mut bracket_pair = None;
 2782                let mut is_bracket_pair_start = false;
 2783                let mut is_bracket_pair_end = false;
 2784                if !text.is_empty() {
 2785                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2786                    //  and they are removing the character that triggered IME popup.
 2787                    for (pair, enabled) in scope.brackets() {
 2788                        if !pair.close && !pair.surround {
 2789                            continue;
 2790                        }
 2791
 2792                        if enabled && pair.start.ends_with(text.as_ref()) {
 2793                            let prefix_len = pair.start.len() - text.len();
 2794                            let preceding_text_matches_prefix = prefix_len == 0
 2795                                || (selection.start.column >= (prefix_len as u32)
 2796                                    && snapshot.contains_str_at(
 2797                                        Point::new(
 2798                                            selection.start.row,
 2799                                            selection.start.column - (prefix_len as u32),
 2800                                        ),
 2801                                        &pair.start[..prefix_len],
 2802                                    ));
 2803                            if preceding_text_matches_prefix {
 2804                                bracket_pair = Some(pair.clone());
 2805                                is_bracket_pair_start = true;
 2806                                break;
 2807                            }
 2808                        }
 2809                        if pair.end.as_str() == text.as_ref() {
 2810                            bracket_pair = Some(pair.clone());
 2811                            is_bracket_pair_end = true;
 2812                            break;
 2813                        }
 2814                    }
 2815                }
 2816
 2817                if let Some(bracket_pair) = bracket_pair {
 2818                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2819                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2820                    let auto_surround =
 2821                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2822                    if selection.is_empty() {
 2823                        if is_bracket_pair_start {
 2824                            // If the inserted text is a suffix of an opening bracket and the
 2825                            // selection is preceded by the rest of the opening bracket, then
 2826                            // insert the closing bracket.
 2827                            let following_text_allows_autoclose = snapshot
 2828                                .chars_at(selection.start)
 2829                                .next()
 2830                                .map_or(true, |c| scope.should_autoclose_before(c));
 2831
 2832                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2833                                && bracket_pair.start.len() == 1
 2834                            {
 2835                                let target = bracket_pair.start.chars().next().unwrap();
 2836                                let current_line_count = snapshot
 2837                                    .reversed_chars_at(selection.start)
 2838                                    .take_while(|&c| c != '\n')
 2839                                    .filter(|&c| c == target)
 2840                                    .count();
 2841                                current_line_count % 2 == 1
 2842                            } else {
 2843                                false
 2844                            };
 2845
 2846                            if autoclose
 2847                                && bracket_pair.close
 2848                                && following_text_allows_autoclose
 2849                                && !is_closing_quote
 2850                            {
 2851                                let anchor = snapshot.anchor_before(selection.end);
 2852                                new_selections.push((selection.map(|_| anchor), text.len()));
 2853                                new_autoclose_regions.push((
 2854                                    anchor,
 2855                                    text.len(),
 2856                                    selection.id,
 2857                                    bracket_pair.clone(),
 2858                                ));
 2859                                edits.push((
 2860                                    selection.range(),
 2861                                    format!("{}{}", text, bracket_pair.end).into(),
 2862                                ));
 2863                                bracket_inserted = true;
 2864                                continue;
 2865                            }
 2866                        }
 2867
 2868                        if let Some(region) = autoclose_region {
 2869                            // If the selection is followed by an auto-inserted closing bracket,
 2870                            // then don't insert that closing bracket again; just move the selection
 2871                            // past the closing bracket.
 2872                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2873                                && text.as_ref() == region.pair.end.as_str();
 2874                            if should_skip {
 2875                                let anchor = snapshot.anchor_after(selection.end);
 2876                                new_selections
 2877                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2878                                continue;
 2879                            }
 2880                        }
 2881
 2882                        let always_treat_brackets_as_autoclosed = snapshot
 2883                            .settings_at(selection.start, cx)
 2884                            .always_treat_brackets_as_autoclosed;
 2885                        if always_treat_brackets_as_autoclosed
 2886                            && is_bracket_pair_end
 2887                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2888                        {
 2889                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2890                            // and the inserted text is a closing bracket and the selection is followed
 2891                            // by the closing bracket then move the selection past the closing bracket.
 2892                            let anchor = snapshot.anchor_after(selection.end);
 2893                            new_selections.push((selection.map(|_| anchor), text.len()));
 2894                            continue;
 2895                        }
 2896                    }
 2897                    // If an opening bracket is 1 character long and is typed while
 2898                    // text is selected, then surround that text with the bracket pair.
 2899                    else if auto_surround
 2900                        && bracket_pair.surround
 2901                        && is_bracket_pair_start
 2902                        && bracket_pair.start.chars().count() == 1
 2903                    {
 2904                        edits.push((selection.start..selection.start, text.clone()));
 2905                        edits.push((
 2906                            selection.end..selection.end,
 2907                            bracket_pair.end.as_str().into(),
 2908                        ));
 2909                        bracket_inserted = true;
 2910                        new_selections.push((
 2911                            Selection {
 2912                                id: selection.id,
 2913                                start: snapshot.anchor_after(selection.start),
 2914                                end: snapshot.anchor_before(selection.end),
 2915                                reversed: selection.reversed,
 2916                                goal: selection.goal,
 2917                            },
 2918                            0,
 2919                        ));
 2920                        continue;
 2921                    }
 2922                }
 2923            }
 2924
 2925            if self.auto_replace_emoji_shortcode
 2926                && selection.is_empty()
 2927                && text.as_ref().ends_with(':')
 2928            {
 2929                if let Some(possible_emoji_short_code) =
 2930                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2931                {
 2932                    if !possible_emoji_short_code.is_empty() {
 2933                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2934                            let emoji_shortcode_start = Point::new(
 2935                                selection.start.row,
 2936                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2937                            );
 2938
 2939                            // Remove shortcode from buffer
 2940                            edits.push((
 2941                                emoji_shortcode_start..selection.start,
 2942                                "".to_string().into(),
 2943                            ));
 2944                            new_selections.push((
 2945                                Selection {
 2946                                    id: selection.id,
 2947                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2948                                    end: snapshot.anchor_before(selection.start),
 2949                                    reversed: selection.reversed,
 2950                                    goal: selection.goal,
 2951                                },
 2952                                0,
 2953                            ));
 2954
 2955                            // Insert emoji
 2956                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2957                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2958                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2959
 2960                            continue;
 2961                        }
 2962                    }
 2963                }
 2964            }
 2965
 2966            // If not handling any auto-close operation, then just replace the selected
 2967            // text with the given input and move the selection to the end of the
 2968            // newly inserted text.
 2969            let anchor = snapshot.anchor_after(selection.end);
 2970            if !self.linked_edit_ranges.is_empty() {
 2971                let start_anchor = snapshot.anchor_before(selection.start);
 2972
 2973                let is_word_char = text.chars().next().map_or(true, |char| {
 2974                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2975                    classifier.is_word(char)
 2976                });
 2977
 2978                if is_word_char {
 2979                    if let Some(ranges) = self
 2980                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2981                    {
 2982                        for (buffer, edits) in ranges {
 2983                            linked_edits
 2984                                .entry(buffer.clone())
 2985                                .or_default()
 2986                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2987                        }
 2988                    }
 2989                }
 2990            }
 2991
 2992            new_selections.push((selection.map(|_| anchor), 0));
 2993            edits.push((selection.start..selection.end, text.clone()));
 2994        }
 2995
 2996        drop(snapshot);
 2997
 2998        self.transact(window, cx, |this, window, cx| {
 2999            this.buffer.update(cx, |buffer, cx| {
 3000                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3001            });
 3002            for (buffer, edits) in linked_edits {
 3003                buffer.update(cx, |buffer, cx| {
 3004                    let snapshot = buffer.snapshot();
 3005                    let edits = edits
 3006                        .into_iter()
 3007                        .map(|(range, text)| {
 3008                            use text::ToPoint as TP;
 3009                            let end_point = TP::to_point(&range.end, &snapshot);
 3010                            let start_point = TP::to_point(&range.start, &snapshot);
 3011                            (start_point..end_point, text)
 3012                        })
 3013                        .sorted_by_key(|(range, _)| range.start)
 3014                        .collect::<Vec<_>>();
 3015                    buffer.edit(edits, None, cx);
 3016                })
 3017            }
 3018            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3019            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3020            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3021            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3022                .zip(new_selection_deltas)
 3023                .map(|(selection, delta)| Selection {
 3024                    id: selection.id,
 3025                    start: selection.start + delta,
 3026                    end: selection.end + delta,
 3027                    reversed: selection.reversed,
 3028                    goal: SelectionGoal::None,
 3029                })
 3030                .collect::<Vec<_>>();
 3031
 3032            let mut i = 0;
 3033            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3034                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3035                let start = map.buffer_snapshot.anchor_before(position);
 3036                let end = map.buffer_snapshot.anchor_after(position);
 3037                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3038                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3039                        Ordering::Less => i += 1,
 3040                        Ordering::Greater => break,
 3041                        Ordering::Equal => {
 3042                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3043                                Ordering::Less => i += 1,
 3044                                Ordering::Equal => break,
 3045                                Ordering::Greater => break,
 3046                            }
 3047                        }
 3048                    }
 3049                }
 3050                this.autoclose_regions.insert(
 3051                    i,
 3052                    AutocloseRegion {
 3053                        selection_id,
 3054                        range: start..end,
 3055                        pair,
 3056                    },
 3057                );
 3058            }
 3059
 3060            let had_active_inline_completion = this.has_active_inline_completion();
 3061            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3062                s.select(new_selections)
 3063            });
 3064
 3065            if !bracket_inserted {
 3066                if let Some(on_type_format_task) =
 3067                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3068                {
 3069                    on_type_format_task.detach_and_log_err(cx);
 3070                }
 3071            }
 3072
 3073            let editor_settings = EditorSettings::get_global(cx);
 3074            if bracket_inserted
 3075                && (editor_settings.auto_signature_help
 3076                    || editor_settings.show_signature_help_after_edits)
 3077            {
 3078                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3079            }
 3080
 3081            let trigger_in_words =
 3082                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3083            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3084            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3085            this.refresh_inline_completion(true, false, window, cx);
 3086        });
 3087    }
 3088
 3089    fn find_possible_emoji_shortcode_at_position(
 3090        snapshot: &MultiBufferSnapshot,
 3091        position: Point,
 3092    ) -> Option<String> {
 3093        let mut chars = Vec::new();
 3094        let mut found_colon = false;
 3095        for char in snapshot.reversed_chars_at(position).take(100) {
 3096            // Found a possible emoji shortcode in the middle of the buffer
 3097            if found_colon {
 3098                if char.is_whitespace() {
 3099                    chars.reverse();
 3100                    return Some(chars.iter().collect());
 3101                }
 3102                // If the previous character is not a whitespace, we are in the middle of a word
 3103                // and we only want to complete the shortcode if the word is made up of other emojis
 3104                let mut containing_word = String::new();
 3105                for ch in snapshot
 3106                    .reversed_chars_at(position)
 3107                    .skip(chars.len() + 1)
 3108                    .take(100)
 3109                {
 3110                    if ch.is_whitespace() {
 3111                        break;
 3112                    }
 3113                    containing_word.push(ch);
 3114                }
 3115                let containing_word = containing_word.chars().rev().collect::<String>();
 3116                if util::word_consists_of_emojis(containing_word.as_str()) {
 3117                    chars.reverse();
 3118                    return Some(chars.iter().collect());
 3119                }
 3120            }
 3121
 3122            if char.is_whitespace() || !char.is_ascii() {
 3123                return None;
 3124            }
 3125            if char == ':' {
 3126                found_colon = true;
 3127            } else {
 3128                chars.push(char);
 3129            }
 3130        }
 3131        // Found a possible emoji shortcode at the beginning of the buffer
 3132        chars.reverse();
 3133        Some(chars.iter().collect())
 3134    }
 3135
 3136    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3137        self.transact(window, cx, |this, window, cx| {
 3138            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3139                let selections = this.selections.all::<usize>(cx);
 3140                let multi_buffer = this.buffer.read(cx);
 3141                let buffer = multi_buffer.snapshot(cx);
 3142                selections
 3143                    .iter()
 3144                    .map(|selection| {
 3145                        let start_point = selection.start.to_point(&buffer);
 3146                        let mut indent =
 3147                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3148                        indent.len = cmp::min(indent.len, start_point.column);
 3149                        let start = selection.start;
 3150                        let end = selection.end;
 3151                        let selection_is_empty = start == end;
 3152                        let language_scope = buffer.language_scope_at(start);
 3153                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3154                            &language_scope
 3155                        {
 3156                            let insert_extra_newline =
 3157                                insert_extra_newline_brackets(&buffer, start..end, language)
 3158                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3159
 3160                            // Comment extension on newline is allowed only for cursor selections
 3161                            let comment_delimiter = maybe!({
 3162                                if !selection_is_empty {
 3163                                    return None;
 3164                                }
 3165
 3166                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3167                                    return None;
 3168                                }
 3169
 3170                                let delimiters = language.line_comment_prefixes();
 3171                                let max_len_of_delimiter =
 3172                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3173                                let (snapshot, range) =
 3174                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3175
 3176                                let mut index_of_first_non_whitespace = 0;
 3177                                let comment_candidate = snapshot
 3178                                    .chars_for_range(range)
 3179                                    .skip_while(|c| {
 3180                                        let should_skip = c.is_whitespace();
 3181                                        if should_skip {
 3182                                            index_of_first_non_whitespace += 1;
 3183                                        }
 3184                                        should_skip
 3185                                    })
 3186                                    .take(max_len_of_delimiter)
 3187                                    .collect::<String>();
 3188                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3189                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3190                                })?;
 3191                                let cursor_is_placed_after_comment_marker =
 3192                                    index_of_first_non_whitespace + comment_prefix.len()
 3193                                        <= start_point.column as usize;
 3194                                if cursor_is_placed_after_comment_marker {
 3195                                    Some(comment_prefix.clone())
 3196                                } else {
 3197                                    None
 3198                                }
 3199                            });
 3200                            (comment_delimiter, insert_extra_newline)
 3201                        } else {
 3202                            (None, false)
 3203                        };
 3204
 3205                        let capacity_for_delimiter = comment_delimiter
 3206                            .as_deref()
 3207                            .map(str::len)
 3208                            .unwrap_or_default();
 3209                        let mut new_text =
 3210                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3211                        new_text.push('\n');
 3212                        new_text.extend(indent.chars());
 3213                        if let Some(delimiter) = &comment_delimiter {
 3214                            new_text.push_str(delimiter);
 3215                        }
 3216                        if insert_extra_newline {
 3217                            new_text = new_text.repeat(2);
 3218                        }
 3219
 3220                        let anchor = buffer.anchor_after(end);
 3221                        let new_selection = selection.map(|_| anchor);
 3222                        (
 3223                            (start..end, new_text),
 3224                            (insert_extra_newline, new_selection),
 3225                        )
 3226                    })
 3227                    .unzip()
 3228            };
 3229
 3230            this.edit_with_autoindent(edits, cx);
 3231            let buffer = this.buffer.read(cx).snapshot(cx);
 3232            let new_selections = selection_fixup_info
 3233                .into_iter()
 3234                .map(|(extra_newline_inserted, new_selection)| {
 3235                    let mut cursor = new_selection.end.to_point(&buffer);
 3236                    if extra_newline_inserted {
 3237                        cursor.row -= 1;
 3238                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3239                    }
 3240                    new_selection.map(|_| cursor)
 3241                })
 3242                .collect();
 3243
 3244            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3245                s.select(new_selections)
 3246            });
 3247            this.refresh_inline_completion(true, false, window, cx);
 3248        });
 3249    }
 3250
 3251    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3252        let buffer = self.buffer.read(cx);
 3253        let snapshot = buffer.snapshot(cx);
 3254
 3255        let mut edits = Vec::new();
 3256        let mut rows = Vec::new();
 3257
 3258        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3259            let cursor = selection.head();
 3260            let row = cursor.row;
 3261
 3262            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3263
 3264            let newline = "\n".to_string();
 3265            edits.push((start_of_line..start_of_line, newline));
 3266
 3267            rows.push(row + rows_inserted as u32);
 3268        }
 3269
 3270        self.transact(window, cx, |editor, window, cx| {
 3271            editor.edit(edits, cx);
 3272
 3273            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3274                let mut index = 0;
 3275                s.move_cursors_with(|map, _, _| {
 3276                    let row = rows[index];
 3277                    index += 1;
 3278
 3279                    let point = Point::new(row, 0);
 3280                    let boundary = map.next_line_boundary(point).1;
 3281                    let clipped = map.clip_point(boundary, Bias::Left);
 3282
 3283                    (clipped, SelectionGoal::None)
 3284                });
 3285            });
 3286
 3287            let mut indent_edits = Vec::new();
 3288            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3289            for row in rows {
 3290                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3291                for (row, indent) in indents {
 3292                    if indent.len == 0 {
 3293                        continue;
 3294                    }
 3295
 3296                    let text = match indent.kind {
 3297                        IndentKind::Space => " ".repeat(indent.len as usize),
 3298                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3299                    };
 3300                    let point = Point::new(row.0, 0);
 3301                    indent_edits.push((point..point, text));
 3302                }
 3303            }
 3304            editor.edit(indent_edits, cx);
 3305        });
 3306    }
 3307
 3308    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3309        let buffer = self.buffer.read(cx);
 3310        let snapshot = buffer.snapshot(cx);
 3311
 3312        let mut edits = Vec::new();
 3313        let mut rows = Vec::new();
 3314        let mut rows_inserted = 0;
 3315
 3316        for selection in self.selections.all_adjusted(cx) {
 3317            let cursor = selection.head();
 3318            let row = cursor.row;
 3319
 3320            let point = Point::new(row + 1, 0);
 3321            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3322
 3323            let newline = "\n".to_string();
 3324            edits.push((start_of_line..start_of_line, newline));
 3325
 3326            rows_inserted += 1;
 3327            rows.push(row + rows_inserted);
 3328        }
 3329
 3330        self.transact(window, cx, |editor, window, cx| {
 3331            editor.edit(edits, cx);
 3332
 3333            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3334                let mut index = 0;
 3335                s.move_cursors_with(|map, _, _| {
 3336                    let row = rows[index];
 3337                    index += 1;
 3338
 3339                    let point = Point::new(row, 0);
 3340                    let boundary = map.next_line_boundary(point).1;
 3341                    let clipped = map.clip_point(boundary, Bias::Left);
 3342
 3343                    (clipped, SelectionGoal::None)
 3344                });
 3345            });
 3346
 3347            let mut indent_edits = Vec::new();
 3348            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3349            for row in rows {
 3350                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3351                for (row, indent) in indents {
 3352                    if indent.len == 0 {
 3353                        continue;
 3354                    }
 3355
 3356                    let text = match indent.kind {
 3357                        IndentKind::Space => " ".repeat(indent.len as usize),
 3358                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3359                    };
 3360                    let point = Point::new(row.0, 0);
 3361                    indent_edits.push((point..point, text));
 3362                }
 3363            }
 3364            editor.edit(indent_edits, cx);
 3365        });
 3366    }
 3367
 3368    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3369        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3370            original_indent_columns: Vec::new(),
 3371        });
 3372        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3373    }
 3374
 3375    fn insert_with_autoindent_mode(
 3376        &mut self,
 3377        text: &str,
 3378        autoindent_mode: Option<AutoindentMode>,
 3379        window: &mut Window,
 3380        cx: &mut Context<Self>,
 3381    ) {
 3382        if self.read_only(cx) {
 3383            return;
 3384        }
 3385
 3386        let text: Arc<str> = text.into();
 3387        self.transact(window, cx, |this, window, cx| {
 3388            let old_selections = this.selections.all_adjusted(cx);
 3389            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3390                let anchors = {
 3391                    let snapshot = buffer.read(cx);
 3392                    old_selections
 3393                        .iter()
 3394                        .map(|s| {
 3395                            let anchor = snapshot.anchor_after(s.head());
 3396                            s.map(|_| anchor)
 3397                        })
 3398                        .collect::<Vec<_>>()
 3399                };
 3400                buffer.edit(
 3401                    old_selections
 3402                        .iter()
 3403                        .map(|s| (s.start..s.end, text.clone())),
 3404                    autoindent_mode,
 3405                    cx,
 3406                );
 3407                anchors
 3408            });
 3409
 3410            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3411                s.select_anchors(selection_anchors);
 3412            });
 3413
 3414            cx.notify();
 3415        });
 3416    }
 3417
 3418    fn trigger_completion_on_input(
 3419        &mut self,
 3420        text: &str,
 3421        trigger_in_words: bool,
 3422        window: &mut Window,
 3423        cx: &mut Context<Self>,
 3424    ) {
 3425        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3426            self.show_completions(
 3427                &ShowCompletions {
 3428                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3429                },
 3430                window,
 3431                cx,
 3432            );
 3433        } else {
 3434            self.hide_context_menu(window, cx);
 3435        }
 3436    }
 3437
 3438    fn is_completion_trigger(
 3439        &self,
 3440        text: &str,
 3441        trigger_in_words: bool,
 3442        cx: &mut Context<Self>,
 3443    ) -> bool {
 3444        let position = self.selections.newest_anchor().head();
 3445        let multibuffer = self.buffer.read(cx);
 3446        let Some(buffer) = position
 3447            .buffer_id
 3448            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3449        else {
 3450            return false;
 3451        };
 3452
 3453        if let Some(completion_provider) = &self.completion_provider {
 3454            completion_provider.is_completion_trigger(
 3455                &buffer,
 3456                position.text_anchor,
 3457                text,
 3458                trigger_in_words,
 3459                cx,
 3460            )
 3461        } else {
 3462            false
 3463        }
 3464    }
 3465
 3466    /// If any empty selections is touching the start of its innermost containing autoclose
 3467    /// region, expand it to select the brackets.
 3468    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3469        let selections = self.selections.all::<usize>(cx);
 3470        let buffer = self.buffer.read(cx).read(cx);
 3471        let new_selections = self
 3472            .selections_with_autoclose_regions(selections, &buffer)
 3473            .map(|(mut selection, region)| {
 3474                if !selection.is_empty() {
 3475                    return selection;
 3476                }
 3477
 3478                if let Some(region) = region {
 3479                    let mut range = region.range.to_offset(&buffer);
 3480                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3481                        range.start -= region.pair.start.len();
 3482                        if buffer.contains_str_at(range.start, &region.pair.start)
 3483                            && buffer.contains_str_at(range.end, &region.pair.end)
 3484                        {
 3485                            range.end += region.pair.end.len();
 3486                            selection.start = range.start;
 3487                            selection.end = range.end;
 3488
 3489                            return selection;
 3490                        }
 3491                    }
 3492                }
 3493
 3494                let always_treat_brackets_as_autoclosed = buffer
 3495                    .settings_at(selection.start, cx)
 3496                    .always_treat_brackets_as_autoclosed;
 3497
 3498                if !always_treat_brackets_as_autoclosed {
 3499                    return selection;
 3500                }
 3501
 3502                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3503                    for (pair, enabled) in scope.brackets() {
 3504                        if !enabled || !pair.close {
 3505                            continue;
 3506                        }
 3507
 3508                        if buffer.contains_str_at(selection.start, &pair.end) {
 3509                            let pair_start_len = pair.start.len();
 3510                            if buffer.contains_str_at(
 3511                                selection.start.saturating_sub(pair_start_len),
 3512                                &pair.start,
 3513                            ) {
 3514                                selection.start -= pair_start_len;
 3515                                selection.end += pair.end.len();
 3516
 3517                                return selection;
 3518                            }
 3519                        }
 3520                    }
 3521                }
 3522
 3523                selection
 3524            })
 3525            .collect();
 3526
 3527        drop(buffer);
 3528        self.change_selections(None, window, cx, |selections| {
 3529            selections.select(new_selections)
 3530        });
 3531    }
 3532
 3533    /// Iterate the given selections, and for each one, find the smallest surrounding
 3534    /// autoclose region. This uses the ordering of the selections and the autoclose
 3535    /// regions to avoid repeated comparisons.
 3536    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3537        &'a self,
 3538        selections: impl IntoIterator<Item = Selection<D>>,
 3539        buffer: &'a MultiBufferSnapshot,
 3540    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3541        let mut i = 0;
 3542        let mut regions = self.autoclose_regions.as_slice();
 3543        selections.into_iter().map(move |selection| {
 3544            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3545
 3546            let mut enclosing = None;
 3547            while let Some(pair_state) = regions.get(i) {
 3548                if pair_state.range.end.to_offset(buffer) < range.start {
 3549                    regions = &regions[i + 1..];
 3550                    i = 0;
 3551                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3552                    break;
 3553                } else {
 3554                    if pair_state.selection_id == selection.id {
 3555                        enclosing = Some(pair_state);
 3556                    }
 3557                    i += 1;
 3558                }
 3559            }
 3560
 3561            (selection, enclosing)
 3562        })
 3563    }
 3564
 3565    /// Remove any autoclose regions that no longer contain their selection.
 3566    fn invalidate_autoclose_regions(
 3567        &mut self,
 3568        mut selections: &[Selection<Anchor>],
 3569        buffer: &MultiBufferSnapshot,
 3570    ) {
 3571        self.autoclose_regions.retain(|state| {
 3572            let mut i = 0;
 3573            while let Some(selection) = selections.get(i) {
 3574                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3575                    selections = &selections[1..];
 3576                    continue;
 3577                }
 3578                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3579                    break;
 3580                }
 3581                if selection.id == state.selection_id {
 3582                    return true;
 3583                } else {
 3584                    i += 1;
 3585                }
 3586            }
 3587            false
 3588        });
 3589    }
 3590
 3591    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3592        let offset = position.to_offset(buffer);
 3593        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3594        if offset > word_range.start && kind == Some(CharKind::Word) {
 3595            Some(
 3596                buffer
 3597                    .text_for_range(word_range.start..offset)
 3598                    .collect::<String>(),
 3599            )
 3600        } else {
 3601            None
 3602        }
 3603    }
 3604
 3605    pub fn toggle_inlay_hints(
 3606        &mut self,
 3607        _: &ToggleInlayHints,
 3608        _: &mut Window,
 3609        cx: &mut Context<Self>,
 3610    ) {
 3611        self.refresh_inlay_hints(
 3612            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3613            cx,
 3614        );
 3615    }
 3616
 3617    pub fn inlay_hints_enabled(&self) -> bool {
 3618        self.inlay_hint_cache.enabled
 3619    }
 3620
 3621    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3622        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3623            return;
 3624        }
 3625
 3626        let reason_description = reason.description();
 3627        let ignore_debounce = matches!(
 3628            reason,
 3629            InlayHintRefreshReason::SettingsChange(_)
 3630                | InlayHintRefreshReason::Toggle(_)
 3631                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3632        );
 3633        let (invalidate_cache, required_languages) = match reason {
 3634            InlayHintRefreshReason::Toggle(enabled) => {
 3635                self.inlay_hint_cache.enabled = enabled;
 3636                if enabled {
 3637                    (InvalidationStrategy::RefreshRequested, None)
 3638                } else {
 3639                    self.inlay_hint_cache.clear();
 3640                    self.splice_inlays(
 3641                        &self
 3642                            .visible_inlay_hints(cx)
 3643                            .iter()
 3644                            .map(|inlay| inlay.id)
 3645                            .collect::<Vec<InlayId>>(),
 3646                        Vec::new(),
 3647                        cx,
 3648                    );
 3649                    return;
 3650                }
 3651            }
 3652            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3653                match self.inlay_hint_cache.update_settings(
 3654                    &self.buffer,
 3655                    new_settings,
 3656                    self.visible_inlay_hints(cx),
 3657                    cx,
 3658                ) {
 3659                    ControlFlow::Break(Some(InlaySplice {
 3660                        to_remove,
 3661                        to_insert,
 3662                    })) => {
 3663                        self.splice_inlays(&to_remove, to_insert, cx);
 3664                        return;
 3665                    }
 3666                    ControlFlow::Break(None) => return,
 3667                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3668                }
 3669            }
 3670            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3671                if let Some(InlaySplice {
 3672                    to_remove,
 3673                    to_insert,
 3674                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3675                {
 3676                    self.splice_inlays(&to_remove, to_insert, cx);
 3677                }
 3678                return;
 3679            }
 3680            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3681            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3682                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3683            }
 3684            InlayHintRefreshReason::RefreshRequested => {
 3685                (InvalidationStrategy::RefreshRequested, None)
 3686            }
 3687        };
 3688
 3689        if let Some(InlaySplice {
 3690            to_remove,
 3691            to_insert,
 3692        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3693            reason_description,
 3694            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3695            invalidate_cache,
 3696            ignore_debounce,
 3697            cx,
 3698        ) {
 3699            self.splice_inlays(&to_remove, to_insert, cx);
 3700        }
 3701    }
 3702
 3703    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3704        self.display_map
 3705            .read(cx)
 3706            .current_inlays()
 3707            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3708            .cloned()
 3709            .collect()
 3710    }
 3711
 3712    pub fn excerpts_for_inlay_hints_query(
 3713        &self,
 3714        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3715        cx: &mut Context<Editor>,
 3716    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3717        let Some(project) = self.project.as_ref() else {
 3718            return HashMap::default();
 3719        };
 3720        let project = project.read(cx);
 3721        let multi_buffer = self.buffer().read(cx);
 3722        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3723        let multi_buffer_visible_start = self
 3724            .scroll_manager
 3725            .anchor()
 3726            .anchor
 3727            .to_point(&multi_buffer_snapshot);
 3728        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3729            multi_buffer_visible_start
 3730                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3731            Bias::Left,
 3732        );
 3733        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3734        multi_buffer_snapshot
 3735            .range_to_buffer_ranges(multi_buffer_visible_range)
 3736            .into_iter()
 3737            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3738            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3739                let buffer_file = project::File::from_dyn(buffer.file())?;
 3740                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3741                let worktree_entry = buffer_worktree
 3742                    .read(cx)
 3743                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3744                if worktree_entry.is_ignored {
 3745                    return None;
 3746                }
 3747
 3748                let language = buffer.language()?;
 3749                if let Some(restrict_to_languages) = restrict_to_languages {
 3750                    if !restrict_to_languages.contains(language) {
 3751                        return None;
 3752                    }
 3753                }
 3754                Some((
 3755                    excerpt_id,
 3756                    (
 3757                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3758                        buffer.version().clone(),
 3759                        excerpt_visible_range,
 3760                    ),
 3761                ))
 3762            })
 3763            .collect()
 3764    }
 3765
 3766    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3767        TextLayoutDetails {
 3768            text_system: window.text_system().clone(),
 3769            editor_style: self.style.clone().unwrap(),
 3770            rem_size: window.rem_size(),
 3771            scroll_anchor: self.scroll_manager.anchor(),
 3772            visible_rows: self.visible_line_count(),
 3773            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3774        }
 3775    }
 3776
 3777    pub fn splice_inlays(
 3778        &self,
 3779        to_remove: &[InlayId],
 3780        to_insert: Vec<Inlay>,
 3781        cx: &mut Context<Self>,
 3782    ) {
 3783        self.display_map.update(cx, |display_map, cx| {
 3784            display_map.splice_inlays(to_remove, to_insert, cx)
 3785        });
 3786        cx.notify();
 3787    }
 3788
 3789    fn trigger_on_type_formatting(
 3790        &self,
 3791        input: String,
 3792        window: &mut Window,
 3793        cx: &mut Context<Self>,
 3794    ) -> Option<Task<Result<()>>> {
 3795        if input.len() != 1 {
 3796            return None;
 3797        }
 3798
 3799        let project = self.project.as_ref()?;
 3800        let position = self.selections.newest_anchor().head();
 3801        let (buffer, buffer_position) = self
 3802            .buffer
 3803            .read(cx)
 3804            .text_anchor_for_position(position, cx)?;
 3805
 3806        let settings = language_settings::language_settings(
 3807            buffer
 3808                .read(cx)
 3809                .language_at(buffer_position)
 3810                .map(|l| l.name()),
 3811            buffer.read(cx).file(),
 3812            cx,
 3813        );
 3814        if !settings.use_on_type_format {
 3815            return None;
 3816        }
 3817
 3818        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3819        // hence we do LSP request & edit on host side only — add formats to host's history.
 3820        let push_to_lsp_host_history = true;
 3821        // If this is not the host, append its history with new edits.
 3822        let push_to_client_history = project.read(cx).is_via_collab();
 3823
 3824        let on_type_formatting = project.update(cx, |project, cx| {
 3825            project.on_type_format(
 3826                buffer.clone(),
 3827                buffer_position,
 3828                input,
 3829                push_to_lsp_host_history,
 3830                cx,
 3831            )
 3832        });
 3833        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3834            if let Some(transaction) = on_type_formatting.await? {
 3835                if push_to_client_history {
 3836                    buffer
 3837                        .update(&mut cx, |buffer, _| {
 3838                            buffer.push_transaction(transaction, Instant::now());
 3839                        })
 3840                        .ok();
 3841                }
 3842                editor.update(&mut cx, |editor, cx| {
 3843                    editor.refresh_document_highlights(cx);
 3844                })?;
 3845            }
 3846            Ok(())
 3847        }))
 3848    }
 3849
 3850    pub fn show_completions(
 3851        &mut self,
 3852        options: &ShowCompletions,
 3853        window: &mut Window,
 3854        cx: &mut Context<Self>,
 3855    ) {
 3856        if self.pending_rename.is_some() {
 3857            return;
 3858        }
 3859
 3860        let Some(provider) = self.completion_provider.as_ref() else {
 3861            return;
 3862        };
 3863
 3864        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3865            return;
 3866        }
 3867
 3868        let position = self.selections.newest_anchor().head();
 3869        if position.diff_base_anchor.is_some() {
 3870            return;
 3871        }
 3872        let (buffer, buffer_position) =
 3873            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3874                output
 3875            } else {
 3876                return;
 3877            };
 3878        let show_completion_documentation = buffer
 3879            .read(cx)
 3880            .snapshot()
 3881            .settings_at(buffer_position, cx)
 3882            .show_completion_documentation;
 3883
 3884        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3885
 3886        let trigger_kind = match &options.trigger {
 3887            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3888                CompletionTriggerKind::TRIGGER_CHARACTER
 3889            }
 3890            _ => CompletionTriggerKind::INVOKED,
 3891        };
 3892        let completion_context = CompletionContext {
 3893            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3894                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3895                    Some(String::from(trigger))
 3896                } else {
 3897                    None
 3898                }
 3899            }),
 3900            trigger_kind,
 3901        };
 3902        let completions =
 3903            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3904        let sort_completions = provider.sort_completions();
 3905
 3906        let id = post_inc(&mut self.next_completion_id);
 3907        let task = cx.spawn_in(window, |editor, mut cx| {
 3908            async move {
 3909                editor.update(&mut cx, |this, _| {
 3910                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3911                })?;
 3912                let completions = completions.await.log_err();
 3913                let menu = if let Some(completions) = completions {
 3914                    let mut menu = CompletionsMenu::new(
 3915                        id,
 3916                        sort_completions,
 3917                        show_completion_documentation,
 3918                        position,
 3919                        buffer.clone(),
 3920                        completions.into(),
 3921                    );
 3922
 3923                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3924                        .await;
 3925
 3926                    menu.visible().then_some(menu)
 3927                } else {
 3928                    None
 3929                };
 3930
 3931                editor.update_in(&mut cx, |editor, window, cx| {
 3932                    match editor.context_menu.borrow().as_ref() {
 3933                        None => {}
 3934                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3935                            if prev_menu.id > id {
 3936                                return;
 3937                            }
 3938                        }
 3939                        _ => return,
 3940                    }
 3941
 3942                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3943                        let mut menu = menu.unwrap();
 3944                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3945
 3946                        *editor.context_menu.borrow_mut() =
 3947                            Some(CodeContextMenu::Completions(menu));
 3948
 3949                        if editor.show_edit_predictions_in_menu() {
 3950                            editor.update_visible_inline_completion(window, cx);
 3951                        } else {
 3952                            editor.discard_inline_completion(false, cx);
 3953                        }
 3954
 3955                        cx.notify();
 3956                    } else if editor.completion_tasks.len() <= 1 {
 3957                        // If there are no more completion tasks and the last menu was
 3958                        // empty, we should hide it.
 3959                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3960                        // If it was already hidden and we don't show inline
 3961                        // completions in the menu, we should also show the
 3962                        // inline-completion when available.
 3963                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3964                            editor.update_visible_inline_completion(window, cx);
 3965                        }
 3966                    }
 3967                })?;
 3968
 3969                Ok::<_, anyhow::Error>(())
 3970            }
 3971            .log_err()
 3972        });
 3973
 3974        self.completion_tasks.push((id, task));
 3975    }
 3976
 3977    pub fn confirm_completion(
 3978        &mut self,
 3979        action: &ConfirmCompletion,
 3980        window: &mut Window,
 3981        cx: &mut Context<Self>,
 3982    ) -> Option<Task<Result<()>>> {
 3983        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3984    }
 3985
 3986    pub fn compose_completion(
 3987        &mut self,
 3988        action: &ComposeCompletion,
 3989        window: &mut Window,
 3990        cx: &mut Context<Self>,
 3991    ) -> Option<Task<Result<()>>> {
 3992        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3993    }
 3994
 3995    fn do_completion(
 3996        &mut self,
 3997        item_ix: Option<usize>,
 3998        intent: CompletionIntent,
 3999        window: &mut Window,
 4000        cx: &mut Context<Editor>,
 4001    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4002        use language::ToOffset as _;
 4003
 4004        let completions_menu =
 4005            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4006                menu
 4007            } else {
 4008                return None;
 4009            };
 4010
 4011        let entries = completions_menu.entries.borrow();
 4012        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4013        if self.show_edit_predictions_in_menu() {
 4014            self.discard_inline_completion(true, cx);
 4015        }
 4016        let candidate_id = mat.candidate_id;
 4017        drop(entries);
 4018
 4019        let buffer_handle = completions_menu.buffer;
 4020        let completion = completions_menu
 4021            .completions
 4022            .borrow()
 4023            .get(candidate_id)?
 4024            .clone();
 4025        cx.stop_propagation();
 4026
 4027        let snippet;
 4028        let text;
 4029
 4030        if completion.is_snippet() {
 4031            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4032            text = snippet.as_ref().unwrap().text.clone();
 4033        } else {
 4034            snippet = None;
 4035            text = completion.new_text.clone();
 4036        };
 4037        let selections = self.selections.all::<usize>(cx);
 4038        let buffer = buffer_handle.read(cx);
 4039        let old_range = completion.old_range.to_offset(buffer);
 4040        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4041
 4042        let newest_selection = self.selections.newest_anchor();
 4043        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4044            return None;
 4045        }
 4046
 4047        let lookbehind = newest_selection
 4048            .start
 4049            .text_anchor
 4050            .to_offset(buffer)
 4051            .saturating_sub(old_range.start);
 4052        let lookahead = old_range
 4053            .end
 4054            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4055        let mut common_prefix_len = old_text
 4056            .bytes()
 4057            .zip(text.bytes())
 4058            .take_while(|(a, b)| a == b)
 4059            .count();
 4060
 4061        let snapshot = self.buffer.read(cx).snapshot(cx);
 4062        let mut range_to_replace: Option<Range<isize>> = None;
 4063        let mut ranges = Vec::new();
 4064        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4065        for selection in &selections {
 4066            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4067                let start = selection.start.saturating_sub(lookbehind);
 4068                let end = selection.end + lookahead;
 4069                if selection.id == newest_selection.id {
 4070                    range_to_replace = Some(
 4071                        ((start + common_prefix_len) as isize - selection.start as isize)
 4072                            ..(end as isize - selection.start as isize),
 4073                    );
 4074                }
 4075                ranges.push(start + common_prefix_len..end);
 4076            } else {
 4077                common_prefix_len = 0;
 4078                ranges.clear();
 4079                ranges.extend(selections.iter().map(|s| {
 4080                    if s.id == newest_selection.id {
 4081                        range_to_replace = Some(
 4082                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4083                                - selection.start as isize
 4084                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4085                                    - selection.start as isize,
 4086                        );
 4087                        old_range.clone()
 4088                    } else {
 4089                        s.start..s.end
 4090                    }
 4091                }));
 4092                break;
 4093            }
 4094            if !self.linked_edit_ranges.is_empty() {
 4095                let start_anchor = snapshot.anchor_before(selection.head());
 4096                let end_anchor = snapshot.anchor_after(selection.tail());
 4097                if let Some(ranges) = self
 4098                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4099                {
 4100                    for (buffer, edits) in ranges {
 4101                        linked_edits.entry(buffer.clone()).or_default().extend(
 4102                            edits
 4103                                .into_iter()
 4104                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4105                        );
 4106                    }
 4107                }
 4108            }
 4109        }
 4110        let text = &text[common_prefix_len..];
 4111
 4112        cx.emit(EditorEvent::InputHandled {
 4113            utf16_range_to_replace: range_to_replace,
 4114            text: text.into(),
 4115        });
 4116
 4117        self.transact(window, cx, |this, window, cx| {
 4118            if let Some(mut snippet) = snippet {
 4119                snippet.text = text.to_string();
 4120                for tabstop in snippet
 4121                    .tabstops
 4122                    .iter_mut()
 4123                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4124                {
 4125                    tabstop.start -= common_prefix_len as isize;
 4126                    tabstop.end -= common_prefix_len as isize;
 4127                }
 4128
 4129                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4130            } else {
 4131                this.buffer.update(cx, |buffer, cx| {
 4132                    buffer.edit(
 4133                        ranges.iter().map(|range| (range.clone(), text)),
 4134                        this.autoindent_mode.clone(),
 4135                        cx,
 4136                    );
 4137                });
 4138            }
 4139            for (buffer, edits) in linked_edits {
 4140                buffer.update(cx, |buffer, cx| {
 4141                    let snapshot = buffer.snapshot();
 4142                    let edits = edits
 4143                        .into_iter()
 4144                        .map(|(range, text)| {
 4145                            use text::ToPoint as TP;
 4146                            let end_point = TP::to_point(&range.end, &snapshot);
 4147                            let start_point = TP::to_point(&range.start, &snapshot);
 4148                            (start_point..end_point, text)
 4149                        })
 4150                        .sorted_by_key(|(range, _)| range.start)
 4151                        .collect::<Vec<_>>();
 4152                    buffer.edit(edits, None, cx);
 4153                })
 4154            }
 4155
 4156            this.refresh_inline_completion(true, false, window, cx);
 4157        });
 4158
 4159        let show_new_completions_on_confirm = completion
 4160            .confirm
 4161            .as_ref()
 4162            .map_or(false, |confirm| confirm(intent, window, cx));
 4163        if show_new_completions_on_confirm {
 4164            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4165        }
 4166
 4167        let provider = self.completion_provider.as_ref()?;
 4168        drop(completion);
 4169        let apply_edits = provider.apply_additional_edits_for_completion(
 4170            buffer_handle,
 4171            completions_menu.completions.clone(),
 4172            candidate_id,
 4173            true,
 4174            cx,
 4175        );
 4176
 4177        let editor_settings = EditorSettings::get_global(cx);
 4178        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4179            // After the code completion is finished, users often want to know what signatures are needed.
 4180            // so we should automatically call signature_help
 4181            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4182        }
 4183
 4184        Some(cx.foreground_executor().spawn(async move {
 4185            apply_edits.await?;
 4186            Ok(())
 4187        }))
 4188    }
 4189
 4190    pub fn toggle_code_actions(
 4191        &mut self,
 4192        action: &ToggleCodeActions,
 4193        window: &mut Window,
 4194        cx: &mut Context<Self>,
 4195    ) {
 4196        let mut context_menu = self.context_menu.borrow_mut();
 4197        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4198            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4199                // Toggle if we're selecting the same one
 4200                *context_menu = None;
 4201                cx.notify();
 4202                return;
 4203            } else {
 4204                // Otherwise, clear it and start a new one
 4205                *context_menu = None;
 4206                cx.notify();
 4207            }
 4208        }
 4209        drop(context_menu);
 4210        let snapshot = self.snapshot(window, cx);
 4211        let deployed_from_indicator = action.deployed_from_indicator;
 4212        let mut task = self.code_actions_task.take();
 4213        let action = action.clone();
 4214        cx.spawn_in(window, |editor, mut cx| async move {
 4215            while let Some(prev_task) = task {
 4216                prev_task.await.log_err();
 4217                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4218            }
 4219
 4220            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4221                if editor.focus_handle.is_focused(window) {
 4222                    let multibuffer_point = action
 4223                        .deployed_from_indicator
 4224                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4225                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4226                    let (buffer, buffer_row) = snapshot
 4227                        .buffer_snapshot
 4228                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4229                        .and_then(|(buffer_snapshot, range)| {
 4230                            editor
 4231                                .buffer
 4232                                .read(cx)
 4233                                .buffer(buffer_snapshot.remote_id())
 4234                                .map(|buffer| (buffer, range.start.row))
 4235                        })?;
 4236                    let (_, code_actions) = editor
 4237                        .available_code_actions
 4238                        .clone()
 4239                        .and_then(|(location, code_actions)| {
 4240                            let snapshot = location.buffer.read(cx).snapshot();
 4241                            let point_range = location.range.to_point(&snapshot);
 4242                            let point_range = point_range.start.row..=point_range.end.row;
 4243                            if point_range.contains(&buffer_row) {
 4244                                Some((location, code_actions))
 4245                            } else {
 4246                                None
 4247                            }
 4248                        })
 4249                        .unzip();
 4250                    let buffer_id = buffer.read(cx).remote_id();
 4251                    let tasks = editor
 4252                        .tasks
 4253                        .get(&(buffer_id, buffer_row))
 4254                        .map(|t| Arc::new(t.to_owned()));
 4255                    if tasks.is_none() && code_actions.is_none() {
 4256                        return None;
 4257                    }
 4258
 4259                    editor.completion_tasks.clear();
 4260                    editor.discard_inline_completion(false, cx);
 4261                    let task_context =
 4262                        tasks
 4263                            .as_ref()
 4264                            .zip(editor.project.clone())
 4265                            .map(|(tasks, project)| {
 4266                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4267                            });
 4268
 4269                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4270                        let task_context = match task_context {
 4271                            Some(task_context) => task_context.await,
 4272                            None => None,
 4273                        };
 4274                        let resolved_tasks =
 4275                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4276                                Rc::new(ResolvedTasks {
 4277                                    templates: tasks.resolve(&task_context).collect(),
 4278                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4279                                        multibuffer_point.row,
 4280                                        tasks.column,
 4281                                    )),
 4282                                })
 4283                            });
 4284                        let spawn_straight_away = resolved_tasks
 4285                            .as_ref()
 4286                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4287                            && code_actions
 4288                                .as_ref()
 4289                                .map_or(true, |actions| actions.is_empty());
 4290                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4291                            *editor.context_menu.borrow_mut() =
 4292                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4293                                    buffer,
 4294                                    actions: CodeActionContents {
 4295                                        tasks: resolved_tasks,
 4296                                        actions: code_actions,
 4297                                    },
 4298                                    selected_item: Default::default(),
 4299                                    scroll_handle: UniformListScrollHandle::default(),
 4300                                    deployed_from_indicator,
 4301                                }));
 4302                            if spawn_straight_away {
 4303                                if let Some(task) = editor.confirm_code_action(
 4304                                    &ConfirmCodeAction { item_ix: Some(0) },
 4305                                    window,
 4306                                    cx,
 4307                                ) {
 4308                                    cx.notify();
 4309                                    return task;
 4310                                }
 4311                            }
 4312                            cx.notify();
 4313                            Task::ready(Ok(()))
 4314                        }) {
 4315                            task.await
 4316                        } else {
 4317                            Ok(())
 4318                        }
 4319                    }))
 4320                } else {
 4321                    Some(Task::ready(Ok(())))
 4322                }
 4323            })?;
 4324            if let Some(task) = spawned_test_task {
 4325                task.await?;
 4326            }
 4327
 4328            Ok::<_, anyhow::Error>(())
 4329        })
 4330        .detach_and_log_err(cx);
 4331    }
 4332
 4333    pub fn confirm_code_action(
 4334        &mut self,
 4335        action: &ConfirmCodeAction,
 4336        window: &mut Window,
 4337        cx: &mut Context<Self>,
 4338    ) -> Option<Task<Result<()>>> {
 4339        let actions_menu =
 4340            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4341                menu
 4342            } else {
 4343                return None;
 4344            };
 4345        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4346        let action = actions_menu.actions.get(action_ix)?;
 4347        let title = action.label();
 4348        let buffer = actions_menu.buffer;
 4349        let workspace = self.workspace()?;
 4350
 4351        match action {
 4352            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4353                workspace.update(cx, |workspace, cx| {
 4354                    workspace::tasks::schedule_resolved_task(
 4355                        workspace,
 4356                        task_source_kind,
 4357                        resolved_task,
 4358                        false,
 4359                        cx,
 4360                    );
 4361
 4362                    Some(Task::ready(Ok(())))
 4363                })
 4364            }
 4365            CodeActionsItem::CodeAction {
 4366                excerpt_id,
 4367                action,
 4368                provider,
 4369            } => {
 4370                let apply_code_action =
 4371                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4372                let workspace = workspace.downgrade();
 4373                Some(cx.spawn_in(window, |editor, cx| async move {
 4374                    let project_transaction = apply_code_action.await?;
 4375                    Self::open_project_transaction(
 4376                        &editor,
 4377                        workspace,
 4378                        project_transaction,
 4379                        title,
 4380                        cx,
 4381                    )
 4382                    .await
 4383                }))
 4384            }
 4385        }
 4386    }
 4387
 4388    pub async fn open_project_transaction(
 4389        this: &WeakEntity<Editor>,
 4390        workspace: WeakEntity<Workspace>,
 4391        transaction: ProjectTransaction,
 4392        title: String,
 4393        mut cx: AsyncWindowContext,
 4394    ) -> Result<()> {
 4395        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4396        cx.update(|_, cx| {
 4397            entries.sort_unstable_by_key(|(buffer, _)| {
 4398                buffer.read(cx).file().map(|f| f.path().clone())
 4399            });
 4400        })?;
 4401
 4402        // If the project transaction's edits are all contained within this editor, then
 4403        // avoid opening a new editor to display them.
 4404
 4405        if let Some((buffer, transaction)) = entries.first() {
 4406            if entries.len() == 1 {
 4407                let excerpt = this.update(&mut cx, |editor, cx| {
 4408                    editor
 4409                        .buffer()
 4410                        .read(cx)
 4411                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4412                })?;
 4413                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4414                    if excerpted_buffer == *buffer {
 4415                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4416                            let excerpt_range = excerpt_range.to_offset(buffer);
 4417                            buffer
 4418                                .edited_ranges_for_transaction::<usize>(transaction)
 4419                                .all(|range| {
 4420                                    excerpt_range.start <= range.start
 4421                                        && excerpt_range.end >= range.end
 4422                                })
 4423                        })?;
 4424
 4425                        if all_edits_within_excerpt {
 4426                            return Ok(());
 4427                        }
 4428                    }
 4429                }
 4430            }
 4431        } else {
 4432            return Ok(());
 4433        }
 4434
 4435        let mut ranges_to_highlight = Vec::new();
 4436        let excerpt_buffer = cx.new(|cx| {
 4437            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4438            for (buffer_handle, transaction) in &entries {
 4439                let buffer = buffer_handle.read(cx);
 4440                ranges_to_highlight.extend(
 4441                    multibuffer.push_excerpts_with_context_lines(
 4442                        buffer_handle.clone(),
 4443                        buffer
 4444                            .edited_ranges_for_transaction::<usize>(transaction)
 4445                            .collect(),
 4446                        DEFAULT_MULTIBUFFER_CONTEXT,
 4447                        cx,
 4448                    ),
 4449                );
 4450            }
 4451            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4452            multibuffer
 4453        })?;
 4454
 4455        workspace.update_in(&mut cx, |workspace, window, cx| {
 4456            let project = workspace.project().clone();
 4457            let editor = cx
 4458                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4459            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4460            editor.update(cx, |editor, cx| {
 4461                editor.highlight_background::<Self>(
 4462                    &ranges_to_highlight,
 4463                    |theme| theme.editor_highlighted_line_background,
 4464                    cx,
 4465                );
 4466            });
 4467        })?;
 4468
 4469        Ok(())
 4470    }
 4471
 4472    pub fn clear_code_action_providers(&mut self) {
 4473        self.code_action_providers.clear();
 4474        self.available_code_actions.take();
 4475    }
 4476
 4477    pub fn add_code_action_provider(
 4478        &mut self,
 4479        provider: Rc<dyn CodeActionProvider>,
 4480        window: &mut Window,
 4481        cx: &mut Context<Self>,
 4482    ) {
 4483        if self
 4484            .code_action_providers
 4485            .iter()
 4486            .any(|existing_provider| existing_provider.id() == provider.id())
 4487        {
 4488            return;
 4489        }
 4490
 4491        self.code_action_providers.push(provider);
 4492        self.refresh_code_actions(window, cx);
 4493    }
 4494
 4495    pub fn remove_code_action_provider(
 4496        &mut self,
 4497        id: Arc<str>,
 4498        window: &mut Window,
 4499        cx: &mut Context<Self>,
 4500    ) {
 4501        self.code_action_providers
 4502            .retain(|provider| provider.id() != id);
 4503        self.refresh_code_actions(window, cx);
 4504    }
 4505
 4506    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4507        let buffer = self.buffer.read(cx);
 4508        let newest_selection = self.selections.newest_anchor().clone();
 4509        if newest_selection.head().diff_base_anchor.is_some() {
 4510            return None;
 4511        }
 4512        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4513        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4514        if start_buffer != end_buffer {
 4515            return None;
 4516        }
 4517
 4518        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4519            cx.background_executor()
 4520                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4521                .await;
 4522
 4523            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4524                let providers = this.code_action_providers.clone();
 4525                let tasks = this
 4526                    .code_action_providers
 4527                    .iter()
 4528                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4529                    .collect::<Vec<_>>();
 4530                (providers, tasks)
 4531            })?;
 4532
 4533            let mut actions = Vec::new();
 4534            for (provider, provider_actions) in
 4535                providers.into_iter().zip(future::join_all(tasks).await)
 4536            {
 4537                if let Some(provider_actions) = provider_actions.log_err() {
 4538                    actions.extend(provider_actions.into_iter().map(|action| {
 4539                        AvailableCodeAction {
 4540                            excerpt_id: newest_selection.start.excerpt_id,
 4541                            action,
 4542                            provider: provider.clone(),
 4543                        }
 4544                    }));
 4545                }
 4546            }
 4547
 4548            this.update(&mut cx, |this, cx| {
 4549                this.available_code_actions = if actions.is_empty() {
 4550                    None
 4551                } else {
 4552                    Some((
 4553                        Location {
 4554                            buffer: start_buffer,
 4555                            range: start..end,
 4556                        },
 4557                        actions.into(),
 4558                    ))
 4559                };
 4560                cx.notify();
 4561            })
 4562        }));
 4563        None
 4564    }
 4565
 4566    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4567        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4568            self.show_git_blame_inline = false;
 4569
 4570            self.show_git_blame_inline_delay_task =
 4571                Some(cx.spawn_in(window, |this, mut cx| async move {
 4572                    cx.background_executor().timer(delay).await;
 4573
 4574                    this.update(&mut cx, |this, cx| {
 4575                        this.show_git_blame_inline = true;
 4576                        cx.notify();
 4577                    })
 4578                    .log_err();
 4579                }));
 4580        }
 4581    }
 4582
 4583    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4584        if self.pending_rename.is_some() {
 4585            return None;
 4586        }
 4587
 4588        let provider = self.semantics_provider.clone()?;
 4589        let buffer = self.buffer.read(cx);
 4590        let newest_selection = self.selections.newest_anchor().clone();
 4591        let cursor_position = newest_selection.head();
 4592        let (cursor_buffer, cursor_buffer_position) =
 4593            buffer.text_anchor_for_position(cursor_position, cx)?;
 4594        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4595        if cursor_buffer != tail_buffer {
 4596            return None;
 4597        }
 4598        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4599        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4600            cx.background_executor()
 4601                .timer(Duration::from_millis(debounce))
 4602                .await;
 4603
 4604            let highlights = if let Some(highlights) = cx
 4605                .update(|cx| {
 4606                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4607                })
 4608                .ok()
 4609                .flatten()
 4610            {
 4611                highlights.await.log_err()
 4612            } else {
 4613                None
 4614            };
 4615
 4616            if let Some(highlights) = highlights {
 4617                this.update(&mut cx, |this, cx| {
 4618                    if this.pending_rename.is_some() {
 4619                        return;
 4620                    }
 4621
 4622                    let buffer_id = cursor_position.buffer_id;
 4623                    let buffer = this.buffer.read(cx);
 4624                    if !buffer
 4625                        .text_anchor_for_position(cursor_position, cx)
 4626                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4627                    {
 4628                        return;
 4629                    }
 4630
 4631                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4632                    let mut write_ranges = Vec::new();
 4633                    let mut read_ranges = Vec::new();
 4634                    for highlight in highlights {
 4635                        for (excerpt_id, excerpt_range) in
 4636                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4637                        {
 4638                            let start = highlight
 4639                                .range
 4640                                .start
 4641                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4642                            let end = highlight
 4643                                .range
 4644                                .end
 4645                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4646                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4647                                continue;
 4648                            }
 4649
 4650                            let range = Anchor {
 4651                                buffer_id,
 4652                                excerpt_id,
 4653                                text_anchor: start,
 4654                                diff_base_anchor: None,
 4655                            }..Anchor {
 4656                                buffer_id,
 4657                                excerpt_id,
 4658                                text_anchor: end,
 4659                                diff_base_anchor: None,
 4660                            };
 4661                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4662                                write_ranges.push(range);
 4663                            } else {
 4664                                read_ranges.push(range);
 4665                            }
 4666                        }
 4667                    }
 4668
 4669                    this.highlight_background::<DocumentHighlightRead>(
 4670                        &read_ranges,
 4671                        |theme| theme.editor_document_highlight_read_background,
 4672                        cx,
 4673                    );
 4674                    this.highlight_background::<DocumentHighlightWrite>(
 4675                        &write_ranges,
 4676                        |theme| theme.editor_document_highlight_write_background,
 4677                        cx,
 4678                    );
 4679                    cx.notify();
 4680                })
 4681                .log_err();
 4682            }
 4683        }));
 4684        None
 4685    }
 4686
 4687    pub fn refresh_selected_text_highlights(
 4688        &mut self,
 4689        window: &mut Window,
 4690        cx: &mut Context<Editor>,
 4691    ) {
 4692        self.selection_highlight_task.take();
 4693        if !EditorSettings::get_global(cx).selection_highlight {
 4694            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4695            return;
 4696        }
 4697        if self.selections.count() != 1 || self.selections.line_mode {
 4698            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4699            return;
 4700        }
 4701        let selection = self.selections.newest::<Point>(cx);
 4702        if selection.is_empty() || selection.start.row != selection.end.row {
 4703            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4704            return;
 4705        }
 4706        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4707        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4708            cx.background_executor()
 4709                .timer(Duration::from_millis(debounce))
 4710                .await;
 4711            let Some(Some(matches_task)) = editor
 4712                .update_in(&mut cx, |editor, _, cx| {
 4713                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4714                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4715                        return None;
 4716                    }
 4717                    let selection = editor.selections.newest::<Point>(cx);
 4718                    if selection.is_empty() || selection.start.row != selection.end.row {
 4719                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4720                        return None;
 4721                    }
 4722                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4723                    Some(cx.background_spawn(async move {
 4724                        let mut ranges = Vec::new();
 4725                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4726                        let selection_anchors = selection.range().to_anchors(&buffer);
 4727                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4728                            for (search_buffer, search_range, excerpt_id) in
 4729                                buffer.range_to_buffer_ranges(range)
 4730                            {
 4731                                ranges.extend(
 4732                                    project::search::SearchQuery::text(
 4733                                        query.clone(),
 4734                                        false,
 4735                                        false,
 4736                                        false,
 4737                                        Default::default(),
 4738                                        Default::default(),
 4739                                        None,
 4740                                    )
 4741                                    .unwrap()
 4742                                    .search(search_buffer, Some(search_range.clone()))
 4743                                    .await
 4744                                    .into_iter()
 4745                                    .filter_map(
 4746                                        |match_range| {
 4747                                            let start = search_buffer.anchor_after(
 4748                                                search_range.start + match_range.start,
 4749                                            );
 4750                                            let end = search_buffer.anchor_before(
 4751                                                search_range.start + match_range.end,
 4752                                            );
 4753                                            let range = Anchor::range_in_buffer(
 4754                                                excerpt_id,
 4755                                                search_buffer.remote_id(),
 4756                                                start..end,
 4757                                            );
 4758                                            (range != selection_anchors).then_some(range)
 4759                                        },
 4760                                    ),
 4761                                );
 4762                            }
 4763                        }
 4764                        ranges
 4765                    }))
 4766                })
 4767                .log_err()
 4768            else {
 4769                return;
 4770            };
 4771            let matches = matches_task.await;
 4772            editor
 4773                .update_in(&mut cx, |editor, _, cx| {
 4774                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4775                    if !matches.is_empty() {
 4776                        editor.highlight_background::<SelectedTextHighlight>(
 4777                            &matches,
 4778                            |theme| theme.editor_document_highlight_bracket_background,
 4779                            cx,
 4780                        )
 4781                    }
 4782                })
 4783                .log_err();
 4784        }));
 4785    }
 4786
 4787    pub fn refresh_inline_completion(
 4788        &mut self,
 4789        debounce: bool,
 4790        user_requested: bool,
 4791        window: &mut Window,
 4792        cx: &mut Context<Self>,
 4793    ) -> Option<()> {
 4794        let provider = self.edit_prediction_provider()?;
 4795        let cursor = self.selections.newest_anchor().head();
 4796        let (buffer, cursor_buffer_position) =
 4797            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4798
 4799        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4800            self.discard_inline_completion(false, cx);
 4801            return None;
 4802        }
 4803
 4804        if !user_requested
 4805            && (!self.should_show_edit_predictions()
 4806                || !self.is_focused(window)
 4807                || buffer.read(cx).is_empty())
 4808        {
 4809            self.discard_inline_completion(false, cx);
 4810            return None;
 4811        }
 4812
 4813        self.update_visible_inline_completion(window, cx);
 4814        provider.refresh(
 4815            self.project.clone(),
 4816            buffer,
 4817            cursor_buffer_position,
 4818            debounce,
 4819            cx,
 4820        );
 4821        Some(())
 4822    }
 4823
 4824    fn show_edit_predictions_in_menu(&self) -> bool {
 4825        match self.edit_prediction_settings {
 4826            EditPredictionSettings::Disabled => false,
 4827            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4828        }
 4829    }
 4830
 4831    pub fn edit_predictions_enabled(&self) -> bool {
 4832        match self.edit_prediction_settings {
 4833            EditPredictionSettings::Disabled => false,
 4834            EditPredictionSettings::Enabled { .. } => true,
 4835        }
 4836    }
 4837
 4838    fn edit_prediction_requires_modifier(&self) -> bool {
 4839        match self.edit_prediction_settings {
 4840            EditPredictionSettings::Disabled => false,
 4841            EditPredictionSettings::Enabled {
 4842                preview_requires_modifier,
 4843                ..
 4844            } => preview_requires_modifier,
 4845        }
 4846    }
 4847
 4848    fn edit_prediction_settings_at_position(
 4849        &self,
 4850        buffer: &Entity<Buffer>,
 4851        buffer_position: language::Anchor,
 4852        cx: &App,
 4853    ) -> EditPredictionSettings {
 4854        if self.mode != EditorMode::Full
 4855            || !self.show_inline_completions_override.unwrap_or(true)
 4856            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4857        {
 4858            return EditPredictionSettings::Disabled;
 4859        }
 4860
 4861        let buffer = buffer.read(cx);
 4862
 4863        let file = buffer.file();
 4864
 4865        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4866            return EditPredictionSettings::Disabled;
 4867        };
 4868
 4869        let by_provider = matches!(
 4870            self.menu_inline_completions_policy,
 4871            MenuInlineCompletionsPolicy::ByProvider
 4872        );
 4873
 4874        let show_in_menu = by_provider
 4875            && self
 4876                .edit_prediction_provider
 4877                .as_ref()
 4878                .map_or(false, |provider| {
 4879                    provider.provider.show_completions_in_menu()
 4880                });
 4881
 4882        let preview_requires_modifier =
 4883            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4884
 4885        EditPredictionSettings::Enabled {
 4886            show_in_menu,
 4887            preview_requires_modifier,
 4888        }
 4889    }
 4890
 4891    fn should_show_edit_predictions(&self) -> bool {
 4892        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4893    }
 4894
 4895    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4896        matches!(
 4897            self.edit_prediction_preview,
 4898            EditPredictionPreview::Active { .. }
 4899        )
 4900    }
 4901
 4902    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4903        let cursor = self.selections.newest_anchor().head();
 4904        if let Some((buffer, cursor_position)) =
 4905            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4906        {
 4907            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4908        } else {
 4909            false
 4910        }
 4911    }
 4912
 4913    fn inline_completions_enabled_in_buffer(
 4914        &self,
 4915        buffer: &Entity<Buffer>,
 4916        buffer_position: language::Anchor,
 4917        cx: &App,
 4918    ) -> bool {
 4919        maybe!({
 4920            let provider = self.edit_prediction_provider()?;
 4921            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4922                return Some(false);
 4923            }
 4924            let buffer = buffer.read(cx);
 4925            let Some(file) = buffer.file() else {
 4926                return Some(true);
 4927            };
 4928            let settings = all_language_settings(Some(file), cx);
 4929            Some(settings.inline_completions_enabled_for_path(file.path()))
 4930        })
 4931        .unwrap_or(false)
 4932    }
 4933
 4934    fn cycle_inline_completion(
 4935        &mut self,
 4936        direction: Direction,
 4937        window: &mut Window,
 4938        cx: &mut Context<Self>,
 4939    ) -> Option<()> {
 4940        let provider = self.edit_prediction_provider()?;
 4941        let cursor = self.selections.newest_anchor().head();
 4942        let (buffer, cursor_buffer_position) =
 4943            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4944        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4945            return None;
 4946        }
 4947
 4948        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4949        self.update_visible_inline_completion(window, cx);
 4950
 4951        Some(())
 4952    }
 4953
 4954    pub fn show_inline_completion(
 4955        &mut self,
 4956        _: &ShowEditPrediction,
 4957        window: &mut Window,
 4958        cx: &mut Context<Self>,
 4959    ) {
 4960        if !self.has_active_inline_completion() {
 4961            self.refresh_inline_completion(false, true, window, cx);
 4962            return;
 4963        }
 4964
 4965        self.update_visible_inline_completion(window, cx);
 4966    }
 4967
 4968    pub fn display_cursor_names(
 4969        &mut self,
 4970        _: &DisplayCursorNames,
 4971        window: &mut Window,
 4972        cx: &mut Context<Self>,
 4973    ) {
 4974        self.show_cursor_names(window, cx);
 4975    }
 4976
 4977    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4978        self.show_cursor_names = true;
 4979        cx.notify();
 4980        cx.spawn_in(window, |this, mut cx| async move {
 4981            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4982            this.update(&mut cx, |this, cx| {
 4983                this.show_cursor_names = false;
 4984                cx.notify()
 4985            })
 4986            .ok()
 4987        })
 4988        .detach();
 4989    }
 4990
 4991    pub fn next_edit_prediction(
 4992        &mut self,
 4993        _: &NextEditPrediction,
 4994        window: &mut Window,
 4995        cx: &mut Context<Self>,
 4996    ) {
 4997        if self.has_active_inline_completion() {
 4998            self.cycle_inline_completion(Direction::Next, window, cx);
 4999        } else {
 5000            let is_copilot_disabled = self
 5001                .refresh_inline_completion(false, true, window, cx)
 5002                .is_none();
 5003            if is_copilot_disabled {
 5004                cx.propagate();
 5005            }
 5006        }
 5007    }
 5008
 5009    pub fn previous_edit_prediction(
 5010        &mut self,
 5011        _: &PreviousEditPrediction,
 5012        window: &mut Window,
 5013        cx: &mut Context<Self>,
 5014    ) {
 5015        if self.has_active_inline_completion() {
 5016            self.cycle_inline_completion(Direction::Prev, window, cx);
 5017        } else {
 5018            let is_copilot_disabled = self
 5019                .refresh_inline_completion(false, true, window, cx)
 5020                .is_none();
 5021            if is_copilot_disabled {
 5022                cx.propagate();
 5023            }
 5024        }
 5025    }
 5026
 5027    pub fn accept_edit_prediction(
 5028        &mut self,
 5029        _: &AcceptEditPrediction,
 5030        window: &mut Window,
 5031        cx: &mut Context<Self>,
 5032    ) {
 5033        if self.show_edit_predictions_in_menu() {
 5034            self.hide_context_menu(window, cx);
 5035        }
 5036
 5037        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5038            return;
 5039        };
 5040
 5041        self.report_inline_completion_event(
 5042            active_inline_completion.completion_id.clone(),
 5043            true,
 5044            cx,
 5045        );
 5046
 5047        match &active_inline_completion.completion {
 5048            InlineCompletion::Move { target, .. } => {
 5049                let target = *target;
 5050
 5051                if let Some(position_map) = &self.last_position_map {
 5052                    if position_map
 5053                        .visible_row_range
 5054                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5055                        || !self.edit_prediction_requires_modifier()
 5056                    {
 5057                        self.unfold_ranges(&[target..target], true, false, cx);
 5058                        // Note that this is also done in vim's handler of the Tab action.
 5059                        self.change_selections(
 5060                            Some(Autoscroll::newest()),
 5061                            window,
 5062                            cx,
 5063                            |selections| {
 5064                                selections.select_anchor_ranges([target..target]);
 5065                            },
 5066                        );
 5067                        self.clear_row_highlights::<EditPredictionPreview>();
 5068
 5069                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5070                            previous_scroll_position: None,
 5071                        };
 5072                    } else {
 5073                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5074                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5075                        };
 5076                        self.highlight_rows::<EditPredictionPreview>(
 5077                            target..target,
 5078                            cx.theme().colors().editor_highlighted_line_background,
 5079                            true,
 5080                            cx,
 5081                        );
 5082                        self.request_autoscroll(Autoscroll::fit(), cx);
 5083                    }
 5084                }
 5085            }
 5086            InlineCompletion::Edit { edits, .. } => {
 5087                if let Some(provider) = self.edit_prediction_provider() {
 5088                    provider.accept(cx);
 5089                }
 5090
 5091                let snapshot = self.buffer.read(cx).snapshot(cx);
 5092                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5093
 5094                self.buffer.update(cx, |buffer, cx| {
 5095                    buffer.edit(edits.iter().cloned(), None, cx)
 5096                });
 5097
 5098                self.change_selections(None, window, cx, |s| {
 5099                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5100                });
 5101
 5102                self.update_visible_inline_completion(window, cx);
 5103                if self.active_inline_completion.is_none() {
 5104                    self.refresh_inline_completion(true, true, window, cx);
 5105                }
 5106
 5107                cx.notify();
 5108            }
 5109        }
 5110
 5111        self.edit_prediction_requires_modifier_in_leading_space = false;
 5112    }
 5113
 5114    pub fn accept_partial_inline_completion(
 5115        &mut self,
 5116        _: &AcceptPartialEditPrediction,
 5117        window: &mut Window,
 5118        cx: &mut Context<Self>,
 5119    ) {
 5120        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5121            return;
 5122        };
 5123        if self.selections.count() != 1 {
 5124            return;
 5125        }
 5126
 5127        self.report_inline_completion_event(
 5128            active_inline_completion.completion_id.clone(),
 5129            true,
 5130            cx,
 5131        );
 5132
 5133        match &active_inline_completion.completion {
 5134            InlineCompletion::Move { target, .. } => {
 5135                let target = *target;
 5136                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5137                    selections.select_anchor_ranges([target..target]);
 5138                });
 5139            }
 5140            InlineCompletion::Edit { edits, .. } => {
 5141                // Find an insertion that starts at the cursor position.
 5142                let snapshot = self.buffer.read(cx).snapshot(cx);
 5143                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5144                let insertion = edits.iter().find_map(|(range, text)| {
 5145                    let range = range.to_offset(&snapshot);
 5146                    if range.is_empty() && range.start == cursor_offset {
 5147                        Some(text)
 5148                    } else {
 5149                        None
 5150                    }
 5151                });
 5152
 5153                if let Some(text) = insertion {
 5154                    let mut partial_completion = text
 5155                        .chars()
 5156                        .by_ref()
 5157                        .take_while(|c| c.is_alphabetic())
 5158                        .collect::<String>();
 5159                    if partial_completion.is_empty() {
 5160                        partial_completion = text
 5161                            .chars()
 5162                            .by_ref()
 5163                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5164                            .collect::<String>();
 5165                    }
 5166
 5167                    cx.emit(EditorEvent::InputHandled {
 5168                        utf16_range_to_replace: None,
 5169                        text: partial_completion.clone().into(),
 5170                    });
 5171
 5172                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5173
 5174                    self.refresh_inline_completion(true, true, window, cx);
 5175                    cx.notify();
 5176                } else {
 5177                    self.accept_edit_prediction(&Default::default(), window, cx);
 5178                }
 5179            }
 5180        }
 5181    }
 5182
 5183    fn discard_inline_completion(
 5184        &mut self,
 5185        should_report_inline_completion_event: bool,
 5186        cx: &mut Context<Self>,
 5187    ) -> bool {
 5188        if should_report_inline_completion_event {
 5189            let completion_id = self
 5190                .active_inline_completion
 5191                .as_ref()
 5192                .and_then(|active_completion| active_completion.completion_id.clone());
 5193
 5194            self.report_inline_completion_event(completion_id, false, cx);
 5195        }
 5196
 5197        if let Some(provider) = self.edit_prediction_provider() {
 5198            provider.discard(cx);
 5199        }
 5200
 5201        self.take_active_inline_completion(cx)
 5202    }
 5203
 5204    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5205        let Some(provider) = self.edit_prediction_provider() else {
 5206            return;
 5207        };
 5208
 5209        let Some((_, buffer, _)) = self
 5210            .buffer
 5211            .read(cx)
 5212            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5213        else {
 5214            return;
 5215        };
 5216
 5217        let extension = buffer
 5218            .read(cx)
 5219            .file()
 5220            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5221
 5222        let event_type = match accepted {
 5223            true => "Edit Prediction Accepted",
 5224            false => "Edit Prediction Discarded",
 5225        };
 5226        telemetry::event!(
 5227            event_type,
 5228            provider = provider.name(),
 5229            prediction_id = id,
 5230            suggestion_accepted = accepted,
 5231            file_extension = extension,
 5232        );
 5233    }
 5234
 5235    pub fn has_active_inline_completion(&self) -> bool {
 5236        self.active_inline_completion.is_some()
 5237    }
 5238
 5239    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5240        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5241            return false;
 5242        };
 5243
 5244        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5245        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5246        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5247        true
 5248    }
 5249
 5250    /// Returns true when we're displaying the edit prediction popover below the cursor
 5251    /// like we are not previewing and the LSP autocomplete menu is visible
 5252    /// or we are in `when_holding_modifier` mode.
 5253    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5254        if self.edit_prediction_preview_is_active()
 5255            || !self.show_edit_predictions_in_menu()
 5256            || !self.edit_predictions_enabled()
 5257        {
 5258            return false;
 5259        }
 5260
 5261        if self.has_visible_completions_menu() {
 5262            return true;
 5263        }
 5264
 5265        has_completion && self.edit_prediction_requires_modifier()
 5266    }
 5267
 5268    fn handle_modifiers_changed(
 5269        &mut self,
 5270        modifiers: Modifiers,
 5271        position_map: &PositionMap,
 5272        window: &mut Window,
 5273        cx: &mut Context<Self>,
 5274    ) {
 5275        if self.show_edit_predictions_in_menu() {
 5276            self.update_edit_prediction_preview(&modifiers, window, cx);
 5277        }
 5278
 5279        self.update_selection_mode(&modifiers, position_map, window, cx);
 5280
 5281        let mouse_position = window.mouse_position();
 5282        if !position_map.text_hitbox.is_hovered(window) {
 5283            return;
 5284        }
 5285
 5286        self.update_hovered_link(
 5287            position_map.point_for_position(mouse_position),
 5288            &position_map.snapshot,
 5289            modifiers,
 5290            window,
 5291            cx,
 5292        )
 5293    }
 5294
 5295    fn update_selection_mode(
 5296        &mut self,
 5297        modifiers: &Modifiers,
 5298        position_map: &PositionMap,
 5299        window: &mut Window,
 5300        cx: &mut Context<Self>,
 5301    ) {
 5302        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5303            return;
 5304        }
 5305
 5306        let mouse_position = window.mouse_position();
 5307        let point_for_position = position_map.point_for_position(mouse_position);
 5308        let position = point_for_position.previous_valid;
 5309
 5310        self.select(
 5311            SelectPhase::BeginColumnar {
 5312                position,
 5313                reset: false,
 5314                goal_column: point_for_position.exact_unclipped.column(),
 5315            },
 5316            window,
 5317            cx,
 5318        );
 5319    }
 5320
 5321    fn update_edit_prediction_preview(
 5322        &mut self,
 5323        modifiers: &Modifiers,
 5324        window: &mut Window,
 5325        cx: &mut Context<Self>,
 5326    ) {
 5327        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5328        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5329            return;
 5330        };
 5331
 5332        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5333            if matches!(
 5334                self.edit_prediction_preview,
 5335                EditPredictionPreview::Inactive
 5336            ) {
 5337                self.edit_prediction_preview = EditPredictionPreview::Active {
 5338                    previous_scroll_position: None,
 5339                };
 5340
 5341                self.update_visible_inline_completion(window, cx);
 5342                cx.notify();
 5343            }
 5344        } else if let EditPredictionPreview::Active {
 5345            previous_scroll_position,
 5346        } = self.edit_prediction_preview
 5347        {
 5348            if let (Some(previous_scroll_position), Some(position_map)) =
 5349                (previous_scroll_position, self.last_position_map.as_ref())
 5350            {
 5351                self.set_scroll_position(
 5352                    previous_scroll_position
 5353                        .scroll_position(&position_map.snapshot.display_snapshot),
 5354                    window,
 5355                    cx,
 5356                );
 5357            }
 5358
 5359            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5360            self.clear_row_highlights::<EditPredictionPreview>();
 5361            self.update_visible_inline_completion(window, cx);
 5362            cx.notify();
 5363        }
 5364    }
 5365
 5366    fn update_visible_inline_completion(
 5367        &mut self,
 5368        _window: &mut Window,
 5369        cx: &mut Context<Self>,
 5370    ) -> Option<()> {
 5371        let selection = self.selections.newest_anchor();
 5372        let cursor = selection.head();
 5373        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5374        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5375        let excerpt_id = cursor.excerpt_id;
 5376
 5377        let show_in_menu = self.show_edit_predictions_in_menu();
 5378        let completions_menu_has_precedence = !show_in_menu
 5379            && (self.context_menu.borrow().is_some()
 5380                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5381
 5382        if completions_menu_has_precedence
 5383            || !offset_selection.is_empty()
 5384            || self
 5385                .active_inline_completion
 5386                .as_ref()
 5387                .map_or(false, |completion| {
 5388                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5389                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5390                    !invalidation_range.contains(&offset_selection.head())
 5391                })
 5392        {
 5393            self.discard_inline_completion(false, cx);
 5394            return None;
 5395        }
 5396
 5397        self.take_active_inline_completion(cx);
 5398        let Some(provider) = self.edit_prediction_provider() else {
 5399            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5400            return None;
 5401        };
 5402
 5403        let (buffer, cursor_buffer_position) =
 5404            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5405
 5406        self.edit_prediction_settings =
 5407            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5408
 5409        self.edit_prediction_cursor_on_leading_whitespace =
 5410            multibuffer.is_line_whitespace_upto(cursor);
 5411
 5412        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5413        let edits = inline_completion
 5414            .edits
 5415            .into_iter()
 5416            .flat_map(|(range, new_text)| {
 5417                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5418                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5419                Some((start..end, new_text))
 5420            })
 5421            .collect::<Vec<_>>();
 5422        if edits.is_empty() {
 5423            return None;
 5424        }
 5425
 5426        let first_edit_start = edits.first().unwrap().0.start;
 5427        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5428        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5429
 5430        let last_edit_end = edits.last().unwrap().0.end;
 5431        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5432        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5433
 5434        let cursor_row = cursor.to_point(&multibuffer).row;
 5435
 5436        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5437
 5438        let mut inlay_ids = Vec::new();
 5439        let invalidation_row_range;
 5440        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5441            Some(cursor_row..edit_end_row)
 5442        } else if cursor_row > edit_end_row {
 5443            Some(edit_start_row..cursor_row)
 5444        } else {
 5445            None
 5446        };
 5447        let is_move =
 5448            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5449        let completion = if is_move {
 5450            invalidation_row_range =
 5451                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5452            let target = first_edit_start;
 5453            InlineCompletion::Move { target, snapshot }
 5454        } else {
 5455            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5456                && !self.inline_completions_hidden_for_vim_mode;
 5457
 5458            if show_completions_in_buffer {
 5459                if edits
 5460                    .iter()
 5461                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5462                {
 5463                    let mut inlays = Vec::new();
 5464                    for (range, new_text) in &edits {
 5465                        let inlay = Inlay::inline_completion(
 5466                            post_inc(&mut self.next_inlay_id),
 5467                            range.start,
 5468                            new_text.as_str(),
 5469                        );
 5470                        inlay_ids.push(inlay.id);
 5471                        inlays.push(inlay);
 5472                    }
 5473
 5474                    self.splice_inlays(&[], inlays, cx);
 5475                } else {
 5476                    let background_color = cx.theme().status().deleted_background;
 5477                    self.highlight_text::<InlineCompletionHighlight>(
 5478                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5479                        HighlightStyle {
 5480                            background_color: Some(background_color),
 5481                            ..Default::default()
 5482                        },
 5483                        cx,
 5484                    );
 5485                }
 5486            }
 5487
 5488            invalidation_row_range = edit_start_row..edit_end_row;
 5489
 5490            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5491                if provider.show_tab_accept_marker() {
 5492                    EditDisplayMode::TabAccept
 5493                } else {
 5494                    EditDisplayMode::Inline
 5495                }
 5496            } else {
 5497                EditDisplayMode::DiffPopover
 5498            };
 5499
 5500            InlineCompletion::Edit {
 5501                edits,
 5502                edit_preview: inline_completion.edit_preview,
 5503                display_mode,
 5504                snapshot,
 5505            }
 5506        };
 5507
 5508        let invalidation_range = multibuffer
 5509            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5510            ..multibuffer.anchor_after(Point::new(
 5511                invalidation_row_range.end,
 5512                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5513            ));
 5514
 5515        self.stale_inline_completion_in_menu = None;
 5516        self.active_inline_completion = Some(InlineCompletionState {
 5517            inlay_ids,
 5518            completion,
 5519            completion_id: inline_completion.id,
 5520            invalidation_range,
 5521        });
 5522
 5523        cx.notify();
 5524
 5525        Some(())
 5526    }
 5527
 5528    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5529        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5530    }
 5531
 5532    fn render_code_actions_indicator(
 5533        &self,
 5534        _style: &EditorStyle,
 5535        row: DisplayRow,
 5536        is_active: bool,
 5537        cx: &mut Context<Self>,
 5538    ) -> Option<IconButton> {
 5539        if self.available_code_actions.is_some() {
 5540            Some(
 5541                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5542                    .shape(ui::IconButtonShape::Square)
 5543                    .icon_size(IconSize::XSmall)
 5544                    .icon_color(Color::Muted)
 5545                    .toggle_state(is_active)
 5546                    .tooltip({
 5547                        let focus_handle = self.focus_handle.clone();
 5548                        move |window, cx| {
 5549                            Tooltip::for_action_in(
 5550                                "Toggle Code Actions",
 5551                                &ToggleCodeActions {
 5552                                    deployed_from_indicator: None,
 5553                                },
 5554                                &focus_handle,
 5555                                window,
 5556                                cx,
 5557                            )
 5558                        }
 5559                    })
 5560                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5561                        window.focus(&editor.focus_handle(cx));
 5562                        editor.toggle_code_actions(
 5563                            &ToggleCodeActions {
 5564                                deployed_from_indicator: Some(row),
 5565                            },
 5566                            window,
 5567                            cx,
 5568                        );
 5569                    })),
 5570            )
 5571        } else {
 5572            None
 5573        }
 5574    }
 5575
 5576    fn clear_tasks(&mut self) {
 5577        self.tasks.clear()
 5578    }
 5579
 5580    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5581        if self.tasks.insert(key, value).is_some() {
 5582            // This case should hopefully be rare, but just in case...
 5583            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5584        }
 5585    }
 5586
 5587    fn build_tasks_context(
 5588        project: &Entity<Project>,
 5589        buffer: &Entity<Buffer>,
 5590        buffer_row: u32,
 5591        tasks: &Arc<RunnableTasks>,
 5592        cx: &mut Context<Self>,
 5593    ) -> Task<Option<task::TaskContext>> {
 5594        let position = Point::new(buffer_row, tasks.column);
 5595        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5596        let location = Location {
 5597            buffer: buffer.clone(),
 5598            range: range_start..range_start,
 5599        };
 5600        // Fill in the environmental variables from the tree-sitter captures
 5601        let mut captured_task_variables = TaskVariables::default();
 5602        for (capture_name, value) in tasks.extra_variables.clone() {
 5603            captured_task_variables.insert(
 5604                task::VariableName::Custom(capture_name.into()),
 5605                value.clone(),
 5606            );
 5607        }
 5608        project.update(cx, |project, cx| {
 5609            project.task_store().update(cx, |task_store, cx| {
 5610                task_store.task_context_for_location(captured_task_variables, location, cx)
 5611            })
 5612        })
 5613    }
 5614
 5615    pub fn spawn_nearest_task(
 5616        &mut self,
 5617        action: &SpawnNearestTask,
 5618        window: &mut Window,
 5619        cx: &mut Context<Self>,
 5620    ) {
 5621        let Some((workspace, _)) = self.workspace.clone() else {
 5622            return;
 5623        };
 5624        let Some(project) = self.project.clone() else {
 5625            return;
 5626        };
 5627
 5628        // Try to find a closest, enclosing node using tree-sitter that has a
 5629        // task
 5630        let Some((buffer, buffer_row, tasks)) = self
 5631            .find_enclosing_node_task(cx)
 5632            // Or find the task that's closest in row-distance.
 5633            .or_else(|| self.find_closest_task(cx))
 5634        else {
 5635            return;
 5636        };
 5637
 5638        let reveal_strategy = action.reveal;
 5639        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5640        cx.spawn_in(window, |_, mut cx| async move {
 5641            let context = task_context.await?;
 5642            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5643
 5644            let resolved = resolved_task.resolved.as_mut()?;
 5645            resolved.reveal = reveal_strategy;
 5646
 5647            workspace
 5648                .update(&mut cx, |workspace, cx| {
 5649                    workspace::tasks::schedule_resolved_task(
 5650                        workspace,
 5651                        task_source_kind,
 5652                        resolved_task,
 5653                        false,
 5654                        cx,
 5655                    );
 5656                })
 5657                .ok()
 5658        })
 5659        .detach();
 5660    }
 5661
 5662    fn find_closest_task(
 5663        &mut self,
 5664        cx: &mut Context<Self>,
 5665    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5666        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5667
 5668        let ((buffer_id, row), tasks) = self
 5669            .tasks
 5670            .iter()
 5671            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5672
 5673        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5674        let tasks = Arc::new(tasks.to_owned());
 5675        Some((buffer, *row, tasks))
 5676    }
 5677
 5678    fn find_enclosing_node_task(
 5679        &mut self,
 5680        cx: &mut Context<Self>,
 5681    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5682        let snapshot = self.buffer.read(cx).snapshot(cx);
 5683        let offset = self.selections.newest::<usize>(cx).head();
 5684        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5685        let buffer_id = excerpt.buffer().remote_id();
 5686
 5687        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5688        let mut cursor = layer.node().walk();
 5689
 5690        while cursor.goto_first_child_for_byte(offset).is_some() {
 5691            if cursor.node().end_byte() == offset {
 5692                cursor.goto_next_sibling();
 5693            }
 5694        }
 5695
 5696        // Ascend to the smallest ancestor that contains the range and has a task.
 5697        loop {
 5698            let node = cursor.node();
 5699            let node_range = node.byte_range();
 5700            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5701
 5702            // Check if this node contains our offset
 5703            if node_range.start <= offset && node_range.end >= offset {
 5704                // If it contains offset, check for task
 5705                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5706                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5707                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5708                }
 5709            }
 5710
 5711            if !cursor.goto_parent() {
 5712                break;
 5713            }
 5714        }
 5715        None
 5716    }
 5717
 5718    fn render_run_indicator(
 5719        &self,
 5720        _style: &EditorStyle,
 5721        is_active: bool,
 5722        row: DisplayRow,
 5723        cx: &mut Context<Self>,
 5724    ) -> IconButton {
 5725        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5726            .shape(ui::IconButtonShape::Square)
 5727            .icon_size(IconSize::XSmall)
 5728            .icon_color(Color::Muted)
 5729            .toggle_state(is_active)
 5730            .on_click(cx.listener(move |editor, _e, window, cx| {
 5731                window.focus(&editor.focus_handle(cx));
 5732                editor.toggle_code_actions(
 5733                    &ToggleCodeActions {
 5734                        deployed_from_indicator: Some(row),
 5735                    },
 5736                    window,
 5737                    cx,
 5738                );
 5739            }))
 5740    }
 5741
 5742    pub fn context_menu_visible(&self) -> bool {
 5743        !self.edit_prediction_preview_is_active()
 5744            && self
 5745                .context_menu
 5746                .borrow()
 5747                .as_ref()
 5748                .map_or(false, |menu| menu.visible())
 5749    }
 5750
 5751    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5752        self.context_menu
 5753            .borrow()
 5754            .as_ref()
 5755            .map(|menu| menu.origin())
 5756    }
 5757
 5758    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5759        px(30.)
 5760    }
 5761
 5762    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5763        if self.read_only(cx) {
 5764            cx.theme().players().read_only()
 5765        } else {
 5766            self.style.as_ref().unwrap().local_player
 5767        }
 5768    }
 5769
 5770    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5771        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5772        let accept_keystroke = accept_binding.keystroke()?;
 5773
 5774        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5775
 5776        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5777            Color::Accent
 5778        } else {
 5779            Color::Muted
 5780        };
 5781
 5782        h_flex()
 5783            .px_0p5()
 5784            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5785            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5786            .text_size(TextSize::XSmall.rems(cx))
 5787            .child(h_flex().children(ui::render_modifiers(
 5788                &accept_keystroke.modifiers,
 5789                PlatformStyle::platform(),
 5790                Some(modifiers_color),
 5791                Some(IconSize::XSmall.rems().into()),
 5792                true,
 5793            )))
 5794            .when(is_platform_style_mac, |parent| {
 5795                parent.child(accept_keystroke.key.clone())
 5796            })
 5797            .when(!is_platform_style_mac, |parent| {
 5798                parent.child(
 5799                    Key::new(
 5800                        util::capitalize(&accept_keystroke.key),
 5801                        Some(Color::Default),
 5802                    )
 5803                    .size(Some(IconSize::XSmall.rems().into())),
 5804                )
 5805            })
 5806            .into()
 5807    }
 5808
 5809    fn render_edit_prediction_line_popover(
 5810        &self,
 5811        label: impl Into<SharedString>,
 5812        icon: Option<IconName>,
 5813        window: &mut Window,
 5814        cx: &App,
 5815    ) -> Option<Div> {
 5816        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5817
 5818        let result = h_flex()
 5819            .py_0p5()
 5820            .pl_1()
 5821            .pr(padding_right)
 5822            .gap_1()
 5823            .rounded(px(6.))
 5824            .border_1()
 5825            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5826            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 5827            .shadow_sm()
 5828            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5829            .child(Label::new(label).size(LabelSize::Small))
 5830            .when_some(icon, |element, icon| {
 5831                element.child(
 5832                    div()
 5833                        .mt(px(1.5))
 5834                        .child(Icon::new(icon).size(IconSize::Small)),
 5835                )
 5836            });
 5837
 5838        Some(result)
 5839    }
 5840
 5841    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5842        let accent_color = cx.theme().colors().text_accent;
 5843        let editor_bg_color = cx.theme().colors().editor_background;
 5844        editor_bg_color.blend(accent_color.opacity(0.1))
 5845    }
 5846
 5847    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 5848        let accent_color = cx.theme().colors().text_accent;
 5849        let editor_bg_color = cx.theme().colors().editor_background;
 5850        editor_bg_color.blend(accent_color.opacity(0.6))
 5851    }
 5852
 5853    #[allow(clippy::too_many_arguments)]
 5854    fn render_edit_prediction_cursor_popover(
 5855        &self,
 5856        min_width: Pixels,
 5857        max_width: Pixels,
 5858        cursor_point: Point,
 5859        style: &EditorStyle,
 5860        accept_keystroke: Option<&gpui::Keystroke>,
 5861        _window: &Window,
 5862        cx: &mut Context<Editor>,
 5863    ) -> Option<AnyElement> {
 5864        let provider = self.edit_prediction_provider.as_ref()?;
 5865
 5866        if provider.provider.needs_terms_acceptance(cx) {
 5867            return Some(
 5868                h_flex()
 5869                    .min_w(min_width)
 5870                    .flex_1()
 5871                    .px_2()
 5872                    .py_1()
 5873                    .gap_3()
 5874                    .elevation_2(cx)
 5875                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5876                    .id("accept-terms")
 5877                    .cursor_pointer()
 5878                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5879                    .on_click(cx.listener(|this, _event, window, cx| {
 5880                        cx.stop_propagation();
 5881                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5882                        window.dispatch_action(
 5883                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5884                            cx,
 5885                        );
 5886                    }))
 5887                    .child(
 5888                        h_flex()
 5889                            .flex_1()
 5890                            .gap_2()
 5891                            .child(Icon::new(IconName::ZedPredict))
 5892                            .child(Label::new("Accept Terms of Service"))
 5893                            .child(div().w_full())
 5894                            .child(
 5895                                Icon::new(IconName::ArrowUpRight)
 5896                                    .color(Color::Muted)
 5897                                    .size(IconSize::Small),
 5898                            )
 5899                            .into_any_element(),
 5900                    )
 5901                    .into_any(),
 5902            );
 5903        }
 5904
 5905        let is_refreshing = provider.provider.is_refreshing(cx);
 5906
 5907        fn pending_completion_container() -> Div {
 5908            h_flex()
 5909                .h_full()
 5910                .flex_1()
 5911                .gap_2()
 5912                .child(Icon::new(IconName::ZedPredict))
 5913        }
 5914
 5915        let completion = match &self.active_inline_completion {
 5916            Some(completion) => match &completion.completion {
 5917                InlineCompletion::Move {
 5918                    target, snapshot, ..
 5919                } if !self.has_visible_completions_menu() => {
 5920                    use text::ToPoint as _;
 5921
 5922                    return Some(
 5923                        h_flex()
 5924                            .px_2()
 5925                            .py_1()
 5926                            .gap_2()
 5927                            .elevation_2(cx)
 5928                            .border_color(cx.theme().colors().border)
 5929                            .rounded(px(6.))
 5930                            .rounded_tl(px(0.))
 5931                            .child(
 5932                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5933                                    Icon::new(IconName::ZedPredictDown)
 5934                                } else {
 5935                                    Icon::new(IconName::ZedPredictUp)
 5936                                },
 5937                            )
 5938                            .child(Label::new("Hold").size(LabelSize::Small))
 5939                            .child(h_flex().children(ui::render_modifiers(
 5940                                &accept_keystroke?.modifiers,
 5941                                PlatformStyle::platform(),
 5942                                Some(Color::Default),
 5943                                Some(IconSize::Small.rems().into()),
 5944                                false,
 5945                            )))
 5946                            .into_any(),
 5947                    );
 5948                }
 5949                _ => self.render_edit_prediction_cursor_popover_preview(
 5950                    completion,
 5951                    cursor_point,
 5952                    style,
 5953                    cx,
 5954                )?,
 5955            },
 5956
 5957            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5958                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5959                    stale_completion,
 5960                    cursor_point,
 5961                    style,
 5962                    cx,
 5963                )?,
 5964
 5965                None => {
 5966                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5967                }
 5968            },
 5969
 5970            None => pending_completion_container().child(Label::new("No Prediction")),
 5971        };
 5972
 5973        let completion = if is_refreshing {
 5974            completion
 5975                .with_animation(
 5976                    "loading-completion",
 5977                    Animation::new(Duration::from_secs(2))
 5978                        .repeat()
 5979                        .with_easing(pulsating_between(0.4, 0.8)),
 5980                    |label, delta| label.opacity(delta),
 5981                )
 5982                .into_any_element()
 5983        } else {
 5984            completion.into_any_element()
 5985        };
 5986
 5987        let has_completion = self.active_inline_completion.is_some();
 5988
 5989        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5990        Some(
 5991            h_flex()
 5992                .min_w(min_width)
 5993                .max_w(max_width)
 5994                .flex_1()
 5995                .elevation_2(cx)
 5996                .border_color(cx.theme().colors().border)
 5997                .child(
 5998                    div()
 5999                        .flex_1()
 6000                        .py_1()
 6001                        .px_2()
 6002                        .overflow_hidden()
 6003                        .child(completion),
 6004                )
 6005                .when_some(accept_keystroke, |el, accept_keystroke| {
 6006                    if !accept_keystroke.modifiers.modified() {
 6007                        return el;
 6008                    }
 6009
 6010                    el.child(
 6011                        h_flex()
 6012                            .h_full()
 6013                            .border_l_1()
 6014                            .rounded_r_lg()
 6015                            .border_color(cx.theme().colors().border)
 6016                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6017                            .gap_1()
 6018                            .py_1()
 6019                            .px_2()
 6020                            .child(
 6021                                h_flex()
 6022                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6023                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6024                                    .child(h_flex().children(ui::render_modifiers(
 6025                                        &accept_keystroke.modifiers,
 6026                                        PlatformStyle::platform(),
 6027                                        Some(if !has_completion {
 6028                                            Color::Muted
 6029                                        } else {
 6030                                            Color::Default
 6031                                        }),
 6032                                        None,
 6033                                        false,
 6034                                    ))),
 6035                            )
 6036                            .child(Label::new("Preview").into_any_element())
 6037                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6038                    )
 6039                })
 6040                .into_any(),
 6041        )
 6042    }
 6043
 6044    fn render_edit_prediction_cursor_popover_preview(
 6045        &self,
 6046        completion: &InlineCompletionState,
 6047        cursor_point: Point,
 6048        style: &EditorStyle,
 6049        cx: &mut Context<Editor>,
 6050    ) -> Option<Div> {
 6051        use text::ToPoint as _;
 6052
 6053        fn render_relative_row_jump(
 6054            prefix: impl Into<String>,
 6055            current_row: u32,
 6056            target_row: u32,
 6057        ) -> Div {
 6058            let (row_diff, arrow) = if target_row < current_row {
 6059                (current_row - target_row, IconName::ArrowUp)
 6060            } else {
 6061                (target_row - current_row, IconName::ArrowDown)
 6062            };
 6063
 6064            h_flex()
 6065                .child(
 6066                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6067                        .color(Color::Muted)
 6068                        .size(LabelSize::Small),
 6069                )
 6070                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6071        }
 6072
 6073        match &completion.completion {
 6074            InlineCompletion::Move {
 6075                target, snapshot, ..
 6076            } => Some(
 6077                h_flex()
 6078                    .px_2()
 6079                    .gap_2()
 6080                    .flex_1()
 6081                    .child(
 6082                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6083                            Icon::new(IconName::ZedPredictDown)
 6084                        } else {
 6085                            Icon::new(IconName::ZedPredictUp)
 6086                        },
 6087                    )
 6088                    .child(Label::new("Jump to Edit")),
 6089            ),
 6090
 6091            InlineCompletion::Edit {
 6092                edits,
 6093                edit_preview,
 6094                snapshot,
 6095                display_mode: _,
 6096            } => {
 6097                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6098
 6099                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6100                    &snapshot,
 6101                    &edits,
 6102                    edit_preview.as_ref()?,
 6103                    true,
 6104                    cx,
 6105                )
 6106                .first_line_preview();
 6107
 6108                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6109                    .with_highlights(&style.text, highlighted_edits.highlights);
 6110
 6111                let preview = h_flex()
 6112                    .gap_1()
 6113                    .min_w_16()
 6114                    .child(styled_text)
 6115                    .when(has_more_lines, |parent| parent.child(""));
 6116
 6117                let left = if first_edit_row != cursor_point.row {
 6118                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6119                        .into_any_element()
 6120                } else {
 6121                    Icon::new(IconName::ZedPredict).into_any_element()
 6122                };
 6123
 6124                Some(
 6125                    h_flex()
 6126                        .h_full()
 6127                        .flex_1()
 6128                        .gap_2()
 6129                        .pr_1()
 6130                        .overflow_x_hidden()
 6131                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6132                        .child(left)
 6133                        .child(preview),
 6134                )
 6135            }
 6136        }
 6137    }
 6138
 6139    fn render_context_menu(
 6140        &self,
 6141        style: &EditorStyle,
 6142        max_height_in_lines: u32,
 6143        y_flipped: bool,
 6144        window: &mut Window,
 6145        cx: &mut Context<Editor>,
 6146    ) -> Option<AnyElement> {
 6147        let menu = self.context_menu.borrow();
 6148        let menu = menu.as_ref()?;
 6149        if !menu.visible() {
 6150            return None;
 6151        };
 6152        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6153    }
 6154
 6155    fn render_context_menu_aside(
 6156        &mut self,
 6157        max_size: Size<Pixels>,
 6158        window: &mut Window,
 6159        cx: &mut Context<Editor>,
 6160    ) -> Option<AnyElement> {
 6161        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6162            if menu.visible() {
 6163                menu.render_aside(self, max_size, window, cx)
 6164            } else {
 6165                None
 6166            }
 6167        })
 6168    }
 6169
 6170    fn hide_context_menu(
 6171        &mut self,
 6172        window: &mut Window,
 6173        cx: &mut Context<Self>,
 6174    ) -> Option<CodeContextMenu> {
 6175        cx.notify();
 6176        self.completion_tasks.clear();
 6177        let context_menu = self.context_menu.borrow_mut().take();
 6178        self.stale_inline_completion_in_menu.take();
 6179        self.update_visible_inline_completion(window, cx);
 6180        context_menu
 6181    }
 6182
 6183    fn show_snippet_choices(
 6184        &mut self,
 6185        choices: &Vec<String>,
 6186        selection: Range<Anchor>,
 6187        cx: &mut Context<Self>,
 6188    ) {
 6189        if selection.start.buffer_id.is_none() {
 6190            return;
 6191        }
 6192        let buffer_id = selection.start.buffer_id.unwrap();
 6193        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6194        let id = post_inc(&mut self.next_completion_id);
 6195
 6196        if let Some(buffer) = buffer {
 6197            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6198                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6199            ));
 6200        }
 6201    }
 6202
 6203    pub fn insert_snippet(
 6204        &mut self,
 6205        insertion_ranges: &[Range<usize>],
 6206        snippet: Snippet,
 6207        window: &mut Window,
 6208        cx: &mut Context<Self>,
 6209    ) -> Result<()> {
 6210        struct Tabstop<T> {
 6211            is_end_tabstop: bool,
 6212            ranges: Vec<Range<T>>,
 6213            choices: Option<Vec<String>>,
 6214        }
 6215
 6216        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6217            let snippet_text: Arc<str> = snippet.text.clone().into();
 6218            buffer.edit(
 6219                insertion_ranges
 6220                    .iter()
 6221                    .cloned()
 6222                    .map(|range| (range, snippet_text.clone())),
 6223                Some(AutoindentMode::EachLine),
 6224                cx,
 6225            );
 6226
 6227            let snapshot = &*buffer.read(cx);
 6228            let snippet = &snippet;
 6229            snippet
 6230                .tabstops
 6231                .iter()
 6232                .map(|tabstop| {
 6233                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6234                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6235                    });
 6236                    let mut tabstop_ranges = tabstop
 6237                        .ranges
 6238                        .iter()
 6239                        .flat_map(|tabstop_range| {
 6240                            let mut delta = 0_isize;
 6241                            insertion_ranges.iter().map(move |insertion_range| {
 6242                                let insertion_start = insertion_range.start as isize + delta;
 6243                                delta +=
 6244                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6245
 6246                                let start = ((insertion_start + tabstop_range.start) as usize)
 6247                                    .min(snapshot.len());
 6248                                let end = ((insertion_start + tabstop_range.end) as usize)
 6249                                    .min(snapshot.len());
 6250                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6251                            })
 6252                        })
 6253                        .collect::<Vec<_>>();
 6254                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6255
 6256                    Tabstop {
 6257                        is_end_tabstop,
 6258                        ranges: tabstop_ranges,
 6259                        choices: tabstop.choices.clone(),
 6260                    }
 6261                })
 6262                .collect::<Vec<_>>()
 6263        });
 6264        if let Some(tabstop) = tabstops.first() {
 6265            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6266                s.select_ranges(tabstop.ranges.iter().cloned());
 6267            });
 6268
 6269            if let Some(choices) = &tabstop.choices {
 6270                if let Some(selection) = tabstop.ranges.first() {
 6271                    self.show_snippet_choices(choices, selection.clone(), cx)
 6272                }
 6273            }
 6274
 6275            // If we're already at the last tabstop and it's at the end of the snippet,
 6276            // we're done, we don't need to keep the state around.
 6277            if !tabstop.is_end_tabstop {
 6278                let choices = tabstops
 6279                    .iter()
 6280                    .map(|tabstop| tabstop.choices.clone())
 6281                    .collect();
 6282
 6283                let ranges = tabstops
 6284                    .into_iter()
 6285                    .map(|tabstop| tabstop.ranges)
 6286                    .collect::<Vec<_>>();
 6287
 6288                self.snippet_stack.push(SnippetState {
 6289                    active_index: 0,
 6290                    ranges,
 6291                    choices,
 6292                });
 6293            }
 6294
 6295            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6296            if self.autoclose_regions.is_empty() {
 6297                let snapshot = self.buffer.read(cx).snapshot(cx);
 6298                for selection in &mut self.selections.all::<Point>(cx) {
 6299                    let selection_head = selection.head();
 6300                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6301                        continue;
 6302                    };
 6303
 6304                    let mut bracket_pair = None;
 6305                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6306                    let prev_chars = snapshot
 6307                        .reversed_chars_at(selection_head)
 6308                        .collect::<String>();
 6309                    for (pair, enabled) in scope.brackets() {
 6310                        if enabled
 6311                            && pair.close
 6312                            && prev_chars.starts_with(pair.start.as_str())
 6313                            && next_chars.starts_with(pair.end.as_str())
 6314                        {
 6315                            bracket_pair = Some(pair.clone());
 6316                            break;
 6317                        }
 6318                    }
 6319                    if let Some(pair) = bracket_pair {
 6320                        let start = snapshot.anchor_after(selection_head);
 6321                        let end = snapshot.anchor_after(selection_head);
 6322                        self.autoclose_regions.push(AutocloseRegion {
 6323                            selection_id: selection.id,
 6324                            range: start..end,
 6325                            pair,
 6326                        });
 6327                    }
 6328                }
 6329            }
 6330        }
 6331        Ok(())
 6332    }
 6333
 6334    pub fn move_to_next_snippet_tabstop(
 6335        &mut self,
 6336        window: &mut Window,
 6337        cx: &mut Context<Self>,
 6338    ) -> bool {
 6339        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6340    }
 6341
 6342    pub fn move_to_prev_snippet_tabstop(
 6343        &mut self,
 6344        window: &mut Window,
 6345        cx: &mut Context<Self>,
 6346    ) -> bool {
 6347        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6348    }
 6349
 6350    pub fn move_to_snippet_tabstop(
 6351        &mut self,
 6352        bias: Bias,
 6353        window: &mut Window,
 6354        cx: &mut Context<Self>,
 6355    ) -> bool {
 6356        if let Some(mut snippet) = self.snippet_stack.pop() {
 6357            match bias {
 6358                Bias::Left => {
 6359                    if snippet.active_index > 0 {
 6360                        snippet.active_index -= 1;
 6361                    } else {
 6362                        self.snippet_stack.push(snippet);
 6363                        return false;
 6364                    }
 6365                }
 6366                Bias::Right => {
 6367                    if snippet.active_index + 1 < snippet.ranges.len() {
 6368                        snippet.active_index += 1;
 6369                    } else {
 6370                        self.snippet_stack.push(snippet);
 6371                        return false;
 6372                    }
 6373                }
 6374            }
 6375            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6376                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6377                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6378                });
 6379
 6380                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6381                    if let Some(selection) = current_ranges.first() {
 6382                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6383                    }
 6384                }
 6385
 6386                // If snippet state is not at the last tabstop, push it back on the stack
 6387                if snippet.active_index + 1 < snippet.ranges.len() {
 6388                    self.snippet_stack.push(snippet);
 6389                }
 6390                return true;
 6391            }
 6392        }
 6393
 6394        false
 6395    }
 6396
 6397    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6398        self.transact(window, cx, |this, window, cx| {
 6399            this.select_all(&SelectAll, window, cx);
 6400            this.insert("", window, cx);
 6401        });
 6402    }
 6403
 6404    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6405        self.transact(window, cx, |this, window, cx| {
 6406            this.select_autoclose_pair(window, cx);
 6407            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6408            if !this.linked_edit_ranges.is_empty() {
 6409                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6410                let snapshot = this.buffer.read(cx).snapshot(cx);
 6411
 6412                for selection in selections.iter() {
 6413                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6414                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6415                    if selection_start.buffer_id != selection_end.buffer_id {
 6416                        continue;
 6417                    }
 6418                    if let Some(ranges) =
 6419                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6420                    {
 6421                        for (buffer, entries) in ranges {
 6422                            linked_ranges.entry(buffer).or_default().extend(entries);
 6423                        }
 6424                    }
 6425                }
 6426            }
 6427
 6428            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6429            if !this.selections.line_mode {
 6430                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6431                for selection in &mut selections {
 6432                    if selection.is_empty() {
 6433                        let old_head = selection.head();
 6434                        let mut new_head =
 6435                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6436                                .to_point(&display_map);
 6437                        if let Some((buffer, line_buffer_range)) = display_map
 6438                            .buffer_snapshot
 6439                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6440                        {
 6441                            let indent_size =
 6442                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6443                            let indent_len = match indent_size.kind {
 6444                                IndentKind::Space => {
 6445                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6446                                }
 6447                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6448                            };
 6449                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6450                                let indent_len = indent_len.get();
 6451                                new_head = cmp::min(
 6452                                    new_head,
 6453                                    MultiBufferPoint::new(
 6454                                        old_head.row,
 6455                                        ((old_head.column - 1) / indent_len) * indent_len,
 6456                                    ),
 6457                                );
 6458                            }
 6459                        }
 6460
 6461                        selection.set_head(new_head, SelectionGoal::None);
 6462                    }
 6463                }
 6464            }
 6465
 6466            this.signature_help_state.set_backspace_pressed(true);
 6467            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6468                s.select(selections)
 6469            });
 6470            this.insert("", window, cx);
 6471            let empty_str: Arc<str> = Arc::from("");
 6472            for (buffer, edits) in linked_ranges {
 6473                let snapshot = buffer.read(cx).snapshot();
 6474                use text::ToPoint as TP;
 6475
 6476                let edits = edits
 6477                    .into_iter()
 6478                    .map(|range| {
 6479                        let end_point = TP::to_point(&range.end, &snapshot);
 6480                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6481
 6482                        if end_point == start_point {
 6483                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6484                                .saturating_sub(1);
 6485                            start_point =
 6486                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6487                        };
 6488
 6489                        (start_point..end_point, empty_str.clone())
 6490                    })
 6491                    .sorted_by_key(|(range, _)| range.start)
 6492                    .collect::<Vec<_>>();
 6493                buffer.update(cx, |this, cx| {
 6494                    this.edit(edits, None, cx);
 6495                })
 6496            }
 6497            this.refresh_inline_completion(true, false, window, cx);
 6498            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6499        });
 6500    }
 6501
 6502    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6503        self.transact(window, cx, |this, window, cx| {
 6504            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6505                let line_mode = s.line_mode;
 6506                s.move_with(|map, selection| {
 6507                    if selection.is_empty() && !line_mode {
 6508                        let cursor = movement::right(map, selection.head());
 6509                        selection.end = cursor;
 6510                        selection.reversed = true;
 6511                        selection.goal = SelectionGoal::None;
 6512                    }
 6513                })
 6514            });
 6515            this.insert("", window, cx);
 6516            this.refresh_inline_completion(true, false, window, cx);
 6517        });
 6518    }
 6519
 6520    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6521        if self.move_to_prev_snippet_tabstop(window, cx) {
 6522            return;
 6523        }
 6524
 6525        self.outdent(&Outdent, window, cx);
 6526    }
 6527
 6528    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6529        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6530            return;
 6531        }
 6532
 6533        let mut selections = self.selections.all_adjusted(cx);
 6534        let buffer = self.buffer.read(cx);
 6535        let snapshot = buffer.snapshot(cx);
 6536        let rows_iter = selections.iter().map(|s| s.head().row);
 6537        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6538
 6539        let mut edits = Vec::new();
 6540        let mut prev_edited_row = 0;
 6541        let mut row_delta = 0;
 6542        for selection in &mut selections {
 6543            if selection.start.row != prev_edited_row {
 6544                row_delta = 0;
 6545            }
 6546            prev_edited_row = selection.end.row;
 6547
 6548            // If the selection is non-empty, then increase the indentation of the selected lines.
 6549            if !selection.is_empty() {
 6550                row_delta =
 6551                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6552                continue;
 6553            }
 6554
 6555            // If the selection is empty and the cursor is in the leading whitespace before the
 6556            // suggested indentation, then auto-indent the line.
 6557            let cursor = selection.head();
 6558            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6559            if let Some(suggested_indent) =
 6560                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6561            {
 6562                if cursor.column < suggested_indent.len
 6563                    && cursor.column <= current_indent.len
 6564                    && current_indent.len <= suggested_indent.len
 6565                {
 6566                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6567                    selection.end = selection.start;
 6568                    if row_delta == 0 {
 6569                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6570                            cursor.row,
 6571                            current_indent,
 6572                            suggested_indent,
 6573                        ));
 6574                        row_delta = suggested_indent.len - current_indent.len;
 6575                    }
 6576                    continue;
 6577                }
 6578            }
 6579
 6580            // Otherwise, insert a hard or soft tab.
 6581            let settings = buffer.settings_at(cursor, cx);
 6582            let tab_size = if settings.hard_tabs {
 6583                IndentSize::tab()
 6584            } else {
 6585                let tab_size = settings.tab_size.get();
 6586                let char_column = snapshot
 6587                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6588                    .flat_map(str::chars)
 6589                    .count()
 6590                    + row_delta as usize;
 6591                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6592                IndentSize::spaces(chars_to_next_tab_stop)
 6593            };
 6594            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6595            selection.end = selection.start;
 6596            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6597            row_delta += tab_size.len;
 6598        }
 6599
 6600        self.transact(window, cx, |this, window, cx| {
 6601            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6602            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6603                s.select(selections)
 6604            });
 6605            this.refresh_inline_completion(true, false, window, cx);
 6606        });
 6607    }
 6608
 6609    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6610        if self.read_only(cx) {
 6611            return;
 6612        }
 6613        let mut selections = self.selections.all::<Point>(cx);
 6614        let mut prev_edited_row = 0;
 6615        let mut row_delta = 0;
 6616        let mut edits = Vec::new();
 6617        let buffer = self.buffer.read(cx);
 6618        let snapshot = buffer.snapshot(cx);
 6619        for selection in &mut selections {
 6620            if selection.start.row != prev_edited_row {
 6621                row_delta = 0;
 6622            }
 6623            prev_edited_row = selection.end.row;
 6624
 6625            row_delta =
 6626                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6627        }
 6628
 6629        self.transact(window, cx, |this, window, cx| {
 6630            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6631            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6632                s.select(selections)
 6633            });
 6634        });
 6635    }
 6636
 6637    fn indent_selection(
 6638        buffer: &MultiBuffer,
 6639        snapshot: &MultiBufferSnapshot,
 6640        selection: &mut Selection<Point>,
 6641        edits: &mut Vec<(Range<Point>, String)>,
 6642        delta_for_start_row: u32,
 6643        cx: &App,
 6644    ) -> u32 {
 6645        let settings = buffer.settings_at(selection.start, cx);
 6646        let tab_size = settings.tab_size.get();
 6647        let indent_kind = if settings.hard_tabs {
 6648            IndentKind::Tab
 6649        } else {
 6650            IndentKind::Space
 6651        };
 6652        let mut start_row = selection.start.row;
 6653        let mut end_row = selection.end.row + 1;
 6654
 6655        // If a selection ends at the beginning of a line, don't indent
 6656        // that last line.
 6657        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6658            end_row -= 1;
 6659        }
 6660
 6661        // Avoid re-indenting a row that has already been indented by a
 6662        // previous selection, but still update this selection's column
 6663        // to reflect that indentation.
 6664        if delta_for_start_row > 0 {
 6665            start_row += 1;
 6666            selection.start.column += delta_for_start_row;
 6667            if selection.end.row == selection.start.row {
 6668                selection.end.column += delta_for_start_row;
 6669            }
 6670        }
 6671
 6672        let mut delta_for_end_row = 0;
 6673        let has_multiple_rows = start_row + 1 != end_row;
 6674        for row in start_row..end_row {
 6675            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6676            let indent_delta = match (current_indent.kind, indent_kind) {
 6677                (IndentKind::Space, IndentKind::Space) => {
 6678                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6679                    IndentSize::spaces(columns_to_next_tab_stop)
 6680                }
 6681                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6682                (_, IndentKind::Tab) => IndentSize::tab(),
 6683            };
 6684
 6685            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6686                0
 6687            } else {
 6688                selection.start.column
 6689            };
 6690            let row_start = Point::new(row, start);
 6691            edits.push((
 6692                row_start..row_start,
 6693                indent_delta.chars().collect::<String>(),
 6694            ));
 6695
 6696            // Update this selection's endpoints to reflect the indentation.
 6697            if row == selection.start.row {
 6698                selection.start.column += indent_delta.len;
 6699            }
 6700            if row == selection.end.row {
 6701                selection.end.column += indent_delta.len;
 6702                delta_for_end_row = indent_delta.len;
 6703            }
 6704        }
 6705
 6706        if selection.start.row == selection.end.row {
 6707            delta_for_start_row + delta_for_end_row
 6708        } else {
 6709            delta_for_end_row
 6710        }
 6711    }
 6712
 6713    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6714        if self.read_only(cx) {
 6715            return;
 6716        }
 6717        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6718        let selections = self.selections.all::<Point>(cx);
 6719        let mut deletion_ranges = Vec::new();
 6720        let mut last_outdent = None;
 6721        {
 6722            let buffer = self.buffer.read(cx);
 6723            let snapshot = buffer.snapshot(cx);
 6724            for selection in &selections {
 6725                let settings = buffer.settings_at(selection.start, cx);
 6726                let tab_size = settings.tab_size.get();
 6727                let mut rows = selection.spanned_rows(false, &display_map);
 6728
 6729                // Avoid re-outdenting a row that has already been outdented by a
 6730                // previous selection.
 6731                if let Some(last_row) = last_outdent {
 6732                    if last_row == rows.start {
 6733                        rows.start = rows.start.next_row();
 6734                    }
 6735                }
 6736                let has_multiple_rows = rows.len() > 1;
 6737                for row in rows.iter_rows() {
 6738                    let indent_size = snapshot.indent_size_for_line(row);
 6739                    if indent_size.len > 0 {
 6740                        let deletion_len = match indent_size.kind {
 6741                            IndentKind::Space => {
 6742                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6743                                if columns_to_prev_tab_stop == 0 {
 6744                                    tab_size
 6745                                } else {
 6746                                    columns_to_prev_tab_stop
 6747                                }
 6748                            }
 6749                            IndentKind::Tab => 1,
 6750                        };
 6751                        let start = if has_multiple_rows
 6752                            || deletion_len > selection.start.column
 6753                            || indent_size.len < selection.start.column
 6754                        {
 6755                            0
 6756                        } else {
 6757                            selection.start.column - deletion_len
 6758                        };
 6759                        deletion_ranges.push(
 6760                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6761                        );
 6762                        last_outdent = Some(row);
 6763                    }
 6764                }
 6765            }
 6766        }
 6767
 6768        self.transact(window, cx, |this, window, cx| {
 6769            this.buffer.update(cx, |buffer, cx| {
 6770                let empty_str: Arc<str> = Arc::default();
 6771                buffer.edit(
 6772                    deletion_ranges
 6773                        .into_iter()
 6774                        .map(|range| (range, empty_str.clone())),
 6775                    None,
 6776                    cx,
 6777                );
 6778            });
 6779            let selections = this.selections.all::<usize>(cx);
 6780            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6781                s.select(selections)
 6782            });
 6783        });
 6784    }
 6785
 6786    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6787        if self.read_only(cx) {
 6788            return;
 6789        }
 6790        let selections = self
 6791            .selections
 6792            .all::<usize>(cx)
 6793            .into_iter()
 6794            .map(|s| s.range());
 6795
 6796        self.transact(window, cx, |this, window, cx| {
 6797            this.buffer.update(cx, |buffer, cx| {
 6798                buffer.autoindent_ranges(selections, cx);
 6799            });
 6800            let selections = this.selections.all::<usize>(cx);
 6801            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6802                s.select(selections)
 6803            });
 6804        });
 6805    }
 6806
 6807    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6809        let selections = self.selections.all::<Point>(cx);
 6810
 6811        let mut new_cursors = Vec::new();
 6812        let mut edit_ranges = Vec::new();
 6813        let mut selections = selections.iter().peekable();
 6814        while let Some(selection) = selections.next() {
 6815            let mut rows = selection.spanned_rows(false, &display_map);
 6816            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6817
 6818            // Accumulate contiguous regions of rows that we want to delete.
 6819            while let Some(next_selection) = selections.peek() {
 6820                let next_rows = next_selection.spanned_rows(false, &display_map);
 6821                if next_rows.start <= rows.end {
 6822                    rows.end = next_rows.end;
 6823                    selections.next().unwrap();
 6824                } else {
 6825                    break;
 6826                }
 6827            }
 6828
 6829            let buffer = &display_map.buffer_snapshot;
 6830            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6831            let edit_end;
 6832            let cursor_buffer_row;
 6833            if buffer.max_point().row >= rows.end.0 {
 6834                // If there's a line after the range, delete the \n from the end of the row range
 6835                // and position the cursor on the next line.
 6836                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6837                cursor_buffer_row = rows.end;
 6838            } else {
 6839                // If there isn't a line after the range, delete the \n from the line before the
 6840                // start of the row range and position the cursor there.
 6841                edit_start = edit_start.saturating_sub(1);
 6842                edit_end = buffer.len();
 6843                cursor_buffer_row = rows.start.previous_row();
 6844            }
 6845
 6846            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6847            *cursor.column_mut() =
 6848                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6849
 6850            new_cursors.push((
 6851                selection.id,
 6852                buffer.anchor_after(cursor.to_point(&display_map)),
 6853            ));
 6854            edit_ranges.push(edit_start..edit_end);
 6855        }
 6856
 6857        self.transact(window, cx, |this, window, cx| {
 6858            let buffer = this.buffer.update(cx, |buffer, cx| {
 6859                let empty_str: Arc<str> = Arc::default();
 6860                buffer.edit(
 6861                    edit_ranges
 6862                        .into_iter()
 6863                        .map(|range| (range, empty_str.clone())),
 6864                    None,
 6865                    cx,
 6866                );
 6867                buffer.snapshot(cx)
 6868            });
 6869            let new_selections = new_cursors
 6870                .into_iter()
 6871                .map(|(id, cursor)| {
 6872                    let cursor = cursor.to_point(&buffer);
 6873                    Selection {
 6874                        id,
 6875                        start: cursor,
 6876                        end: cursor,
 6877                        reversed: false,
 6878                        goal: SelectionGoal::None,
 6879                    }
 6880                })
 6881                .collect();
 6882
 6883            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6884                s.select(new_selections);
 6885            });
 6886        });
 6887    }
 6888
 6889    pub fn join_lines_impl(
 6890        &mut self,
 6891        insert_whitespace: bool,
 6892        window: &mut Window,
 6893        cx: &mut Context<Self>,
 6894    ) {
 6895        if self.read_only(cx) {
 6896            return;
 6897        }
 6898        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6899        for selection in self.selections.all::<Point>(cx) {
 6900            let start = MultiBufferRow(selection.start.row);
 6901            // Treat single line selections as if they include the next line. Otherwise this action
 6902            // would do nothing for single line selections individual cursors.
 6903            let end = if selection.start.row == selection.end.row {
 6904                MultiBufferRow(selection.start.row + 1)
 6905            } else {
 6906                MultiBufferRow(selection.end.row)
 6907            };
 6908
 6909            if let Some(last_row_range) = row_ranges.last_mut() {
 6910                if start <= last_row_range.end {
 6911                    last_row_range.end = end;
 6912                    continue;
 6913                }
 6914            }
 6915            row_ranges.push(start..end);
 6916        }
 6917
 6918        let snapshot = self.buffer.read(cx).snapshot(cx);
 6919        let mut cursor_positions = Vec::new();
 6920        for row_range in &row_ranges {
 6921            let anchor = snapshot.anchor_before(Point::new(
 6922                row_range.end.previous_row().0,
 6923                snapshot.line_len(row_range.end.previous_row()),
 6924            ));
 6925            cursor_positions.push(anchor..anchor);
 6926        }
 6927
 6928        self.transact(window, cx, |this, window, cx| {
 6929            for row_range in row_ranges.into_iter().rev() {
 6930                for row in row_range.iter_rows().rev() {
 6931                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6932                    let next_line_row = row.next_row();
 6933                    let indent = snapshot.indent_size_for_line(next_line_row);
 6934                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6935
 6936                    let replace =
 6937                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6938                            " "
 6939                        } else {
 6940                            ""
 6941                        };
 6942
 6943                    this.buffer.update(cx, |buffer, cx| {
 6944                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6945                    });
 6946                }
 6947            }
 6948
 6949            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6950                s.select_anchor_ranges(cursor_positions)
 6951            });
 6952        });
 6953    }
 6954
 6955    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6956        self.join_lines_impl(true, window, cx);
 6957    }
 6958
 6959    pub fn sort_lines_case_sensitive(
 6960        &mut self,
 6961        _: &SortLinesCaseSensitive,
 6962        window: &mut Window,
 6963        cx: &mut Context<Self>,
 6964    ) {
 6965        self.manipulate_lines(window, cx, |lines| lines.sort())
 6966    }
 6967
 6968    pub fn sort_lines_case_insensitive(
 6969        &mut self,
 6970        _: &SortLinesCaseInsensitive,
 6971        window: &mut Window,
 6972        cx: &mut Context<Self>,
 6973    ) {
 6974        self.manipulate_lines(window, cx, |lines| {
 6975            lines.sort_by_key(|line| line.to_lowercase())
 6976        })
 6977    }
 6978
 6979    pub fn unique_lines_case_insensitive(
 6980        &mut self,
 6981        _: &UniqueLinesCaseInsensitive,
 6982        window: &mut Window,
 6983        cx: &mut Context<Self>,
 6984    ) {
 6985        self.manipulate_lines(window, cx, |lines| {
 6986            let mut seen = HashSet::default();
 6987            lines.retain(|line| seen.insert(line.to_lowercase()));
 6988        })
 6989    }
 6990
 6991    pub fn unique_lines_case_sensitive(
 6992        &mut self,
 6993        _: &UniqueLinesCaseSensitive,
 6994        window: &mut Window,
 6995        cx: &mut Context<Self>,
 6996    ) {
 6997        self.manipulate_lines(window, cx, |lines| {
 6998            let mut seen = HashSet::default();
 6999            lines.retain(|line| seen.insert(*line));
 7000        })
 7001    }
 7002
 7003    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7004        let Some(project) = self.project.clone() else {
 7005            return;
 7006        };
 7007        self.reload(project, window, cx)
 7008            .detach_and_notify_err(window, cx);
 7009    }
 7010
 7011    pub fn restore_file(
 7012        &mut self,
 7013        _: &::git::RestoreFile,
 7014        window: &mut Window,
 7015        cx: &mut Context<Self>,
 7016    ) {
 7017        let mut buffer_ids = HashSet::default();
 7018        let snapshot = self.buffer().read(cx).snapshot(cx);
 7019        for selection in self.selections.all::<usize>(cx) {
 7020            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7021        }
 7022
 7023        let buffer = self.buffer().read(cx);
 7024        let ranges = buffer_ids
 7025            .into_iter()
 7026            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7027            .collect::<Vec<_>>();
 7028
 7029        self.restore_hunks_in_ranges(ranges, window, cx);
 7030    }
 7031
 7032    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7033        let selections = self
 7034            .selections
 7035            .all(cx)
 7036            .into_iter()
 7037            .map(|s| s.range())
 7038            .collect();
 7039        self.restore_hunks_in_ranges(selections, window, cx);
 7040    }
 7041
 7042    fn restore_hunks_in_ranges(
 7043        &mut self,
 7044        ranges: Vec<Range<Point>>,
 7045        window: &mut Window,
 7046        cx: &mut Context<Editor>,
 7047    ) {
 7048        let mut revert_changes = HashMap::default();
 7049        let snapshot = self.buffer.read(cx).snapshot(cx);
 7050        let Some(project) = &self.project else {
 7051            return;
 7052        };
 7053
 7054        let chunk_by = self
 7055            .snapshot(window, cx)
 7056            .hunks_for_ranges(ranges.into_iter())
 7057            .into_iter()
 7058            .chunk_by(|hunk| hunk.buffer_id);
 7059        for (buffer_id, hunks) in &chunk_by {
 7060            let hunks = hunks.collect::<Vec<_>>();
 7061            for hunk in &hunks {
 7062                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7063            }
 7064            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7065        }
 7066        drop(chunk_by);
 7067        if !revert_changes.is_empty() {
 7068            self.transact(window, cx, |editor, window, cx| {
 7069                editor.revert(revert_changes, window, cx);
 7070            });
 7071        }
 7072    }
 7073
 7074    pub fn open_active_item_in_terminal(
 7075        &mut self,
 7076        _: &OpenInTerminal,
 7077        window: &mut Window,
 7078        cx: &mut Context<Self>,
 7079    ) {
 7080        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7081            let project_path = buffer.read(cx).project_path(cx)?;
 7082            let project = self.project.as_ref()?.read(cx);
 7083            let entry = project.entry_for_path(&project_path, cx)?;
 7084            let parent = match &entry.canonical_path {
 7085                Some(canonical_path) => canonical_path.to_path_buf(),
 7086                None => project.absolute_path(&project_path, cx)?,
 7087            }
 7088            .parent()?
 7089            .to_path_buf();
 7090            Some(parent)
 7091        }) {
 7092            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7093        }
 7094    }
 7095
 7096    pub fn prepare_restore_change(
 7097        &self,
 7098        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7099        hunk: &MultiBufferDiffHunk,
 7100        cx: &mut App,
 7101    ) -> Option<()> {
 7102        let buffer = self.buffer.read(cx);
 7103        let diff = buffer.diff_for(hunk.buffer_id)?;
 7104        let buffer = buffer.buffer(hunk.buffer_id)?;
 7105        let buffer = buffer.read(cx);
 7106        let original_text = diff
 7107            .read(cx)
 7108            .base_text()
 7109            .as_ref()?
 7110            .as_rope()
 7111            .slice(hunk.diff_base_byte_range.clone());
 7112        let buffer_snapshot = buffer.snapshot();
 7113        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7114        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7115            probe
 7116                .0
 7117                .start
 7118                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7119                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7120        }) {
 7121            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7122            Some(())
 7123        } else {
 7124            None
 7125        }
 7126    }
 7127
 7128    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7129        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7130    }
 7131
 7132    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7133        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7134    }
 7135
 7136    fn manipulate_lines<Fn>(
 7137        &mut self,
 7138        window: &mut Window,
 7139        cx: &mut Context<Self>,
 7140        mut callback: Fn,
 7141    ) where
 7142        Fn: FnMut(&mut Vec<&str>),
 7143    {
 7144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7145        let buffer = self.buffer.read(cx).snapshot(cx);
 7146
 7147        let mut edits = Vec::new();
 7148
 7149        let selections = self.selections.all::<Point>(cx);
 7150        let mut selections = selections.iter().peekable();
 7151        let mut contiguous_row_selections = Vec::new();
 7152        let mut new_selections = Vec::new();
 7153        let mut added_lines = 0;
 7154        let mut removed_lines = 0;
 7155
 7156        while let Some(selection) = selections.next() {
 7157            let (start_row, end_row) = consume_contiguous_rows(
 7158                &mut contiguous_row_selections,
 7159                selection,
 7160                &display_map,
 7161                &mut selections,
 7162            );
 7163
 7164            let start_point = Point::new(start_row.0, 0);
 7165            let end_point = Point::new(
 7166                end_row.previous_row().0,
 7167                buffer.line_len(end_row.previous_row()),
 7168            );
 7169            let text = buffer
 7170                .text_for_range(start_point..end_point)
 7171                .collect::<String>();
 7172
 7173            let mut lines = text.split('\n').collect_vec();
 7174
 7175            let lines_before = lines.len();
 7176            callback(&mut lines);
 7177            let lines_after = lines.len();
 7178
 7179            edits.push((start_point..end_point, lines.join("\n")));
 7180
 7181            // Selections must change based on added and removed line count
 7182            let start_row =
 7183                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7184            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7185            new_selections.push(Selection {
 7186                id: selection.id,
 7187                start: start_row,
 7188                end: end_row,
 7189                goal: SelectionGoal::None,
 7190                reversed: selection.reversed,
 7191            });
 7192
 7193            if lines_after > lines_before {
 7194                added_lines += lines_after - lines_before;
 7195            } else if lines_before > lines_after {
 7196                removed_lines += lines_before - lines_after;
 7197            }
 7198        }
 7199
 7200        self.transact(window, cx, |this, window, cx| {
 7201            let buffer = this.buffer.update(cx, |buffer, cx| {
 7202                buffer.edit(edits, None, cx);
 7203                buffer.snapshot(cx)
 7204            });
 7205
 7206            // Recalculate offsets on newly edited buffer
 7207            let new_selections = new_selections
 7208                .iter()
 7209                .map(|s| {
 7210                    let start_point = Point::new(s.start.0, 0);
 7211                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7212                    Selection {
 7213                        id: s.id,
 7214                        start: buffer.point_to_offset(start_point),
 7215                        end: buffer.point_to_offset(end_point),
 7216                        goal: s.goal,
 7217                        reversed: s.reversed,
 7218                    }
 7219                })
 7220                .collect();
 7221
 7222            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7223                s.select(new_selections);
 7224            });
 7225
 7226            this.request_autoscroll(Autoscroll::fit(), cx);
 7227        });
 7228    }
 7229
 7230    pub fn convert_to_upper_case(
 7231        &mut self,
 7232        _: &ConvertToUpperCase,
 7233        window: &mut Window,
 7234        cx: &mut Context<Self>,
 7235    ) {
 7236        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7237    }
 7238
 7239    pub fn convert_to_lower_case(
 7240        &mut self,
 7241        _: &ConvertToLowerCase,
 7242        window: &mut Window,
 7243        cx: &mut Context<Self>,
 7244    ) {
 7245        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7246    }
 7247
 7248    pub fn convert_to_title_case(
 7249        &mut self,
 7250        _: &ConvertToTitleCase,
 7251        window: &mut Window,
 7252        cx: &mut Context<Self>,
 7253    ) {
 7254        self.manipulate_text(window, cx, |text| {
 7255            text.split('\n')
 7256                .map(|line| line.to_case(Case::Title))
 7257                .join("\n")
 7258        })
 7259    }
 7260
 7261    pub fn convert_to_snake_case(
 7262        &mut self,
 7263        _: &ConvertToSnakeCase,
 7264        window: &mut Window,
 7265        cx: &mut Context<Self>,
 7266    ) {
 7267        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7268    }
 7269
 7270    pub fn convert_to_kebab_case(
 7271        &mut self,
 7272        _: &ConvertToKebabCase,
 7273        window: &mut Window,
 7274        cx: &mut Context<Self>,
 7275    ) {
 7276        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7277    }
 7278
 7279    pub fn convert_to_upper_camel_case(
 7280        &mut self,
 7281        _: &ConvertToUpperCamelCase,
 7282        window: &mut Window,
 7283        cx: &mut Context<Self>,
 7284    ) {
 7285        self.manipulate_text(window, cx, |text| {
 7286            text.split('\n')
 7287                .map(|line| line.to_case(Case::UpperCamel))
 7288                .join("\n")
 7289        })
 7290    }
 7291
 7292    pub fn convert_to_lower_camel_case(
 7293        &mut self,
 7294        _: &ConvertToLowerCamelCase,
 7295        window: &mut Window,
 7296        cx: &mut Context<Self>,
 7297    ) {
 7298        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7299    }
 7300
 7301    pub fn convert_to_opposite_case(
 7302        &mut self,
 7303        _: &ConvertToOppositeCase,
 7304        window: &mut Window,
 7305        cx: &mut Context<Self>,
 7306    ) {
 7307        self.manipulate_text(window, cx, |text| {
 7308            text.chars()
 7309                .fold(String::with_capacity(text.len()), |mut t, c| {
 7310                    if c.is_uppercase() {
 7311                        t.extend(c.to_lowercase());
 7312                    } else {
 7313                        t.extend(c.to_uppercase());
 7314                    }
 7315                    t
 7316                })
 7317        })
 7318    }
 7319
 7320    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7321    where
 7322        Fn: FnMut(&str) -> String,
 7323    {
 7324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7325        let buffer = self.buffer.read(cx).snapshot(cx);
 7326
 7327        let mut new_selections = Vec::new();
 7328        let mut edits = Vec::new();
 7329        let mut selection_adjustment = 0i32;
 7330
 7331        for selection in self.selections.all::<usize>(cx) {
 7332            let selection_is_empty = selection.is_empty();
 7333
 7334            let (start, end) = if selection_is_empty {
 7335                let word_range = movement::surrounding_word(
 7336                    &display_map,
 7337                    selection.start.to_display_point(&display_map),
 7338                );
 7339                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7340                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7341                (start, end)
 7342            } else {
 7343                (selection.start, selection.end)
 7344            };
 7345
 7346            let text = buffer.text_for_range(start..end).collect::<String>();
 7347            let old_length = text.len() as i32;
 7348            let text = callback(&text);
 7349
 7350            new_selections.push(Selection {
 7351                start: (start as i32 - selection_adjustment) as usize,
 7352                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7353                goal: SelectionGoal::None,
 7354                ..selection
 7355            });
 7356
 7357            selection_adjustment += old_length - text.len() as i32;
 7358
 7359            edits.push((start..end, text));
 7360        }
 7361
 7362        self.transact(window, cx, |this, window, cx| {
 7363            this.buffer.update(cx, |buffer, cx| {
 7364                buffer.edit(edits, None, cx);
 7365            });
 7366
 7367            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7368                s.select(new_selections);
 7369            });
 7370
 7371            this.request_autoscroll(Autoscroll::fit(), cx);
 7372        });
 7373    }
 7374
 7375    pub fn duplicate(
 7376        &mut self,
 7377        upwards: bool,
 7378        whole_lines: bool,
 7379        window: &mut Window,
 7380        cx: &mut Context<Self>,
 7381    ) {
 7382        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7383        let buffer = &display_map.buffer_snapshot;
 7384        let selections = self.selections.all::<Point>(cx);
 7385
 7386        let mut edits = Vec::new();
 7387        let mut selections_iter = selections.iter().peekable();
 7388        while let Some(selection) = selections_iter.next() {
 7389            let mut rows = selection.spanned_rows(false, &display_map);
 7390            // duplicate line-wise
 7391            if whole_lines || selection.start == selection.end {
 7392                // Avoid duplicating the same lines twice.
 7393                while let Some(next_selection) = selections_iter.peek() {
 7394                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7395                    if next_rows.start < rows.end {
 7396                        rows.end = next_rows.end;
 7397                        selections_iter.next().unwrap();
 7398                    } else {
 7399                        break;
 7400                    }
 7401                }
 7402
 7403                // Copy the text from the selected row region and splice it either at the start
 7404                // or end of the region.
 7405                let start = Point::new(rows.start.0, 0);
 7406                let end = Point::new(
 7407                    rows.end.previous_row().0,
 7408                    buffer.line_len(rows.end.previous_row()),
 7409                );
 7410                let text = buffer
 7411                    .text_for_range(start..end)
 7412                    .chain(Some("\n"))
 7413                    .collect::<String>();
 7414                let insert_location = if upwards {
 7415                    Point::new(rows.end.0, 0)
 7416                } else {
 7417                    start
 7418                };
 7419                edits.push((insert_location..insert_location, text));
 7420            } else {
 7421                // duplicate character-wise
 7422                let start = selection.start;
 7423                let end = selection.end;
 7424                let text = buffer.text_for_range(start..end).collect::<String>();
 7425                edits.push((selection.end..selection.end, text));
 7426            }
 7427        }
 7428
 7429        self.transact(window, cx, |this, _, cx| {
 7430            this.buffer.update(cx, |buffer, cx| {
 7431                buffer.edit(edits, None, cx);
 7432            });
 7433
 7434            this.request_autoscroll(Autoscroll::fit(), cx);
 7435        });
 7436    }
 7437
 7438    pub fn duplicate_line_up(
 7439        &mut self,
 7440        _: &DuplicateLineUp,
 7441        window: &mut Window,
 7442        cx: &mut Context<Self>,
 7443    ) {
 7444        self.duplicate(true, true, window, cx);
 7445    }
 7446
 7447    pub fn duplicate_line_down(
 7448        &mut self,
 7449        _: &DuplicateLineDown,
 7450        window: &mut Window,
 7451        cx: &mut Context<Self>,
 7452    ) {
 7453        self.duplicate(false, true, window, cx);
 7454    }
 7455
 7456    pub fn duplicate_selection(
 7457        &mut self,
 7458        _: &DuplicateSelection,
 7459        window: &mut Window,
 7460        cx: &mut Context<Self>,
 7461    ) {
 7462        self.duplicate(false, false, window, cx);
 7463    }
 7464
 7465    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7466        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7467        let buffer = self.buffer.read(cx).snapshot(cx);
 7468
 7469        let mut edits = Vec::new();
 7470        let mut unfold_ranges = Vec::new();
 7471        let mut refold_creases = Vec::new();
 7472
 7473        let selections = self.selections.all::<Point>(cx);
 7474        let mut selections = selections.iter().peekable();
 7475        let mut contiguous_row_selections = Vec::new();
 7476        let mut new_selections = Vec::new();
 7477
 7478        while let Some(selection) = selections.next() {
 7479            // Find all the selections that span a contiguous row range
 7480            let (start_row, end_row) = consume_contiguous_rows(
 7481                &mut contiguous_row_selections,
 7482                selection,
 7483                &display_map,
 7484                &mut selections,
 7485            );
 7486
 7487            // Move the text spanned by the row range to be before the line preceding the row range
 7488            if start_row.0 > 0 {
 7489                let range_to_move = Point::new(
 7490                    start_row.previous_row().0,
 7491                    buffer.line_len(start_row.previous_row()),
 7492                )
 7493                    ..Point::new(
 7494                        end_row.previous_row().0,
 7495                        buffer.line_len(end_row.previous_row()),
 7496                    );
 7497                let insertion_point = display_map
 7498                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7499                    .0;
 7500
 7501                // Don't move lines across excerpts
 7502                if buffer
 7503                    .excerpt_containing(insertion_point..range_to_move.end)
 7504                    .is_some()
 7505                {
 7506                    let text = buffer
 7507                        .text_for_range(range_to_move.clone())
 7508                        .flat_map(|s| s.chars())
 7509                        .skip(1)
 7510                        .chain(['\n'])
 7511                        .collect::<String>();
 7512
 7513                    edits.push((
 7514                        buffer.anchor_after(range_to_move.start)
 7515                            ..buffer.anchor_before(range_to_move.end),
 7516                        String::new(),
 7517                    ));
 7518                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7519                    edits.push((insertion_anchor..insertion_anchor, text));
 7520
 7521                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7522
 7523                    // Move selections up
 7524                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7525                        |mut selection| {
 7526                            selection.start.row -= row_delta;
 7527                            selection.end.row -= row_delta;
 7528                            selection
 7529                        },
 7530                    ));
 7531
 7532                    // Move folds up
 7533                    unfold_ranges.push(range_to_move.clone());
 7534                    for fold in display_map.folds_in_range(
 7535                        buffer.anchor_before(range_to_move.start)
 7536                            ..buffer.anchor_after(range_to_move.end),
 7537                    ) {
 7538                        let mut start = fold.range.start.to_point(&buffer);
 7539                        let mut end = fold.range.end.to_point(&buffer);
 7540                        start.row -= row_delta;
 7541                        end.row -= row_delta;
 7542                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7543                    }
 7544                }
 7545            }
 7546
 7547            // If we didn't move line(s), preserve the existing selections
 7548            new_selections.append(&mut contiguous_row_selections);
 7549        }
 7550
 7551        self.transact(window, cx, |this, window, cx| {
 7552            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7553            this.buffer.update(cx, |buffer, cx| {
 7554                for (range, text) in edits {
 7555                    buffer.edit([(range, text)], None, cx);
 7556                }
 7557            });
 7558            this.fold_creases(refold_creases, true, window, cx);
 7559            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7560                s.select(new_selections);
 7561            })
 7562        });
 7563    }
 7564
 7565    pub fn move_line_down(
 7566        &mut self,
 7567        _: &MoveLineDown,
 7568        window: &mut Window,
 7569        cx: &mut Context<Self>,
 7570    ) {
 7571        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7572        let buffer = self.buffer.read(cx).snapshot(cx);
 7573
 7574        let mut edits = Vec::new();
 7575        let mut unfold_ranges = Vec::new();
 7576        let mut refold_creases = Vec::new();
 7577
 7578        let selections = self.selections.all::<Point>(cx);
 7579        let mut selections = selections.iter().peekable();
 7580        let mut contiguous_row_selections = Vec::new();
 7581        let mut new_selections = Vec::new();
 7582
 7583        while let Some(selection) = selections.next() {
 7584            // Find all the selections that span a contiguous row range
 7585            let (start_row, end_row) = consume_contiguous_rows(
 7586                &mut contiguous_row_selections,
 7587                selection,
 7588                &display_map,
 7589                &mut selections,
 7590            );
 7591
 7592            // Move the text spanned by the row range to be after the last line of the row range
 7593            if end_row.0 <= buffer.max_point().row {
 7594                let range_to_move =
 7595                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7596                let insertion_point = display_map
 7597                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7598                    .0;
 7599
 7600                // Don't move lines across excerpt boundaries
 7601                if buffer
 7602                    .excerpt_containing(range_to_move.start..insertion_point)
 7603                    .is_some()
 7604                {
 7605                    let mut text = String::from("\n");
 7606                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7607                    text.pop(); // Drop trailing newline
 7608                    edits.push((
 7609                        buffer.anchor_after(range_to_move.start)
 7610                            ..buffer.anchor_before(range_to_move.end),
 7611                        String::new(),
 7612                    ));
 7613                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7614                    edits.push((insertion_anchor..insertion_anchor, text));
 7615
 7616                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7617
 7618                    // Move selections down
 7619                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7620                        |mut selection| {
 7621                            selection.start.row += row_delta;
 7622                            selection.end.row += row_delta;
 7623                            selection
 7624                        },
 7625                    ));
 7626
 7627                    // Move folds down
 7628                    unfold_ranges.push(range_to_move.clone());
 7629                    for fold in display_map.folds_in_range(
 7630                        buffer.anchor_before(range_to_move.start)
 7631                            ..buffer.anchor_after(range_to_move.end),
 7632                    ) {
 7633                        let mut start = fold.range.start.to_point(&buffer);
 7634                        let mut end = fold.range.end.to_point(&buffer);
 7635                        start.row += row_delta;
 7636                        end.row += row_delta;
 7637                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7638                    }
 7639                }
 7640            }
 7641
 7642            // If we didn't move line(s), preserve the existing selections
 7643            new_selections.append(&mut contiguous_row_selections);
 7644        }
 7645
 7646        self.transact(window, cx, |this, window, cx| {
 7647            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7648            this.buffer.update(cx, |buffer, cx| {
 7649                for (range, text) in edits {
 7650                    buffer.edit([(range, text)], None, cx);
 7651                }
 7652            });
 7653            this.fold_creases(refold_creases, true, window, cx);
 7654            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7655                s.select(new_selections)
 7656            });
 7657        });
 7658    }
 7659
 7660    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7661        let text_layout_details = &self.text_layout_details(window);
 7662        self.transact(window, cx, |this, window, cx| {
 7663            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7664                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7665                let line_mode = s.line_mode;
 7666                s.move_with(|display_map, selection| {
 7667                    if !selection.is_empty() || line_mode {
 7668                        return;
 7669                    }
 7670
 7671                    let mut head = selection.head();
 7672                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7673                    if head.column() == display_map.line_len(head.row()) {
 7674                        transpose_offset = display_map
 7675                            .buffer_snapshot
 7676                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7677                    }
 7678
 7679                    if transpose_offset == 0 {
 7680                        return;
 7681                    }
 7682
 7683                    *head.column_mut() += 1;
 7684                    head = display_map.clip_point(head, Bias::Right);
 7685                    let goal = SelectionGoal::HorizontalPosition(
 7686                        display_map
 7687                            .x_for_display_point(head, text_layout_details)
 7688                            .into(),
 7689                    );
 7690                    selection.collapse_to(head, goal);
 7691
 7692                    let transpose_start = display_map
 7693                        .buffer_snapshot
 7694                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7695                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7696                        let transpose_end = display_map
 7697                            .buffer_snapshot
 7698                            .clip_offset(transpose_offset + 1, Bias::Right);
 7699                        if let Some(ch) =
 7700                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7701                        {
 7702                            edits.push((transpose_start..transpose_offset, String::new()));
 7703                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7704                        }
 7705                    }
 7706                });
 7707                edits
 7708            });
 7709            this.buffer
 7710                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7711            let selections = this.selections.all::<usize>(cx);
 7712            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7713                s.select(selections);
 7714            });
 7715        });
 7716    }
 7717
 7718    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7719        self.rewrap_impl(IsVimMode::No, cx)
 7720    }
 7721
 7722    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7723        let buffer = self.buffer.read(cx).snapshot(cx);
 7724        let selections = self.selections.all::<Point>(cx);
 7725        let mut selections = selections.iter().peekable();
 7726
 7727        let mut edits = Vec::new();
 7728        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7729
 7730        while let Some(selection) = selections.next() {
 7731            let mut start_row = selection.start.row;
 7732            let mut end_row = selection.end.row;
 7733
 7734            // Skip selections that overlap with a range that has already been rewrapped.
 7735            let selection_range = start_row..end_row;
 7736            if rewrapped_row_ranges
 7737                .iter()
 7738                .any(|range| range.overlaps(&selection_range))
 7739            {
 7740                continue;
 7741            }
 7742
 7743            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7744
 7745            // Since not all lines in the selection may be at the same indent
 7746            // level, choose the indent size that is the most common between all
 7747            // of the lines.
 7748            //
 7749            // If there is a tie, we use the deepest indent.
 7750            let (indent_size, indent_end) = {
 7751                let mut indent_size_occurrences = HashMap::default();
 7752                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7753
 7754                for row in start_row..=end_row {
 7755                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7756                    rows_by_indent_size.entry(indent).or_default().push(row);
 7757                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7758                }
 7759
 7760                let indent_size = indent_size_occurrences
 7761                    .into_iter()
 7762                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7763                    .map(|(indent, _)| indent)
 7764                    .unwrap_or_default();
 7765                let row = rows_by_indent_size[&indent_size][0];
 7766                let indent_end = Point::new(row, indent_size.len);
 7767
 7768                (indent_size, indent_end)
 7769            };
 7770
 7771            let mut line_prefix = indent_size.chars().collect::<String>();
 7772
 7773            let mut inside_comment = false;
 7774            if let Some(comment_prefix) =
 7775                buffer
 7776                    .language_scope_at(selection.head())
 7777                    .and_then(|language| {
 7778                        language
 7779                            .line_comment_prefixes()
 7780                            .iter()
 7781                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7782                            .cloned()
 7783                    })
 7784            {
 7785                line_prefix.push_str(&comment_prefix);
 7786                inside_comment = true;
 7787            }
 7788
 7789            let language_settings = buffer.settings_at(selection.head(), cx);
 7790            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 7791                RewrapBehavior::InComments => inside_comment,
 7792                RewrapBehavior::InSelections => !selection.is_empty(),
 7793                RewrapBehavior::Anywhere => true,
 7794            };
 7795
 7796            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 7797            if !should_rewrap {
 7798                continue;
 7799            }
 7800
 7801            if selection.is_empty() {
 7802                'expand_upwards: while start_row > 0 {
 7803                    let prev_row = start_row - 1;
 7804                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7805                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7806                    {
 7807                        start_row = prev_row;
 7808                    } else {
 7809                        break 'expand_upwards;
 7810                    }
 7811                }
 7812
 7813                'expand_downwards: while end_row < buffer.max_point().row {
 7814                    let next_row = end_row + 1;
 7815                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7816                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7817                    {
 7818                        end_row = next_row;
 7819                    } else {
 7820                        break 'expand_downwards;
 7821                    }
 7822                }
 7823            }
 7824
 7825            let start = Point::new(start_row, 0);
 7826            let start_offset = start.to_offset(&buffer);
 7827            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7828            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7829            let Some(lines_without_prefixes) = selection_text
 7830                .lines()
 7831                .map(|line| {
 7832                    line.strip_prefix(&line_prefix)
 7833                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7834                        .ok_or_else(|| {
 7835                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7836                        })
 7837                })
 7838                .collect::<Result<Vec<_>, _>>()
 7839                .log_err()
 7840            else {
 7841                continue;
 7842            };
 7843
 7844            let wrap_column = buffer
 7845                .settings_at(Point::new(start_row, 0), cx)
 7846                .preferred_line_length as usize;
 7847            let wrapped_text = wrap_with_prefix(
 7848                line_prefix,
 7849                lines_without_prefixes.join(" "),
 7850                wrap_column,
 7851                tab_size,
 7852            );
 7853
 7854            // TODO: should always use char-based diff while still supporting cursor behavior that
 7855            // matches vim.
 7856            let mut diff_options = DiffOptions::default();
 7857            if is_vim_mode == IsVimMode::Yes {
 7858                diff_options.max_word_diff_len = 0;
 7859                diff_options.max_word_diff_line_count = 0;
 7860            } else {
 7861                diff_options.max_word_diff_len = usize::MAX;
 7862                diff_options.max_word_diff_line_count = usize::MAX;
 7863            }
 7864
 7865            for (old_range, new_text) in
 7866                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 7867            {
 7868                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 7869                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 7870                edits.push((edit_start..edit_end, new_text));
 7871            }
 7872
 7873            rewrapped_row_ranges.push(start_row..=end_row);
 7874        }
 7875
 7876        self.buffer
 7877            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7878    }
 7879
 7880    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7881        let mut text = String::new();
 7882        let buffer = self.buffer.read(cx).snapshot(cx);
 7883        let mut selections = self.selections.all::<Point>(cx);
 7884        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7885        {
 7886            let max_point = buffer.max_point();
 7887            let mut is_first = true;
 7888            for selection in &mut selections {
 7889                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7890                if is_entire_line {
 7891                    selection.start = Point::new(selection.start.row, 0);
 7892                    if !selection.is_empty() && selection.end.column == 0 {
 7893                        selection.end = cmp::min(max_point, selection.end);
 7894                    } else {
 7895                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7896                    }
 7897                    selection.goal = SelectionGoal::None;
 7898                }
 7899                if is_first {
 7900                    is_first = false;
 7901                } else {
 7902                    text += "\n";
 7903                }
 7904                let mut len = 0;
 7905                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7906                    text.push_str(chunk);
 7907                    len += chunk.len();
 7908                }
 7909                clipboard_selections.push(ClipboardSelection {
 7910                    len,
 7911                    is_entire_line,
 7912                    first_line_indent: buffer
 7913                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7914                        .len,
 7915                });
 7916            }
 7917        }
 7918
 7919        self.transact(window, cx, |this, window, cx| {
 7920            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7921                s.select(selections);
 7922            });
 7923            this.insert("", window, cx);
 7924        });
 7925        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7926    }
 7927
 7928    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7929        let item = self.cut_common(window, cx);
 7930        cx.write_to_clipboard(item);
 7931    }
 7932
 7933    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7934        self.change_selections(None, window, cx, |s| {
 7935            s.move_with(|snapshot, sel| {
 7936                if sel.is_empty() {
 7937                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7938                }
 7939            });
 7940        });
 7941        let item = self.cut_common(window, cx);
 7942        cx.set_global(KillRing(item))
 7943    }
 7944
 7945    pub fn kill_ring_yank(
 7946        &mut self,
 7947        _: &KillRingYank,
 7948        window: &mut Window,
 7949        cx: &mut Context<Self>,
 7950    ) {
 7951        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7952            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7953                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7954            } else {
 7955                return;
 7956            }
 7957        } else {
 7958            return;
 7959        };
 7960        self.do_paste(&text, metadata, false, window, cx);
 7961    }
 7962
 7963    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7964        let selections = self.selections.all::<Point>(cx);
 7965        let buffer = self.buffer.read(cx).read(cx);
 7966        let mut text = String::new();
 7967
 7968        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7969        {
 7970            let max_point = buffer.max_point();
 7971            let mut is_first = true;
 7972            for selection in selections.iter() {
 7973                let mut start = selection.start;
 7974                let mut end = selection.end;
 7975                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7976                if is_entire_line {
 7977                    start = Point::new(start.row, 0);
 7978                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7979                }
 7980                if is_first {
 7981                    is_first = false;
 7982                } else {
 7983                    text += "\n";
 7984                }
 7985                let mut len = 0;
 7986                for chunk in buffer.text_for_range(start..end) {
 7987                    text.push_str(chunk);
 7988                    len += chunk.len();
 7989                }
 7990                clipboard_selections.push(ClipboardSelection {
 7991                    len,
 7992                    is_entire_line,
 7993                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7994                });
 7995            }
 7996        }
 7997
 7998        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7999            text,
 8000            clipboard_selections,
 8001        ));
 8002    }
 8003
 8004    pub fn do_paste(
 8005        &mut self,
 8006        text: &String,
 8007        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8008        handle_entire_lines: bool,
 8009        window: &mut Window,
 8010        cx: &mut Context<Self>,
 8011    ) {
 8012        if self.read_only(cx) {
 8013            return;
 8014        }
 8015
 8016        let clipboard_text = Cow::Borrowed(text);
 8017
 8018        self.transact(window, cx, |this, window, cx| {
 8019            if let Some(mut clipboard_selections) = clipboard_selections {
 8020                let old_selections = this.selections.all::<usize>(cx);
 8021                let all_selections_were_entire_line =
 8022                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8023                let first_selection_indent_column =
 8024                    clipboard_selections.first().map(|s| s.first_line_indent);
 8025                if clipboard_selections.len() != old_selections.len() {
 8026                    clipboard_selections.drain(..);
 8027                }
 8028                let cursor_offset = this.selections.last::<usize>(cx).head();
 8029                let mut auto_indent_on_paste = true;
 8030
 8031                this.buffer.update(cx, |buffer, cx| {
 8032                    let snapshot = buffer.read(cx);
 8033                    auto_indent_on_paste =
 8034                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8035
 8036                    let mut start_offset = 0;
 8037                    let mut edits = Vec::new();
 8038                    let mut original_indent_columns = Vec::new();
 8039                    for (ix, selection) in old_selections.iter().enumerate() {
 8040                        let to_insert;
 8041                        let entire_line;
 8042                        let original_indent_column;
 8043                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8044                            let end_offset = start_offset + clipboard_selection.len;
 8045                            to_insert = &clipboard_text[start_offset..end_offset];
 8046                            entire_line = clipboard_selection.is_entire_line;
 8047                            start_offset = end_offset + 1;
 8048                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8049                        } else {
 8050                            to_insert = clipboard_text.as_str();
 8051                            entire_line = all_selections_were_entire_line;
 8052                            original_indent_column = first_selection_indent_column
 8053                        }
 8054
 8055                        // If the corresponding selection was empty when this slice of the
 8056                        // clipboard text was written, then the entire line containing the
 8057                        // selection was copied. If this selection is also currently empty,
 8058                        // then paste the line before the current line of the buffer.
 8059                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8060                            let column = selection.start.to_point(&snapshot).column as usize;
 8061                            let line_start = selection.start - column;
 8062                            line_start..line_start
 8063                        } else {
 8064                            selection.range()
 8065                        };
 8066
 8067                        edits.push((range, to_insert));
 8068                        original_indent_columns.extend(original_indent_column);
 8069                    }
 8070                    drop(snapshot);
 8071
 8072                    buffer.edit(
 8073                        edits,
 8074                        if auto_indent_on_paste {
 8075                            Some(AutoindentMode::Block {
 8076                                original_indent_columns,
 8077                            })
 8078                        } else {
 8079                            None
 8080                        },
 8081                        cx,
 8082                    );
 8083                });
 8084
 8085                let selections = this.selections.all::<usize>(cx);
 8086                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8087                    s.select(selections)
 8088                });
 8089            } else {
 8090                this.insert(&clipboard_text, window, cx);
 8091            }
 8092        });
 8093    }
 8094
 8095    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8096        if let Some(item) = cx.read_from_clipboard() {
 8097            let entries = item.entries();
 8098
 8099            match entries.first() {
 8100                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8101                // of all the pasted entries.
 8102                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8103                    .do_paste(
 8104                        clipboard_string.text(),
 8105                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8106                        true,
 8107                        window,
 8108                        cx,
 8109                    ),
 8110                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8111            }
 8112        }
 8113    }
 8114
 8115    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8116        if self.read_only(cx) {
 8117            return;
 8118        }
 8119
 8120        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8121            if let Some((selections, _)) =
 8122                self.selection_history.transaction(transaction_id).cloned()
 8123            {
 8124                self.change_selections(None, window, cx, |s| {
 8125                    s.select_anchors(selections.to_vec());
 8126                });
 8127            }
 8128            self.request_autoscroll(Autoscroll::fit(), cx);
 8129            self.unmark_text(window, cx);
 8130            self.refresh_inline_completion(true, false, window, cx);
 8131            cx.emit(EditorEvent::Edited { transaction_id });
 8132            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8133        }
 8134    }
 8135
 8136    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8137        if self.read_only(cx) {
 8138            return;
 8139        }
 8140
 8141        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8142            if let Some((_, Some(selections))) =
 8143                self.selection_history.transaction(transaction_id).cloned()
 8144            {
 8145                self.change_selections(None, window, cx, |s| {
 8146                    s.select_anchors(selections.to_vec());
 8147                });
 8148            }
 8149            self.request_autoscroll(Autoscroll::fit(), cx);
 8150            self.unmark_text(window, cx);
 8151            self.refresh_inline_completion(true, false, window, cx);
 8152            cx.emit(EditorEvent::Edited { transaction_id });
 8153        }
 8154    }
 8155
 8156    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8157        self.buffer
 8158            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8159    }
 8160
 8161    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8162        self.buffer
 8163            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8164    }
 8165
 8166    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8167        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8168            let line_mode = s.line_mode;
 8169            s.move_with(|map, selection| {
 8170                let cursor = if selection.is_empty() && !line_mode {
 8171                    movement::left(map, selection.start)
 8172                } else {
 8173                    selection.start
 8174                };
 8175                selection.collapse_to(cursor, SelectionGoal::None);
 8176            });
 8177        })
 8178    }
 8179
 8180    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8181        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8182            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8183        })
 8184    }
 8185
 8186    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8188            let line_mode = s.line_mode;
 8189            s.move_with(|map, selection| {
 8190                let cursor = if selection.is_empty() && !line_mode {
 8191                    movement::right(map, selection.end)
 8192                } else {
 8193                    selection.end
 8194                };
 8195                selection.collapse_to(cursor, SelectionGoal::None)
 8196            });
 8197        })
 8198    }
 8199
 8200    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8202            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8203        })
 8204    }
 8205
 8206    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8207        if self.take_rename(true, window, cx).is_some() {
 8208            return;
 8209        }
 8210
 8211        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8212            cx.propagate();
 8213            return;
 8214        }
 8215
 8216        let text_layout_details = &self.text_layout_details(window);
 8217        let selection_count = self.selections.count();
 8218        let first_selection = self.selections.first_anchor();
 8219
 8220        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8221            let line_mode = s.line_mode;
 8222            s.move_with(|map, selection| {
 8223                if !selection.is_empty() && !line_mode {
 8224                    selection.goal = SelectionGoal::None;
 8225                }
 8226                let (cursor, goal) = movement::up(
 8227                    map,
 8228                    selection.start,
 8229                    selection.goal,
 8230                    false,
 8231                    text_layout_details,
 8232                );
 8233                selection.collapse_to(cursor, goal);
 8234            });
 8235        });
 8236
 8237        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8238        {
 8239            cx.propagate();
 8240        }
 8241    }
 8242
 8243    pub fn move_up_by_lines(
 8244        &mut self,
 8245        action: &MoveUpByLines,
 8246        window: &mut Window,
 8247        cx: &mut Context<Self>,
 8248    ) {
 8249        if self.take_rename(true, window, cx).is_some() {
 8250            return;
 8251        }
 8252
 8253        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8254            cx.propagate();
 8255            return;
 8256        }
 8257
 8258        let text_layout_details = &self.text_layout_details(window);
 8259
 8260        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8261            let line_mode = s.line_mode;
 8262            s.move_with(|map, selection| {
 8263                if !selection.is_empty() && !line_mode {
 8264                    selection.goal = SelectionGoal::None;
 8265                }
 8266                let (cursor, goal) = movement::up_by_rows(
 8267                    map,
 8268                    selection.start,
 8269                    action.lines,
 8270                    selection.goal,
 8271                    false,
 8272                    text_layout_details,
 8273                );
 8274                selection.collapse_to(cursor, goal);
 8275            });
 8276        })
 8277    }
 8278
 8279    pub fn move_down_by_lines(
 8280        &mut self,
 8281        action: &MoveDownByLines,
 8282        window: &mut Window,
 8283        cx: &mut Context<Self>,
 8284    ) {
 8285        if self.take_rename(true, window, cx).is_some() {
 8286            return;
 8287        }
 8288
 8289        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8290            cx.propagate();
 8291            return;
 8292        }
 8293
 8294        let text_layout_details = &self.text_layout_details(window);
 8295
 8296        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8297            let line_mode = s.line_mode;
 8298            s.move_with(|map, selection| {
 8299                if !selection.is_empty() && !line_mode {
 8300                    selection.goal = SelectionGoal::None;
 8301                }
 8302                let (cursor, goal) = movement::down_by_rows(
 8303                    map,
 8304                    selection.start,
 8305                    action.lines,
 8306                    selection.goal,
 8307                    false,
 8308                    text_layout_details,
 8309                );
 8310                selection.collapse_to(cursor, goal);
 8311            });
 8312        })
 8313    }
 8314
 8315    pub fn select_down_by_lines(
 8316        &mut self,
 8317        action: &SelectDownByLines,
 8318        window: &mut Window,
 8319        cx: &mut Context<Self>,
 8320    ) {
 8321        let text_layout_details = &self.text_layout_details(window);
 8322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8323            s.move_heads_with(|map, head, goal| {
 8324                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8325            })
 8326        })
 8327    }
 8328
 8329    pub fn select_up_by_lines(
 8330        &mut self,
 8331        action: &SelectUpByLines,
 8332        window: &mut Window,
 8333        cx: &mut Context<Self>,
 8334    ) {
 8335        let text_layout_details = &self.text_layout_details(window);
 8336        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8337            s.move_heads_with(|map, head, goal| {
 8338                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8339            })
 8340        })
 8341    }
 8342
 8343    pub fn select_page_up(
 8344        &mut self,
 8345        _: &SelectPageUp,
 8346        window: &mut Window,
 8347        cx: &mut Context<Self>,
 8348    ) {
 8349        let Some(row_count) = self.visible_row_count() else {
 8350            return;
 8351        };
 8352
 8353        let text_layout_details = &self.text_layout_details(window);
 8354
 8355        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8356            s.move_heads_with(|map, head, goal| {
 8357                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8358            })
 8359        })
 8360    }
 8361
 8362    pub fn move_page_up(
 8363        &mut self,
 8364        action: &MovePageUp,
 8365        window: &mut Window,
 8366        cx: &mut Context<Self>,
 8367    ) {
 8368        if self.take_rename(true, window, cx).is_some() {
 8369            return;
 8370        }
 8371
 8372        if self
 8373            .context_menu
 8374            .borrow_mut()
 8375            .as_mut()
 8376            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8377            .unwrap_or(false)
 8378        {
 8379            return;
 8380        }
 8381
 8382        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8383            cx.propagate();
 8384            return;
 8385        }
 8386
 8387        let Some(row_count) = self.visible_row_count() else {
 8388            return;
 8389        };
 8390
 8391        let autoscroll = if action.center_cursor {
 8392            Autoscroll::center()
 8393        } else {
 8394            Autoscroll::fit()
 8395        };
 8396
 8397        let text_layout_details = &self.text_layout_details(window);
 8398
 8399        self.change_selections(Some(autoscroll), window, cx, |s| {
 8400            let line_mode = s.line_mode;
 8401            s.move_with(|map, selection| {
 8402                if !selection.is_empty() && !line_mode {
 8403                    selection.goal = SelectionGoal::None;
 8404                }
 8405                let (cursor, goal) = movement::up_by_rows(
 8406                    map,
 8407                    selection.end,
 8408                    row_count,
 8409                    selection.goal,
 8410                    false,
 8411                    text_layout_details,
 8412                );
 8413                selection.collapse_to(cursor, goal);
 8414            });
 8415        });
 8416    }
 8417
 8418    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8419        let text_layout_details = &self.text_layout_details(window);
 8420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8421            s.move_heads_with(|map, head, goal| {
 8422                movement::up(map, head, goal, false, text_layout_details)
 8423            })
 8424        })
 8425    }
 8426
 8427    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8428        self.take_rename(true, window, cx);
 8429
 8430        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8431            cx.propagate();
 8432            return;
 8433        }
 8434
 8435        let text_layout_details = &self.text_layout_details(window);
 8436        let selection_count = self.selections.count();
 8437        let first_selection = self.selections.first_anchor();
 8438
 8439        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8440            let line_mode = s.line_mode;
 8441            s.move_with(|map, selection| {
 8442                if !selection.is_empty() && !line_mode {
 8443                    selection.goal = SelectionGoal::None;
 8444                }
 8445                let (cursor, goal) = movement::down(
 8446                    map,
 8447                    selection.end,
 8448                    selection.goal,
 8449                    false,
 8450                    text_layout_details,
 8451                );
 8452                selection.collapse_to(cursor, goal);
 8453            });
 8454        });
 8455
 8456        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8457        {
 8458            cx.propagate();
 8459        }
 8460    }
 8461
 8462    pub fn select_page_down(
 8463        &mut self,
 8464        _: &SelectPageDown,
 8465        window: &mut Window,
 8466        cx: &mut Context<Self>,
 8467    ) {
 8468        let Some(row_count) = self.visible_row_count() else {
 8469            return;
 8470        };
 8471
 8472        let text_layout_details = &self.text_layout_details(window);
 8473
 8474        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8475            s.move_heads_with(|map, head, goal| {
 8476                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8477            })
 8478        })
 8479    }
 8480
 8481    pub fn move_page_down(
 8482        &mut self,
 8483        action: &MovePageDown,
 8484        window: &mut Window,
 8485        cx: &mut Context<Self>,
 8486    ) {
 8487        if self.take_rename(true, window, cx).is_some() {
 8488            return;
 8489        }
 8490
 8491        if self
 8492            .context_menu
 8493            .borrow_mut()
 8494            .as_mut()
 8495            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8496            .unwrap_or(false)
 8497        {
 8498            return;
 8499        }
 8500
 8501        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8502            cx.propagate();
 8503            return;
 8504        }
 8505
 8506        let Some(row_count) = self.visible_row_count() else {
 8507            return;
 8508        };
 8509
 8510        let autoscroll = if action.center_cursor {
 8511            Autoscroll::center()
 8512        } else {
 8513            Autoscroll::fit()
 8514        };
 8515
 8516        let text_layout_details = &self.text_layout_details(window);
 8517        self.change_selections(Some(autoscroll), window, cx, |s| {
 8518            let line_mode = s.line_mode;
 8519            s.move_with(|map, selection| {
 8520                if !selection.is_empty() && !line_mode {
 8521                    selection.goal = SelectionGoal::None;
 8522                }
 8523                let (cursor, goal) = movement::down_by_rows(
 8524                    map,
 8525                    selection.end,
 8526                    row_count,
 8527                    selection.goal,
 8528                    false,
 8529                    text_layout_details,
 8530                );
 8531                selection.collapse_to(cursor, goal);
 8532            });
 8533        });
 8534    }
 8535
 8536    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8537        let text_layout_details = &self.text_layout_details(window);
 8538        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8539            s.move_heads_with(|map, head, goal| {
 8540                movement::down(map, head, goal, false, text_layout_details)
 8541            })
 8542        });
 8543    }
 8544
 8545    pub fn context_menu_first(
 8546        &mut self,
 8547        _: &ContextMenuFirst,
 8548        _window: &mut Window,
 8549        cx: &mut Context<Self>,
 8550    ) {
 8551        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8552            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8553        }
 8554    }
 8555
 8556    pub fn context_menu_prev(
 8557        &mut self,
 8558        _: &ContextMenuPrev,
 8559        _window: &mut Window,
 8560        cx: &mut Context<Self>,
 8561    ) {
 8562        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8563            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8564        }
 8565    }
 8566
 8567    pub fn context_menu_next(
 8568        &mut self,
 8569        _: &ContextMenuNext,
 8570        _window: &mut Window,
 8571        cx: &mut Context<Self>,
 8572    ) {
 8573        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8574            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8575        }
 8576    }
 8577
 8578    pub fn context_menu_last(
 8579        &mut self,
 8580        _: &ContextMenuLast,
 8581        _window: &mut Window,
 8582        cx: &mut Context<Self>,
 8583    ) {
 8584        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8585            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8586        }
 8587    }
 8588
 8589    pub fn move_to_previous_word_start(
 8590        &mut self,
 8591        _: &MoveToPreviousWordStart,
 8592        window: &mut Window,
 8593        cx: &mut Context<Self>,
 8594    ) {
 8595        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8596            s.move_cursors_with(|map, head, _| {
 8597                (
 8598                    movement::previous_word_start(map, head),
 8599                    SelectionGoal::None,
 8600                )
 8601            });
 8602        })
 8603    }
 8604
 8605    pub fn move_to_previous_subword_start(
 8606        &mut self,
 8607        _: &MoveToPreviousSubwordStart,
 8608        window: &mut Window,
 8609        cx: &mut Context<Self>,
 8610    ) {
 8611        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8612            s.move_cursors_with(|map, head, _| {
 8613                (
 8614                    movement::previous_subword_start(map, head),
 8615                    SelectionGoal::None,
 8616                )
 8617            });
 8618        })
 8619    }
 8620
 8621    pub fn select_to_previous_word_start(
 8622        &mut self,
 8623        _: &SelectToPreviousWordStart,
 8624        window: &mut Window,
 8625        cx: &mut Context<Self>,
 8626    ) {
 8627        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8628            s.move_heads_with(|map, head, _| {
 8629                (
 8630                    movement::previous_word_start(map, head),
 8631                    SelectionGoal::None,
 8632                )
 8633            });
 8634        })
 8635    }
 8636
 8637    pub fn select_to_previous_subword_start(
 8638        &mut self,
 8639        _: &SelectToPreviousSubwordStart,
 8640        window: &mut Window,
 8641        cx: &mut Context<Self>,
 8642    ) {
 8643        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8644            s.move_heads_with(|map, head, _| {
 8645                (
 8646                    movement::previous_subword_start(map, head),
 8647                    SelectionGoal::None,
 8648                )
 8649            });
 8650        })
 8651    }
 8652
 8653    pub fn delete_to_previous_word_start(
 8654        &mut self,
 8655        action: &DeleteToPreviousWordStart,
 8656        window: &mut Window,
 8657        cx: &mut Context<Self>,
 8658    ) {
 8659        self.transact(window, cx, |this, window, cx| {
 8660            this.select_autoclose_pair(window, cx);
 8661            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8662                let line_mode = s.line_mode;
 8663                s.move_with(|map, selection| {
 8664                    if selection.is_empty() && !line_mode {
 8665                        let cursor = if action.ignore_newlines {
 8666                            movement::previous_word_start(map, selection.head())
 8667                        } else {
 8668                            movement::previous_word_start_or_newline(map, selection.head())
 8669                        };
 8670                        selection.set_head(cursor, SelectionGoal::None);
 8671                    }
 8672                });
 8673            });
 8674            this.insert("", window, cx);
 8675        });
 8676    }
 8677
 8678    pub fn delete_to_previous_subword_start(
 8679        &mut self,
 8680        _: &DeleteToPreviousSubwordStart,
 8681        window: &mut Window,
 8682        cx: &mut Context<Self>,
 8683    ) {
 8684        self.transact(window, cx, |this, window, cx| {
 8685            this.select_autoclose_pair(window, cx);
 8686            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8687                let line_mode = s.line_mode;
 8688                s.move_with(|map, selection| {
 8689                    if selection.is_empty() && !line_mode {
 8690                        let cursor = movement::previous_subword_start(map, selection.head());
 8691                        selection.set_head(cursor, SelectionGoal::None);
 8692                    }
 8693                });
 8694            });
 8695            this.insert("", window, cx);
 8696        });
 8697    }
 8698
 8699    pub fn move_to_next_word_end(
 8700        &mut self,
 8701        _: &MoveToNextWordEnd,
 8702        window: &mut Window,
 8703        cx: &mut Context<Self>,
 8704    ) {
 8705        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8706            s.move_cursors_with(|map, head, _| {
 8707                (movement::next_word_end(map, head), SelectionGoal::None)
 8708            });
 8709        })
 8710    }
 8711
 8712    pub fn move_to_next_subword_end(
 8713        &mut self,
 8714        _: &MoveToNextSubwordEnd,
 8715        window: &mut Window,
 8716        cx: &mut Context<Self>,
 8717    ) {
 8718        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8719            s.move_cursors_with(|map, head, _| {
 8720                (movement::next_subword_end(map, head), SelectionGoal::None)
 8721            });
 8722        })
 8723    }
 8724
 8725    pub fn select_to_next_word_end(
 8726        &mut self,
 8727        _: &SelectToNextWordEnd,
 8728        window: &mut Window,
 8729        cx: &mut Context<Self>,
 8730    ) {
 8731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8732            s.move_heads_with(|map, head, _| {
 8733                (movement::next_word_end(map, head), SelectionGoal::None)
 8734            });
 8735        })
 8736    }
 8737
 8738    pub fn select_to_next_subword_end(
 8739        &mut self,
 8740        _: &SelectToNextSubwordEnd,
 8741        window: &mut Window,
 8742        cx: &mut Context<Self>,
 8743    ) {
 8744        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8745            s.move_heads_with(|map, head, _| {
 8746                (movement::next_subword_end(map, head), SelectionGoal::None)
 8747            });
 8748        })
 8749    }
 8750
 8751    pub fn delete_to_next_word_end(
 8752        &mut self,
 8753        action: &DeleteToNextWordEnd,
 8754        window: &mut Window,
 8755        cx: &mut Context<Self>,
 8756    ) {
 8757        self.transact(window, cx, |this, window, cx| {
 8758            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8759                let line_mode = s.line_mode;
 8760                s.move_with(|map, selection| {
 8761                    if selection.is_empty() && !line_mode {
 8762                        let cursor = if action.ignore_newlines {
 8763                            movement::next_word_end(map, selection.head())
 8764                        } else {
 8765                            movement::next_word_end_or_newline(map, selection.head())
 8766                        };
 8767                        selection.set_head(cursor, SelectionGoal::None);
 8768                    }
 8769                });
 8770            });
 8771            this.insert("", window, cx);
 8772        });
 8773    }
 8774
 8775    pub fn delete_to_next_subword_end(
 8776        &mut self,
 8777        _: &DeleteToNextSubwordEnd,
 8778        window: &mut Window,
 8779        cx: &mut Context<Self>,
 8780    ) {
 8781        self.transact(window, cx, |this, window, cx| {
 8782            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8783                s.move_with(|map, selection| {
 8784                    if selection.is_empty() {
 8785                        let cursor = movement::next_subword_end(map, selection.head());
 8786                        selection.set_head(cursor, SelectionGoal::None);
 8787                    }
 8788                });
 8789            });
 8790            this.insert("", window, cx);
 8791        });
 8792    }
 8793
 8794    pub fn move_to_beginning_of_line(
 8795        &mut self,
 8796        action: &MoveToBeginningOfLine,
 8797        window: &mut Window,
 8798        cx: &mut Context<Self>,
 8799    ) {
 8800        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8801            s.move_cursors_with(|map, head, _| {
 8802                (
 8803                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8804                    SelectionGoal::None,
 8805                )
 8806            });
 8807        })
 8808    }
 8809
 8810    pub fn select_to_beginning_of_line(
 8811        &mut self,
 8812        action: &SelectToBeginningOfLine,
 8813        window: &mut Window,
 8814        cx: &mut Context<Self>,
 8815    ) {
 8816        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8817            s.move_heads_with(|map, head, _| {
 8818                (
 8819                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8820                    SelectionGoal::None,
 8821                )
 8822            });
 8823        });
 8824    }
 8825
 8826    pub fn delete_to_beginning_of_line(
 8827        &mut self,
 8828        _: &DeleteToBeginningOfLine,
 8829        window: &mut Window,
 8830        cx: &mut Context<Self>,
 8831    ) {
 8832        self.transact(window, cx, |this, window, cx| {
 8833            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8834                s.move_with(|_, selection| {
 8835                    selection.reversed = true;
 8836                });
 8837            });
 8838
 8839            this.select_to_beginning_of_line(
 8840                &SelectToBeginningOfLine {
 8841                    stop_at_soft_wraps: false,
 8842                },
 8843                window,
 8844                cx,
 8845            );
 8846            this.backspace(&Backspace, window, cx);
 8847        });
 8848    }
 8849
 8850    pub fn move_to_end_of_line(
 8851        &mut self,
 8852        action: &MoveToEndOfLine,
 8853        window: &mut Window,
 8854        cx: &mut Context<Self>,
 8855    ) {
 8856        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8857            s.move_cursors_with(|map, head, _| {
 8858                (
 8859                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8860                    SelectionGoal::None,
 8861                )
 8862            });
 8863        })
 8864    }
 8865
 8866    pub fn select_to_end_of_line(
 8867        &mut self,
 8868        action: &SelectToEndOfLine,
 8869        window: &mut Window,
 8870        cx: &mut Context<Self>,
 8871    ) {
 8872        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8873            s.move_heads_with(|map, head, _| {
 8874                (
 8875                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8876                    SelectionGoal::None,
 8877                )
 8878            });
 8879        })
 8880    }
 8881
 8882    pub fn delete_to_end_of_line(
 8883        &mut self,
 8884        _: &DeleteToEndOfLine,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887    ) {
 8888        self.transact(window, cx, |this, window, cx| {
 8889            this.select_to_end_of_line(
 8890                &SelectToEndOfLine {
 8891                    stop_at_soft_wraps: false,
 8892                },
 8893                window,
 8894                cx,
 8895            );
 8896            this.delete(&Delete, window, cx);
 8897        });
 8898    }
 8899
 8900    pub fn cut_to_end_of_line(
 8901        &mut self,
 8902        _: &CutToEndOfLine,
 8903        window: &mut Window,
 8904        cx: &mut Context<Self>,
 8905    ) {
 8906        self.transact(window, cx, |this, window, cx| {
 8907            this.select_to_end_of_line(
 8908                &SelectToEndOfLine {
 8909                    stop_at_soft_wraps: false,
 8910                },
 8911                window,
 8912                cx,
 8913            );
 8914            this.cut(&Cut, window, cx);
 8915        });
 8916    }
 8917
 8918    pub fn move_to_start_of_paragraph(
 8919        &mut self,
 8920        _: &MoveToStartOfParagraph,
 8921        window: &mut Window,
 8922        cx: &mut Context<Self>,
 8923    ) {
 8924        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8925            cx.propagate();
 8926            return;
 8927        }
 8928
 8929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8930            s.move_with(|map, selection| {
 8931                selection.collapse_to(
 8932                    movement::start_of_paragraph(map, selection.head(), 1),
 8933                    SelectionGoal::None,
 8934                )
 8935            });
 8936        })
 8937    }
 8938
 8939    pub fn move_to_end_of_paragraph(
 8940        &mut self,
 8941        _: &MoveToEndOfParagraph,
 8942        window: &mut Window,
 8943        cx: &mut Context<Self>,
 8944    ) {
 8945        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8946            cx.propagate();
 8947            return;
 8948        }
 8949
 8950        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8951            s.move_with(|map, selection| {
 8952                selection.collapse_to(
 8953                    movement::end_of_paragraph(map, selection.head(), 1),
 8954                    SelectionGoal::None,
 8955                )
 8956            });
 8957        })
 8958    }
 8959
 8960    pub fn select_to_start_of_paragraph(
 8961        &mut self,
 8962        _: &SelectToStartOfParagraph,
 8963        window: &mut Window,
 8964        cx: &mut Context<Self>,
 8965    ) {
 8966        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8967            cx.propagate();
 8968            return;
 8969        }
 8970
 8971        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8972            s.move_heads_with(|map, head, _| {
 8973                (
 8974                    movement::start_of_paragraph(map, head, 1),
 8975                    SelectionGoal::None,
 8976                )
 8977            });
 8978        })
 8979    }
 8980
 8981    pub fn select_to_end_of_paragraph(
 8982        &mut self,
 8983        _: &SelectToEndOfParagraph,
 8984        window: &mut Window,
 8985        cx: &mut Context<Self>,
 8986    ) {
 8987        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8988            cx.propagate();
 8989            return;
 8990        }
 8991
 8992        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8993            s.move_heads_with(|map, head, _| {
 8994                (
 8995                    movement::end_of_paragraph(map, head, 1),
 8996                    SelectionGoal::None,
 8997                )
 8998            });
 8999        })
 9000    }
 9001
 9002    pub fn move_to_beginning(
 9003        &mut self,
 9004        _: &MoveToBeginning,
 9005        window: &mut Window,
 9006        cx: &mut Context<Self>,
 9007    ) {
 9008        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9009            cx.propagate();
 9010            return;
 9011        }
 9012
 9013        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9014            s.select_ranges(vec![0..0]);
 9015        });
 9016    }
 9017
 9018    pub fn select_to_beginning(
 9019        &mut self,
 9020        _: &SelectToBeginning,
 9021        window: &mut Window,
 9022        cx: &mut Context<Self>,
 9023    ) {
 9024        let mut selection = self.selections.last::<Point>(cx);
 9025        selection.set_head(Point::zero(), SelectionGoal::None);
 9026
 9027        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9028            s.select(vec![selection]);
 9029        });
 9030    }
 9031
 9032    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9033        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9034            cx.propagate();
 9035            return;
 9036        }
 9037
 9038        let cursor = self.buffer.read(cx).read(cx).len();
 9039        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9040            s.select_ranges(vec![cursor..cursor])
 9041        });
 9042    }
 9043
 9044    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9045        self.nav_history = nav_history;
 9046    }
 9047
 9048    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9049        self.nav_history.as_ref()
 9050    }
 9051
 9052    fn push_to_nav_history(
 9053        &mut self,
 9054        cursor_anchor: Anchor,
 9055        new_position: Option<Point>,
 9056        cx: &mut Context<Self>,
 9057    ) {
 9058        if let Some(nav_history) = self.nav_history.as_mut() {
 9059            let buffer = self.buffer.read(cx).read(cx);
 9060            let cursor_position = cursor_anchor.to_point(&buffer);
 9061            let scroll_state = self.scroll_manager.anchor();
 9062            let scroll_top_row = scroll_state.top_row(&buffer);
 9063            drop(buffer);
 9064
 9065            if let Some(new_position) = new_position {
 9066                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9067                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9068                    return;
 9069                }
 9070            }
 9071
 9072            nav_history.push(
 9073                Some(NavigationData {
 9074                    cursor_anchor,
 9075                    cursor_position,
 9076                    scroll_anchor: scroll_state,
 9077                    scroll_top_row,
 9078                }),
 9079                cx,
 9080            );
 9081        }
 9082    }
 9083
 9084    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9085        let buffer = self.buffer.read(cx).snapshot(cx);
 9086        let mut selection = self.selections.first::<usize>(cx);
 9087        selection.set_head(buffer.len(), SelectionGoal::None);
 9088        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9089            s.select(vec![selection]);
 9090        });
 9091    }
 9092
 9093    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9094        let end = self.buffer.read(cx).read(cx).len();
 9095        self.change_selections(None, window, cx, |s| {
 9096            s.select_ranges(vec![0..end]);
 9097        });
 9098    }
 9099
 9100    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9102        let mut selections = self.selections.all::<Point>(cx);
 9103        let max_point = display_map.buffer_snapshot.max_point();
 9104        for selection in &mut selections {
 9105            let rows = selection.spanned_rows(true, &display_map);
 9106            selection.start = Point::new(rows.start.0, 0);
 9107            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9108            selection.reversed = false;
 9109        }
 9110        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9111            s.select(selections);
 9112        });
 9113    }
 9114
 9115    pub fn split_selection_into_lines(
 9116        &mut self,
 9117        _: &SplitSelectionIntoLines,
 9118        window: &mut Window,
 9119        cx: &mut Context<Self>,
 9120    ) {
 9121        let selections = self
 9122            .selections
 9123            .all::<Point>(cx)
 9124            .into_iter()
 9125            .map(|selection| selection.start..selection.end)
 9126            .collect::<Vec<_>>();
 9127        self.unfold_ranges(&selections, true, true, cx);
 9128
 9129        let mut new_selection_ranges = Vec::new();
 9130        {
 9131            let buffer = self.buffer.read(cx).read(cx);
 9132            for selection in selections {
 9133                for row in selection.start.row..selection.end.row {
 9134                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9135                    new_selection_ranges.push(cursor..cursor);
 9136                }
 9137
 9138                let is_multiline_selection = selection.start.row != selection.end.row;
 9139                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9140                // so this action feels more ergonomic when paired with other selection operations
 9141                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9142                if !should_skip_last {
 9143                    new_selection_ranges.push(selection.end..selection.end);
 9144                }
 9145            }
 9146        }
 9147        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9148            s.select_ranges(new_selection_ranges);
 9149        });
 9150    }
 9151
 9152    pub fn add_selection_above(
 9153        &mut self,
 9154        _: &AddSelectionAbove,
 9155        window: &mut Window,
 9156        cx: &mut Context<Self>,
 9157    ) {
 9158        self.add_selection(true, window, cx);
 9159    }
 9160
 9161    pub fn add_selection_below(
 9162        &mut self,
 9163        _: &AddSelectionBelow,
 9164        window: &mut Window,
 9165        cx: &mut Context<Self>,
 9166    ) {
 9167        self.add_selection(false, window, cx);
 9168    }
 9169
 9170    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9171        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9172        let mut selections = self.selections.all::<Point>(cx);
 9173        let text_layout_details = self.text_layout_details(window);
 9174        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9175            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9176            let range = oldest_selection.display_range(&display_map).sorted();
 9177
 9178            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9179            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9180            let positions = start_x.min(end_x)..start_x.max(end_x);
 9181
 9182            selections.clear();
 9183            let mut stack = Vec::new();
 9184            for row in range.start.row().0..=range.end.row().0 {
 9185                if let Some(selection) = self.selections.build_columnar_selection(
 9186                    &display_map,
 9187                    DisplayRow(row),
 9188                    &positions,
 9189                    oldest_selection.reversed,
 9190                    &text_layout_details,
 9191                ) {
 9192                    stack.push(selection.id);
 9193                    selections.push(selection);
 9194                }
 9195            }
 9196
 9197            if above {
 9198                stack.reverse();
 9199            }
 9200
 9201            AddSelectionsState { above, stack }
 9202        });
 9203
 9204        let last_added_selection = *state.stack.last().unwrap();
 9205        let mut new_selections = Vec::new();
 9206        if above == state.above {
 9207            let end_row = if above {
 9208                DisplayRow(0)
 9209            } else {
 9210                display_map.max_point().row()
 9211            };
 9212
 9213            'outer: for selection in selections {
 9214                if selection.id == last_added_selection {
 9215                    let range = selection.display_range(&display_map).sorted();
 9216                    debug_assert_eq!(range.start.row(), range.end.row());
 9217                    let mut row = range.start.row();
 9218                    let positions =
 9219                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9220                            px(start)..px(end)
 9221                        } else {
 9222                            let start_x =
 9223                                display_map.x_for_display_point(range.start, &text_layout_details);
 9224                            let end_x =
 9225                                display_map.x_for_display_point(range.end, &text_layout_details);
 9226                            start_x.min(end_x)..start_x.max(end_x)
 9227                        };
 9228
 9229                    while row != end_row {
 9230                        if above {
 9231                            row.0 -= 1;
 9232                        } else {
 9233                            row.0 += 1;
 9234                        }
 9235
 9236                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9237                            &display_map,
 9238                            row,
 9239                            &positions,
 9240                            selection.reversed,
 9241                            &text_layout_details,
 9242                        ) {
 9243                            state.stack.push(new_selection.id);
 9244                            if above {
 9245                                new_selections.push(new_selection);
 9246                                new_selections.push(selection);
 9247                            } else {
 9248                                new_selections.push(selection);
 9249                                new_selections.push(new_selection);
 9250                            }
 9251
 9252                            continue 'outer;
 9253                        }
 9254                    }
 9255                }
 9256
 9257                new_selections.push(selection);
 9258            }
 9259        } else {
 9260            new_selections = selections;
 9261            new_selections.retain(|s| s.id != last_added_selection);
 9262            state.stack.pop();
 9263        }
 9264
 9265        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9266            s.select(new_selections);
 9267        });
 9268        if state.stack.len() > 1 {
 9269            self.add_selections_state = Some(state);
 9270        }
 9271    }
 9272
 9273    pub fn select_next_match_internal(
 9274        &mut self,
 9275        display_map: &DisplaySnapshot,
 9276        replace_newest: bool,
 9277        autoscroll: Option<Autoscroll>,
 9278        window: &mut Window,
 9279        cx: &mut Context<Self>,
 9280    ) -> Result<()> {
 9281        fn select_next_match_ranges(
 9282            this: &mut Editor,
 9283            range: Range<usize>,
 9284            replace_newest: bool,
 9285            auto_scroll: Option<Autoscroll>,
 9286            window: &mut Window,
 9287            cx: &mut Context<Editor>,
 9288        ) {
 9289            this.unfold_ranges(&[range.clone()], false, true, cx);
 9290            this.change_selections(auto_scroll, window, cx, |s| {
 9291                if replace_newest {
 9292                    s.delete(s.newest_anchor().id);
 9293                }
 9294                s.insert_range(range.clone());
 9295            });
 9296        }
 9297
 9298        let buffer = &display_map.buffer_snapshot;
 9299        let mut selections = self.selections.all::<usize>(cx);
 9300        if let Some(mut select_next_state) = self.select_next_state.take() {
 9301            let query = &select_next_state.query;
 9302            if !select_next_state.done {
 9303                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9304                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9305                let mut next_selected_range = None;
 9306
 9307                let bytes_after_last_selection =
 9308                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9309                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9310                let query_matches = query
 9311                    .stream_find_iter(bytes_after_last_selection)
 9312                    .map(|result| (last_selection.end, result))
 9313                    .chain(
 9314                        query
 9315                            .stream_find_iter(bytes_before_first_selection)
 9316                            .map(|result| (0, result)),
 9317                    );
 9318
 9319                for (start_offset, query_match) in query_matches {
 9320                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9321                    let offset_range =
 9322                        start_offset + query_match.start()..start_offset + query_match.end();
 9323                    let display_range = offset_range.start.to_display_point(display_map)
 9324                        ..offset_range.end.to_display_point(display_map);
 9325
 9326                    if !select_next_state.wordwise
 9327                        || (!movement::is_inside_word(display_map, display_range.start)
 9328                            && !movement::is_inside_word(display_map, display_range.end))
 9329                    {
 9330                        // TODO: This is n^2, because we might check all the selections
 9331                        if !selections
 9332                            .iter()
 9333                            .any(|selection| selection.range().overlaps(&offset_range))
 9334                        {
 9335                            next_selected_range = Some(offset_range);
 9336                            break;
 9337                        }
 9338                    }
 9339                }
 9340
 9341                if let Some(next_selected_range) = next_selected_range {
 9342                    select_next_match_ranges(
 9343                        self,
 9344                        next_selected_range,
 9345                        replace_newest,
 9346                        autoscroll,
 9347                        window,
 9348                        cx,
 9349                    );
 9350                } else {
 9351                    select_next_state.done = true;
 9352                }
 9353            }
 9354
 9355            self.select_next_state = Some(select_next_state);
 9356        } else {
 9357            let mut only_carets = true;
 9358            let mut same_text_selected = true;
 9359            let mut selected_text = None;
 9360
 9361            let mut selections_iter = selections.iter().peekable();
 9362            while let Some(selection) = selections_iter.next() {
 9363                if selection.start != selection.end {
 9364                    only_carets = false;
 9365                }
 9366
 9367                if same_text_selected {
 9368                    if selected_text.is_none() {
 9369                        selected_text =
 9370                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9371                    }
 9372
 9373                    if let Some(next_selection) = selections_iter.peek() {
 9374                        if next_selection.range().len() == selection.range().len() {
 9375                            let next_selected_text = buffer
 9376                                .text_for_range(next_selection.range())
 9377                                .collect::<String>();
 9378                            if Some(next_selected_text) != selected_text {
 9379                                same_text_selected = false;
 9380                                selected_text = None;
 9381                            }
 9382                        } else {
 9383                            same_text_selected = false;
 9384                            selected_text = None;
 9385                        }
 9386                    }
 9387                }
 9388            }
 9389
 9390            if only_carets {
 9391                for selection in &mut selections {
 9392                    let word_range = movement::surrounding_word(
 9393                        display_map,
 9394                        selection.start.to_display_point(display_map),
 9395                    );
 9396                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9397                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9398                    selection.goal = SelectionGoal::None;
 9399                    selection.reversed = false;
 9400                    select_next_match_ranges(
 9401                        self,
 9402                        selection.start..selection.end,
 9403                        replace_newest,
 9404                        autoscroll,
 9405                        window,
 9406                        cx,
 9407                    );
 9408                }
 9409
 9410                if selections.len() == 1 {
 9411                    let selection = selections
 9412                        .last()
 9413                        .expect("ensured that there's only one selection");
 9414                    let query = buffer
 9415                        .text_for_range(selection.start..selection.end)
 9416                        .collect::<String>();
 9417                    let is_empty = query.is_empty();
 9418                    let select_state = SelectNextState {
 9419                        query: AhoCorasick::new(&[query])?,
 9420                        wordwise: true,
 9421                        done: is_empty,
 9422                    };
 9423                    self.select_next_state = Some(select_state);
 9424                } else {
 9425                    self.select_next_state = None;
 9426                }
 9427            } else if let Some(selected_text) = selected_text {
 9428                self.select_next_state = Some(SelectNextState {
 9429                    query: AhoCorasick::new(&[selected_text])?,
 9430                    wordwise: false,
 9431                    done: false,
 9432                });
 9433                self.select_next_match_internal(
 9434                    display_map,
 9435                    replace_newest,
 9436                    autoscroll,
 9437                    window,
 9438                    cx,
 9439                )?;
 9440            }
 9441        }
 9442        Ok(())
 9443    }
 9444
 9445    pub fn select_all_matches(
 9446        &mut self,
 9447        _action: &SelectAllMatches,
 9448        window: &mut Window,
 9449        cx: &mut Context<Self>,
 9450    ) -> Result<()> {
 9451        self.push_to_selection_history();
 9452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9453
 9454        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9455        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9456            return Ok(());
 9457        };
 9458        if select_next_state.done {
 9459            return Ok(());
 9460        }
 9461
 9462        let mut new_selections = self.selections.all::<usize>(cx);
 9463
 9464        let buffer = &display_map.buffer_snapshot;
 9465        let query_matches = select_next_state
 9466            .query
 9467            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9468
 9469        for query_match in query_matches {
 9470            let query_match = query_match.unwrap(); // can only fail due to I/O
 9471            let offset_range = query_match.start()..query_match.end();
 9472            let display_range = offset_range.start.to_display_point(&display_map)
 9473                ..offset_range.end.to_display_point(&display_map);
 9474
 9475            if !select_next_state.wordwise
 9476                || (!movement::is_inside_word(&display_map, display_range.start)
 9477                    && !movement::is_inside_word(&display_map, display_range.end))
 9478            {
 9479                self.selections.change_with(cx, |selections| {
 9480                    new_selections.push(Selection {
 9481                        id: selections.new_selection_id(),
 9482                        start: offset_range.start,
 9483                        end: offset_range.end,
 9484                        reversed: false,
 9485                        goal: SelectionGoal::None,
 9486                    });
 9487                });
 9488            }
 9489        }
 9490
 9491        new_selections.sort_by_key(|selection| selection.start);
 9492        let mut ix = 0;
 9493        while ix + 1 < new_selections.len() {
 9494            let current_selection = &new_selections[ix];
 9495            let next_selection = &new_selections[ix + 1];
 9496            if current_selection.range().overlaps(&next_selection.range()) {
 9497                if current_selection.id < next_selection.id {
 9498                    new_selections.remove(ix + 1);
 9499                } else {
 9500                    new_selections.remove(ix);
 9501                }
 9502            } else {
 9503                ix += 1;
 9504            }
 9505        }
 9506
 9507        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9508
 9509        for selection in new_selections.iter_mut() {
 9510            selection.reversed = reversed;
 9511        }
 9512
 9513        select_next_state.done = true;
 9514        self.unfold_ranges(
 9515            &new_selections
 9516                .iter()
 9517                .map(|selection| selection.range())
 9518                .collect::<Vec<_>>(),
 9519            false,
 9520            false,
 9521            cx,
 9522        );
 9523        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9524            selections.select(new_selections)
 9525        });
 9526
 9527        Ok(())
 9528    }
 9529
 9530    pub fn select_next(
 9531        &mut self,
 9532        action: &SelectNext,
 9533        window: &mut Window,
 9534        cx: &mut Context<Self>,
 9535    ) -> Result<()> {
 9536        self.push_to_selection_history();
 9537        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9538        self.select_next_match_internal(
 9539            &display_map,
 9540            action.replace_newest,
 9541            Some(Autoscroll::newest()),
 9542            window,
 9543            cx,
 9544        )?;
 9545        Ok(())
 9546    }
 9547
 9548    pub fn select_previous(
 9549        &mut self,
 9550        action: &SelectPrevious,
 9551        window: &mut Window,
 9552        cx: &mut Context<Self>,
 9553    ) -> Result<()> {
 9554        self.push_to_selection_history();
 9555        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9556        let buffer = &display_map.buffer_snapshot;
 9557        let mut selections = self.selections.all::<usize>(cx);
 9558        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9559            let query = &select_prev_state.query;
 9560            if !select_prev_state.done {
 9561                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9562                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9563                let mut next_selected_range = None;
 9564                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9565                let bytes_before_last_selection =
 9566                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9567                let bytes_after_first_selection =
 9568                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9569                let query_matches = query
 9570                    .stream_find_iter(bytes_before_last_selection)
 9571                    .map(|result| (last_selection.start, result))
 9572                    .chain(
 9573                        query
 9574                            .stream_find_iter(bytes_after_first_selection)
 9575                            .map(|result| (buffer.len(), result)),
 9576                    );
 9577                for (end_offset, query_match) in query_matches {
 9578                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9579                    let offset_range =
 9580                        end_offset - query_match.end()..end_offset - query_match.start();
 9581                    let display_range = offset_range.start.to_display_point(&display_map)
 9582                        ..offset_range.end.to_display_point(&display_map);
 9583
 9584                    if !select_prev_state.wordwise
 9585                        || (!movement::is_inside_word(&display_map, display_range.start)
 9586                            && !movement::is_inside_word(&display_map, display_range.end))
 9587                    {
 9588                        next_selected_range = Some(offset_range);
 9589                        break;
 9590                    }
 9591                }
 9592
 9593                if let Some(next_selected_range) = next_selected_range {
 9594                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9595                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9596                        if action.replace_newest {
 9597                            s.delete(s.newest_anchor().id);
 9598                        }
 9599                        s.insert_range(next_selected_range);
 9600                    });
 9601                } else {
 9602                    select_prev_state.done = true;
 9603                }
 9604            }
 9605
 9606            self.select_prev_state = Some(select_prev_state);
 9607        } else {
 9608            let mut only_carets = true;
 9609            let mut same_text_selected = true;
 9610            let mut selected_text = None;
 9611
 9612            let mut selections_iter = selections.iter().peekable();
 9613            while let Some(selection) = selections_iter.next() {
 9614                if selection.start != selection.end {
 9615                    only_carets = false;
 9616                }
 9617
 9618                if same_text_selected {
 9619                    if selected_text.is_none() {
 9620                        selected_text =
 9621                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9622                    }
 9623
 9624                    if let Some(next_selection) = selections_iter.peek() {
 9625                        if next_selection.range().len() == selection.range().len() {
 9626                            let next_selected_text = buffer
 9627                                .text_for_range(next_selection.range())
 9628                                .collect::<String>();
 9629                            if Some(next_selected_text) != selected_text {
 9630                                same_text_selected = false;
 9631                                selected_text = None;
 9632                            }
 9633                        } else {
 9634                            same_text_selected = false;
 9635                            selected_text = None;
 9636                        }
 9637                    }
 9638                }
 9639            }
 9640
 9641            if only_carets {
 9642                for selection in &mut selections {
 9643                    let word_range = movement::surrounding_word(
 9644                        &display_map,
 9645                        selection.start.to_display_point(&display_map),
 9646                    );
 9647                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9648                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9649                    selection.goal = SelectionGoal::None;
 9650                    selection.reversed = false;
 9651                }
 9652                if selections.len() == 1 {
 9653                    let selection = selections
 9654                        .last()
 9655                        .expect("ensured that there's only one selection");
 9656                    let query = buffer
 9657                        .text_for_range(selection.start..selection.end)
 9658                        .collect::<String>();
 9659                    let is_empty = query.is_empty();
 9660                    let select_state = SelectNextState {
 9661                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9662                        wordwise: true,
 9663                        done: is_empty,
 9664                    };
 9665                    self.select_prev_state = Some(select_state);
 9666                } else {
 9667                    self.select_prev_state = None;
 9668                }
 9669
 9670                self.unfold_ranges(
 9671                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9672                    false,
 9673                    true,
 9674                    cx,
 9675                );
 9676                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9677                    s.select(selections);
 9678                });
 9679            } else if let Some(selected_text) = selected_text {
 9680                self.select_prev_state = Some(SelectNextState {
 9681                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9682                    wordwise: false,
 9683                    done: false,
 9684                });
 9685                self.select_previous(action, window, cx)?;
 9686            }
 9687        }
 9688        Ok(())
 9689    }
 9690
 9691    pub fn toggle_comments(
 9692        &mut self,
 9693        action: &ToggleComments,
 9694        window: &mut Window,
 9695        cx: &mut Context<Self>,
 9696    ) {
 9697        if self.read_only(cx) {
 9698            return;
 9699        }
 9700        let text_layout_details = &self.text_layout_details(window);
 9701        self.transact(window, cx, |this, window, cx| {
 9702            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9703            let mut edits = Vec::new();
 9704            let mut selection_edit_ranges = Vec::new();
 9705            let mut last_toggled_row = None;
 9706            let snapshot = this.buffer.read(cx).read(cx);
 9707            let empty_str: Arc<str> = Arc::default();
 9708            let mut suffixes_inserted = Vec::new();
 9709            let ignore_indent = action.ignore_indent;
 9710
 9711            fn comment_prefix_range(
 9712                snapshot: &MultiBufferSnapshot,
 9713                row: MultiBufferRow,
 9714                comment_prefix: &str,
 9715                comment_prefix_whitespace: &str,
 9716                ignore_indent: bool,
 9717            ) -> Range<Point> {
 9718                let indent_size = if ignore_indent {
 9719                    0
 9720                } else {
 9721                    snapshot.indent_size_for_line(row).len
 9722                };
 9723
 9724                let start = Point::new(row.0, indent_size);
 9725
 9726                let mut line_bytes = snapshot
 9727                    .bytes_in_range(start..snapshot.max_point())
 9728                    .flatten()
 9729                    .copied();
 9730
 9731                // If this line currently begins with the line comment prefix, then record
 9732                // the range containing the prefix.
 9733                if line_bytes
 9734                    .by_ref()
 9735                    .take(comment_prefix.len())
 9736                    .eq(comment_prefix.bytes())
 9737                {
 9738                    // Include any whitespace that matches the comment prefix.
 9739                    let matching_whitespace_len = line_bytes
 9740                        .zip(comment_prefix_whitespace.bytes())
 9741                        .take_while(|(a, b)| a == b)
 9742                        .count() as u32;
 9743                    let end = Point::new(
 9744                        start.row,
 9745                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9746                    );
 9747                    start..end
 9748                } else {
 9749                    start..start
 9750                }
 9751            }
 9752
 9753            fn comment_suffix_range(
 9754                snapshot: &MultiBufferSnapshot,
 9755                row: MultiBufferRow,
 9756                comment_suffix: &str,
 9757                comment_suffix_has_leading_space: bool,
 9758            ) -> Range<Point> {
 9759                let end = Point::new(row.0, snapshot.line_len(row));
 9760                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9761
 9762                let mut line_end_bytes = snapshot
 9763                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9764                    .flatten()
 9765                    .copied();
 9766
 9767                let leading_space_len = if suffix_start_column > 0
 9768                    && line_end_bytes.next() == Some(b' ')
 9769                    && comment_suffix_has_leading_space
 9770                {
 9771                    1
 9772                } else {
 9773                    0
 9774                };
 9775
 9776                // If this line currently begins with the line comment prefix, then record
 9777                // the range containing the prefix.
 9778                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9779                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9780                    start..end
 9781                } else {
 9782                    end..end
 9783                }
 9784            }
 9785
 9786            // TODO: Handle selections that cross excerpts
 9787            for selection in &mut selections {
 9788                let start_column = snapshot
 9789                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9790                    .len;
 9791                let language = if let Some(language) =
 9792                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9793                {
 9794                    language
 9795                } else {
 9796                    continue;
 9797                };
 9798
 9799                selection_edit_ranges.clear();
 9800
 9801                // If multiple selections contain a given row, avoid processing that
 9802                // row more than once.
 9803                let mut start_row = MultiBufferRow(selection.start.row);
 9804                if last_toggled_row == Some(start_row) {
 9805                    start_row = start_row.next_row();
 9806                }
 9807                let end_row =
 9808                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9809                        MultiBufferRow(selection.end.row - 1)
 9810                    } else {
 9811                        MultiBufferRow(selection.end.row)
 9812                    };
 9813                last_toggled_row = Some(end_row);
 9814
 9815                if start_row > end_row {
 9816                    continue;
 9817                }
 9818
 9819                // If the language has line comments, toggle those.
 9820                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9821
 9822                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9823                if ignore_indent {
 9824                    full_comment_prefixes = full_comment_prefixes
 9825                        .into_iter()
 9826                        .map(|s| Arc::from(s.trim_end()))
 9827                        .collect();
 9828                }
 9829
 9830                if !full_comment_prefixes.is_empty() {
 9831                    let first_prefix = full_comment_prefixes
 9832                        .first()
 9833                        .expect("prefixes is non-empty");
 9834                    let prefix_trimmed_lengths = full_comment_prefixes
 9835                        .iter()
 9836                        .map(|p| p.trim_end_matches(' ').len())
 9837                        .collect::<SmallVec<[usize; 4]>>();
 9838
 9839                    let mut all_selection_lines_are_comments = true;
 9840
 9841                    for row in start_row.0..=end_row.0 {
 9842                        let row = MultiBufferRow(row);
 9843                        if start_row < end_row && snapshot.is_line_blank(row) {
 9844                            continue;
 9845                        }
 9846
 9847                        let prefix_range = full_comment_prefixes
 9848                            .iter()
 9849                            .zip(prefix_trimmed_lengths.iter().copied())
 9850                            .map(|(prefix, trimmed_prefix_len)| {
 9851                                comment_prefix_range(
 9852                                    snapshot.deref(),
 9853                                    row,
 9854                                    &prefix[..trimmed_prefix_len],
 9855                                    &prefix[trimmed_prefix_len..],
 9856                                    ignore_indent,
 9857                                )
 9858                            })
 9859                            .max_by_key(|range| range.end.column - range.start.column)
 9860                            .expect("prefixes is non-empty");
 9861
 9862                        if prefix_range.is_empty() {
 9863                            all_selection_lines_are_comments = false;
 9864                        }
 9865
 9866                        selection_edit_ranges.push(prefix_range);
 9867                    }
 9868
 9869                    if all_selection_lines_are_comments {
 9870                        edits.extend(
 9871                            selection_edit_ranges
 9872                                .iter()
 9873                                .cloned()
 9874                                .map(|range| (range, empty_str.clone())),
 9875                        );
 9876                    } else {
 9877                        let min_column = selection_edit_ranges
 9878                            .iter()
 9879                            .map(|range| range.start.column)
 9880                            .min()
 9881                            .unwrap_or(0);
 9882                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9883                            let position = Point::new(range.start.row, min_column);
 9884                            (position..position, first_prefix.clone())
 9885                        }));
 9886                    }
 9887                } else if let Some((full_comment_prefix, comment_suffix)) =
 9888                    language.block_comment_delimiters()
 9889                {
 9890                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9891                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9892                    let prefix_range = comment_prefix_range(
 9893                        snapshot.deref(),
 9894                        start_row,
 9895                        comment_prefix,
 9896                        comment_prefix_whitespace,
 9897                        ignore_indent,
 9898                    );
 9899                    let suffix_range = comment_suffix_range(
 9900                        snapshot.deref(),
 9901                        end_row,
 9902                        comment_suffix.trim_start_matches(' '),
 9903                        comment_suffix.starts_with(' '),
 9904                    );
 9905
 9906                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9907                        edits.push((
 9908                            prefix_range.start..prefix_range.start,
 9909                            full_comment_prefix.clone(),
 9910                        ));
 9911                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9912                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9913                    } else {
 9914                        edits.push((prefix_range, empty_str.clone()));
 9915                        edits.push((suffix_range, empty_str.clone()));
 9916                    }
 9917                } else {
 9918                    continue;
 9919                }
 9920            }
 9921
 9922            drop(snapshot);
 9923            this.buffer.update(cx, |buffer, cx| {
 9924                buffer.edit(edits, None, cx);
 9925            });
 9926
 9927            // Adjust selections so that they end before any comment suffixes that
 9928            // were inserted.
 9929            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9930            let mut selections = this.selections.all::<Point>(cx);
 9931            let snapshot = this.buffer.read(cx).read(cx);
 9932            for selection in &mut selections {
 9933                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9934                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9935                        Ordering::Less => {
 9936                            suffixes_inserted.next();
 9937                            continue;
 9938                        }
 9939                        Ordering::Greater => break,
 9940                        Ordering::Equal => {
 9941                            if selection.end.column == snapshot.line_len(row) {
 9942                                if selection.is_empty() {
 9943                                    selection.start.column -= suffix_len as u32;
 9944                                }
 9945                                selection.end.column -= suffix_len as u32;
 9946                            }
 9947                            break;
 9948                        }
 9949                    }
 9950                }
 9951            }
 9952
 9953            drop(snapshot);
 9954            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9955                s.select(selections)
 9956            });
 9957
 9958            let selections = this.selections.all::<Point>(cx);
 9959            let selections_on_single_row = selections.windows(2).all(|selections| {
 9960                selections[0].start.row == selections[1].start.row
 9961                    && selections[0].end.row == selections[1].end.row
 9962                    && selections[0].start.row == selections[0].end.row
 9963            });
 9964            let selections_selecting = selections
 9965                .iter()
 9966                .any(|selection| selection.start != selection.end);
 9967            let advance_downwards = action.advance_downwards
 9968                && selections_on_single_row
 9969                && !selections_selecting
 9970                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9971
 9972            if advance_downwards {
 9973                let snapshot = this.buffer.read(cx).snapshot(cx);
 9974
 9975                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9976                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9977                        let mut point = display_point.to_point(display_snapshot);
 9978                        point.row += 1;
 9979                        point = snapshot.clip_point(point, Bias::Left);
 9980                        let display_point = point.to_display_point(display_snapshot);
 9981                        let goal = SelectionGoal::HorizontalPosition(
 9982                            display_snapshot
 9983                                .x_for_display_point(display_point, text_layout_details)
 9984                                .into(),
 9985                        );
 9986                        (display_point, goal)
 9987                    })
 9988                });
 9989            }
 9990        });
 9991    }
 9992
 9993    pub fn select_enclosing_symbol(
 9994        &mut self,
 9995        _: &SelectEnclosingSymbol,
 9996        window: &mut Window,
 9997        cx: &mut Context<Self>,
 9998    ) {
 9999        let buffer = self.buffer.read(cx).snapshot(cx);
10000        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10001
10002        fn update_selection(
10003            selection: &Selection<usize>,
10004            buffer_snap: &MultiBufferSnapshot,
10005        ) -> Option<Selection<usize>> {
10006            let cursor = selection.head();
10007            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10008            for symbol in symbols.iter().rev() {
10009                let start = symbol.range.start.to_offset(buffer_snap);
10010                let end = symbol.range.end.to_offset(buffer_snap);
10011                let new_range = start..end;
10012                if start < selection.start || end > selection.end {
10013                    return Some(Selection {
10014                        id: selection.id,
10015                        start: new_range.start,
10016                        end: new_range.end,
10017                        goal: SelectionGoal::None,
10018                        reversed: selection.reversed,
10019                    });
10020                }
10021            }
10022            None
10023        }
10024
10025        let mut selected_larger_symbol = false;
10026        let new_selections = old_selections
10027            .iter()
10028            .map(|selection| match update_selection(selection, &buffer) {
10029                Some(new_selection) => {
10030                    if new_selection.range() != selection.range() {
10031                        selected_larger_symbol = true;
10032                    }
10033                    new_selection
10034                }
10035                None => selection.clone(),
10036            })
10037            .collect::<Vec<_>>();
10038
10039        if selected_larger_symbol {
10040            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10041                s.select(new_selections);
10042            });
10043        }
10044    }
10045
10046    pub fn select_larger_syntax_node(
10047        &mut self,
10048        _: &SelectLargerSyntaxNode,
10049        window: &mut Window,
10050        cx: &mut Context<Self>,
10051    ) {
10052        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10053        let buffer = self.buffer.read(cx).snapshot(cx);
10054        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10055
10056        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10057        let mut selected_larger_node = false;
10058        let new_selections = old_selections
10059            .iter()
10060            .map(|selection| {
10061                let old_range = selection.start..selection.end;
10062                let mut new_range = old_range.clone();
10063                let mut new_node = None;
10064                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10065                {
10066                    new_node = Some(node);
10067                    new_range = containing_range;
10068                    if !display_map.intersects_fold(new_range.start)
10069                        && !display_map.intersects_fold(new_range.end)
10070                    {
10071                        break;
10072                    }
10073                }
10074
10075                if let Some(node) = new_node {
10076                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10077                    // nodes. Parent and grandparent are also logged because this operation will not
10078                    // visit nodes that have the same range as their parent.
10079                    log::info!("Node: {node:?}");
10080                    let parent = node.parent();
10081                    log::info!("Parent: {parent:?}");
10082                    let grandparent = parent.and_then(|x| x.parent());
10083                    log::info!("Grandparent: {grandparent:?}");
10084                }
10085
10086                selected_larger_node |= new_range != old_range;
10087                Selection {
10088                    id: selection.id,
10089                    start: new_range.start,
10090                    end: new_range.end,
10091                    goal: SelectionGoal::None,
10092                    reversed: selection.reversed,
10093                }
10094            })
10095            .collect::<Vec<_>>();
10096
10097        if selected_larger_node {
10098            stack.push(old_selections);
10099            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10100                s.select(new_selections);
10101            });
10102        }
10103        self.select_larger_syntax_node_stack = stack;
10104    }
10105
10106    pub fn select_smaller_syntax_node(
10107        &mut self,
10108        _: &SelectSmallerSyntaxNode,
10109        window: &mut Window,
10110        cx: &mut Context<Self>,
10111    ) {
10112        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10113        if let Some(selections) = stack.pop() {
10114            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10115                s.select(selections.to_vec());
10116            });
10117        }
10118        self.select_larger_syntax_node_stack = stack;
10119    }
10120
10121    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10122        if !EditorSettings::get_global(cx).gutter.runnables {
10123            self.clear_tasks();
10124            return Task::ready(());
10125        }
10126        let project = self.project.as_ref().map(Entity::downgrade);
10127        cx.spawn_in(window, |this, mut cx| async move {
10128            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10129            let Some(project) = project.and_then(|p| p.upgrade()) else {
10130                return;
10131            };
10132            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10133                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10134            }) else {
10135                return;
10136            };
10137
10138            let hide_runnables = project
10139                .update(&mut cx, |project, cx| {
10140                    // Do not display any test indicators in non-dev server remote projects.
10141                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10142                })
10143                .unwrap_or(true);
10144            if hide_runnables {
10145                return;
10146            }
10147            let new_rows =
10148                cx.background_spawn({
10149                    let snapshot = display_snapshot.clone();
10150                    async move {
10151                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10152                    }
10153                })
10154                    .await;
10155
10156            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10157            this.update(&mut cx, |this, _| {
10158                this.clear_tasks();
10159                for (key, value) in rows {
10160                    this.insert_tasks(key, value);
10161                }
10162            })
10163            .ok();
10164        })
10165    }
10166    fn fetch_runnable_ranges(
10167        snapshot: &DisplaySnapshot,
10168        range: Range<Anchor>,
10169    ) -> Vec<language::RunnableRange> {
10170        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10171    }
10172
10173    fn runnable_rows(
10174        project: Entity<Project>,
10175        snapshot: DisplaySnapshot,
10176        runnable_ranges: Vec<RunnableRange>,
10177        mut cx: AsyncWindowContext,
10178    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10179        runnable_ranges
10180            .into_iter()
10181            .filter_map(|mut runnable| {
10182                let tasks = cx
10183                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10184                    .ok()?;
10185                if tasks.is_empty() {
10186                    return None;
10187                }
10188
10189                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10190
10191                let row = snapshot
10192                    .buffer_snapshot
10193                    .buffer_line_for_row(MultiBufferRow(point.row))?
10194                    .1
10195                    .start
10196                    .row;
10197
10198                let context_range =
10199                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10200                Some((
10201                    (runnable.buffer_id, row),
10202                    RunnableTasks {
10203                        templates: tasks,
10204                        offset: MultiBufferOffset(runnable.run_range.start),
10205                        context_range,
10206                        column: point.column,
10207                        extra_variables: runnable.extra_captures,
10208                    },
10209                ))
10210            })
10211            .collect()
10212    }
10213
10214    fn templates_with_tags(
10215        project: &Entity<Project>,
10216        runnable: &mut Runnable,
10217        cx: &mut App,
10218    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10219        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10220            let (worktree_id, file) = project
10221                .buffer_for_id(runnable.buffer, cx)
10222                .and_then(|buffer| buffer.read(cx).file())
10223                .map(|file| (file.worktree_id(cx), file.clone()))
10224                .unzip();
10225
10226            (
10227                project.task_store().read(cx).task_inventory().cloned(),
10228                worktree_id,
10229                file,
10230            )
10231        });
10232
10233        let tags = mem::take(&mut runnable.tags);
10234        let mut tags: Vec<_> = tags
10235            .into_iter()
10236            .flat_map(|tag| {
10237                let tag = tag.0.clone();
10238                inventory
10239                    .as_ref()
10240                    .into_iter()
10241                    .flat_map(|inventory| {
10242                        inventory.read(cx).list_tasks(
10243                            file.clone(),
10244                            Some(runnable.language.clone()),
10245                            worktree_id,
10246                            cx,
10247                        )
10248                    })
10249                    .filter(move |(_, template)| {
10250                        template.tags.iter().any(|source_tag| source_tag == &tag)
10251                    })
10252            })
10253            .sorted_by_key(|(kind, _)| kind.to_owned())
10254            .collect();
10255        if let Some((leading_tag_source, _)) = tags.first() {
10256            // Strongest source wins; if we have worktree tag binding, prefer that to
10257            // global and language bindings;
10258            // if we have a global binding, prefer that to language binding.
10259            let first_mismatch = tags
10260                .iter()
10261                .position(|(tag_source, _)| tag_source != leading_tag_source);
10262            if let Some(index) = first_mismatch {
10263                tags.truncate(index);
10264            }
10265        }
10266
10267        tags
10268    }
10269
10270    pub fn move_to_enclosing_bracket(
10271        &mut self,
10272        _: &MoveToEnclosingBracket,
10273        window: &mut Window,
10274        cx: &mut Context<Self>,
10275    ) {
10276        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10277            s.move_offsets_with(|snapshot, selection| {
10278                let Some(enclosing_bracket_ranges) =
10279                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10280                else {
10281                    return;
10282                };
10283
10284                let mut best_length = usize::MAX;
10285                let mut best_inside = false;
10286                let mut best_in_bracket_range = false;
10287                let mut best_destination = None;
10288                for (open, close) in enclosing_bracket_ranges {
10289                    let close = close.to_inclusive();
10290                    let length = close.end() - open.start;
10291                    let inside = selection.start >= open.end && selection.end <= *close.start();
10292                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10293                        || close.contains(&selection.head());
10294
10295                    // If best is next to a bracket and current isn't, skip
10296                    if !in_bracket_range && best_in_bracket_range {
10297                        continue;
10298                    }
10299
10300                    // Prefer smaller lengths unless best is inside and current isn't
10301                    if length > best_length && (best_inside || !inside) {
10302                        continue;
10303                    }
10304
10305                    best_length = length;
10306                    best_inside = inside;
10307                    best_in_bracket_range = in_bracket_range;
10308                    best_destination = Some(
10309                        if close.contains(&selection.start) && close.contains(&selection.end) {
10310                            if inside {
10311                                open.end
10312                            } else {
10313                                open.start
10314                            }
10315                        } else if inside {
10316                            *close.start()
10317                        } else {
10318                            *close.end()
10319                        },
10320                    );
10321                }
10322
10323                if let Some(destination) = best_destination {
10324                    selection.collapse_to(destination, SelectionGoal::None);
10325                }
10326            })
10327        });
10328    }
10329
10330    pub fn undo_selection(
10331        &mut self,
10332        _: &UndoSelection,
10333        window: &mut Window,
10334        cx: &mut Context<Self>,
10335    ) {
10336        self.end_selection(window, cx);
10337        self.selection_history.mode = SelectionHistoryMode::Undoing;
10338        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10339            self.change_selections(None, window, cx, |s| {
10340                s.select_anchors(entry.selections.to_vec())
10341            });
10342            self.select_next_state = entry.select_next_state;
10343            self.select_prev_state = entry.select_prev_state;
10344            self.add_selections_state = entry.add_selections_state;
10345            self.request_autoscroll(Autoscroll::newest(), cx);
10346        }
10347        self.selection_history.mode = SelectionHistoryMode::Normal;
10348    }
10349
10350    pub fn redo_selection(
10351        &mut self,
10352        _: &RedoSelection,
10353        window: &mut Window,
10354        cx: &mut Context<Self>,
10355    ) {
10356        self.end_selection(window, cx);
10357        self.selection_history.mode = SelectionHistoryMode::Redoing;
10358        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10359            self.change_selections(None, window, cx, |s| {
10360                s.select_anchors(entry.selections.to_vec())
10361            });
10362            self.select_next_state = entry.select_next_state;
10363            self.select_prev_state = entry.select_prev_state;
10364            self.add_selections_state = entry.add_selections_state;
10365            self.request_autoscroll(Autoscroll::newest(), cx);
10366        }
10367        self.selection_history.mode = SelectionHistoryMode::Normal;
10368    }
10369
10370    pub fn expand_excerpts(
10371        &mut self,
10372        action: &ExpandExcerpts,
10373        _: &mut Window,
10374        cx: &mut Context<Self>,
10375    ) {
10376        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10377    }
10378
10379    pub fn expand_excerpts_down(
10380        &mut self,
10381        action: &ExpandExcerptsDown,
10382        _: &mut Window,
10383        cx: &mut Context<Self>,
10384    ) {
10385        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10386    }
10387
10388    pub fn expand_excerpts_up(
10389        &mut self,
10390        action: &ExpandExcerptsUp,
10391        _: &mut Window,
10392        cx: &mut Context<Self>,
10393    ) {
10394        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10395    }
10396
10397    pub fn expand_excerpts_for_direction(
10398        &mut self,
10399        lines: u32,
10400        direction: ExpandExcerptDirection,
10401
10402        cx: &mut Context<Self>,
10403    ) {
10404        let selections = self.selections.disjoint_anchors();
10405
10406        let lines = if lines == 0 {
10407            EditorSettings::get_global(cx).expand_excerpt_lines
10408        } else {
10409            lines
10410        };
10411
10412        self.buffer.update(cx, |buffer, cx| {
10413            let snapshot = buffer.snapshot(cx);
10414            let mut excerpt_ids = selections
10415                .iter()
10416                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10417                .collect::<Vec<_>>();
10418            excerpt_ids.sort();
10419            excerpt_ids.dedup();
10420            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10421        })
10422    }
10423
10424    pub fn expand_excerpt(
10425        &mut self,
10426        excerpt: ExcerptId,
10427        direction: ExpandExcerptDirection,
10428        cx: &mut Context<Self>,
10429    ) {
10430        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10431        self.buffer.update(cx, |buffer, cx| {
10432            buffer.expand_excerpts([excerpt], lines, direction, cx)
10433        })
10434    }
10435
10436    pub fn go_to_singleton_buffer_point(
10437        &mut self,
10438        point: Point,
10439        window: &mut Window,
10440        cx: &mut Context<Self>,
10441    ) {
10442        self.go_to_singleton_buffer_range(point..point, window, cx);
10443    }
10444
10445    pub fn go_to_singleton_buffer_range(
10446        &mut self,
10447        range: Range<Point>,
10448        window: &mut Window,
10449        cx: &mut Context<Self>,
10450    ) {
10451        let multibuffer = self.buffer().read(cx);
10452        let Some(buffer) = multibuffer.as_singleton() else {
10453            return;
10454        };
10455        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10456            return;
10457        };
10458        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10459            return;
10460        };
10461        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10462            s.select_anchor_ranges([start..end])
10463        });
10464    }
10465
10466    fn go_to_diagnostic(
10467        &mut self,
10468        _: &GoToDiagnostic,
10469        window: &mut Window,
10470        cx: &mut Context<Self>,
10471    ) {
10472        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10473    }
10474
10475    fn go_to_prev_diagnostic(
10476        &mut self,
10477        _: &GoToPrevDiagnostic,
10478        window: &mut Window,
10479        cx: &mut Context<Self>,
10480    ) {
10481        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10482    }
10483
10484    pub fn go_to_diagnostic_impl(
10485        &mut self,
10486        direction: Direction,
10487        window: &mut Window,
10488        cx: &mut Context<Self>,
10489    ) {
10490        let buffer = self.buffer.read(cx).snapshot(cx);
10491        let selection = self.selections.newest::<usize>(cx);
10492
10493        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10494        if direction == Direction::Next {
10495            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10496                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10497                    return;
10498                };
10499                self.activate_diagnostics(
10500                    buffer_id,
10501                    popover.local_diagnostic.diagnostic.group_id,
10502                    window,
10503                    cx,
10504                );
10505                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10506                    let primary_range_start = active_diagnostics.primary_range.start;
10507                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10508                        let mut new_selection = s.newest_anchor().clone();
10509                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10510                        s.select_anchors(vec![new_selection.clone()]);
10511                    });
10512                    self.refresh_inline_completion(false, true, window, cx);
10513                }
10514                return;
10515            }
10516        }
10517
10518        let active_group_id = self
10519            .active_diagnostics
10520            .as_ref()
10521            .map(|active_group| active_group.group_id);
10522        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10523            active_diagnostics
10524                .primary_range
10525                .to_offset(&buffer)
10526                .to_inclusive()
10527        });
10528        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10529            if active_primary_range.contains(&selection.head()) {
10530                *active_primary_range.start()
10531            } else {
10532                selection.head()
10533            }
10534        } else {
10535            selection.head()
10536        };
10537
10538        let snapshot = self.snapshot(window, cx);
10539        let primary_diagnostics_before = buffer
10540            .diagnostics_in_range::<usize>(0..search_start)
10541            .filter(|entry| entry.diagnostic.is_primary)
10542            .filter(|entry| entry.range.start != entry.range.end)
10543            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10544            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10545            .collect::<Vec<_>>();
10546        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10547            primary_diagnostics_before
10548                .iter()
10549                .position(|entry| entry.diagnostic.group_id == active_group_id)
10550        });
10551
10552        let primary_diagnostics_after = buffer
10553            .diagnostics_in_range::<usize>(search_start..buffer.len())
10554            .filter(|entry| entry.diagnostic.is_primary)
10555            .filter(|entry| entry.range.start != entry.range.end)
10556            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10557            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10558            .collect::<Vec<_>>();
10559        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10560            primary_diagnostics_after
10561                .iter()
10562                .enumerate()
10563                .rev()
10564                .find_map(|(i, entry)| {
10565                    if entry.diagnostic.group_id == active_group_id {
10566                        Some(i)
10567                    } else {
10568                        None
10569                    }
10570                })
10571        });
10572
10573        let next_primary_diagnostic = match direction {
10574            Direction::Prev => primary_diagnostics_before
10575                .iter()
10576                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10577                .rev()
10578                .next(),
10579            Direction::Next => primary_diagnostics_after
10580                .iter()
10581                .skip(
10582                    last_same_group_diagnostic_after
10583                        .map(|index| index + 1)
10584                        .unwrap_or(0),
10585                )
10586                .next(),
10587        };
10588
10589        // Cycle around to the start of the buffer, potentially moving back to the start of
10590        // the currently active diagnostic.
10591        let cycle_around = || match direction {
10592            Direction::Prev => primary_diagnostics_after
10593                .iter()
10594                .rev()
10595                .chain(primary_diagnostics_before.iter().rev())
10596                .next(),
10597            Direction::Next => primary_diagnostics_before
10598                .iter()
10599                .chain(primary_diagnostics_after.iter())
10600                .next(),
10601        };
10602
10603        if let Some((primary_range, group_id)) = next_primary_diagnostic
10604            .or_else(cycle_around)
10605            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10606        {
10607            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10608                return;
10609            };
10610            self.activate_diagnostics(buffer_id, group_id, window, cx);
10611            if self.active_diagnostics.is_some() {
10612                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10613                    s.select(vec![Selection {
10614                        id: selection.id,
10615                        start: primary_range.start,
10616                        end: primary_range.start,
10617                        reversed: false,
10618                        goal: SelectionGoal::None,
10619                    }]);
10620                });
10621                self.refresh_inline_completion(false, true, window, cx);
10622            }
10623        }
10624    }
10625
10626    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10627        let snapshot = self.snapshot(window, cx);
10628        let selection = self.selections.newest::<Point>(cx);
10629        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10630    }
10631
10632    fn go_to_hunk_after_position(
10633        &mut self,
10634        snapshot: &EditorSnapshot,
10635        position: Point,
10636        window: &mut Window,
10637        cx: &mut Context<Editor>,
10638    ) -> Option<MultiBufferDiffHunk> {
10639        let mut hunk = snapshot
10640            .buffer_snapshot
10641            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10642            .find(|hunk| hunk.row_range.start.0 > position.row);
10643        if hunk.is_none() {
10644            hunk = snapshot
10645                .buffer_snapshot
10646                .diff_hunks_in_range(Point::zero()..position)
10647                .find(|hunk| hunk.row_range.end.0 < position.row)
10648        }
10649        if let Some(hunk) = &hunk {
10650            let destination = Point::new(hunk.row_range.start.0, 0);
10651            self.unfold_ranges(&[destination..destination], false, false, cx);
10652            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10653                s.select_ranges(vec![destination..destination]);
10654            });
10655        }
10656
10657        hunk
10658    }
10659
10660    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10661        let snapshot = self.snapshot(window, cx);
10662        let selection = self.selections.newest::<Point>(cx);
10663        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10664    }
10665
10666    fn go_to_hunk_before_position(
10667        &mut self,
10668        snapshot: &EditorSnapshot,
10669        position: Point,
10670        window: &mut Window,
10671        cx: &mut Context<Editor>,
10672    ) -> Option<MultiBufferDiffHunk> {
10673        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10674        if hunk.is_none() {
10675            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10676        }
10677        if let Some(hunk) = &hunk {
10678            let destination = Point::new(hunk.row_range.start.0, 0);
10679            self.unfold_ranges(&[destination..destination], false, false, cx);
10680            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681                s.select_ranges(vec![destination..destination]);
10682            });
10683        }
10684
10685        hunk
10686    }
10687
10688    pub fn go_to_definition(
10689        &mut self,
10690        _: &GoToDefinition,
10691        window: &mut Window,
10692        cx: &mut Context<Self>,
10693    ) -> Task<Result<Navigated>> {
10694        let definition =
10695            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10696        cx.spawn_in(window, |editor, mut cx| async move {
10697            if definition.await? == Navigated::Yes {
10698                return Ok(Navigated::Yes);
10699            }
10700            match editor.update_in(&mut cx, |editor, window, cx| {
10701                editor.find_all_references(&FindAllReferences, window, cx)
10702            })? {
10703                Some(references) => references.await,
10704                None => Ok(Navigated::No),
10705            }
10706        })
10707    }
10708
10709    pub fn go_to_declaration(
10710        &mut self,
10711        _: &GoToDeclaration,
10712        window: &mut Window,
10713        cx: &mut Context<Self>,
10714    ) -> Task<Result<Navigated>> {
10715        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10716    }
10717
10718    pub fn go_to_declaration_split(
10719        &mut self,
10720        _: &GoToDeclaration,
10721        window: &mut Window,
10722        cx: &mut Context<Self>,
10723    ) -> Task<Result<Navigated>> {
10724        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10725    }
10726
10727    pub fn go_to_implementation(
10728        &mut self,
10729        _: &GoToImplementation,
10730        window: &mut Window,
10731        cx: &mut Context<Self>,
10732    ) -> Task<Result<Navigated>> {
10733        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10734    }
10735
10736    pub fn go_to_implementation_split(
10737        &mut self,
10738        _: &GoToImplementationSplit,
10739        window: &mut Window,
10740        cx: &mut Context<Self>,
10741    ) -> Task<Result<Navigated>> {
10742        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10743    }
10744
10745    pub fn go_to_type_definition(
10746        &mut self,
10747        _: &GoToTypeDefinition,
10748        window: &mut Window,
10749        cx: &mut Context<Self>,
10750    ) -> Task<Result<Navigated>> {
10751        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10752    }
10753
10754    pub fn go_to_definition_split(
10755        &mut self,
10756        _: &GoToDefinitionSplit,
10757        window: &mut Window,
10758        cx: &mut Context<Self>,
10759    ) -> Task<Result<Navigated>> {
10760        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10761    }
10762
10763    pub fn go_to_type_definition_split(
10764        &mut self,
10765        _: &GoToTypeDefinitionSplit,
10766        window: &mut Window,
10767        cx: &mut Context<Self>,
10768    ) -> Task<Result<Navigated>> {
10769        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10770    }
10771
10772    fn go_to_definition_of_kind(
10773        &mut self,
10774        kind: GotoDefinitionKind,
10775        split: bool,
10776        window: &mut Window,
10777        cx: &mut Context<Self>,
10778    ) -> Task<Result<Navigated>> {
10779        let Some(provider) = self.semantics_provider.clone() else {
10780            return Task::ready(Ok(Navigated::No));
10781        };
10782        let head = self.selections.newest::<usize>(cx).head();
10783        let buffer = self.buffer.read(cx);
10784        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10785            text_anchor
10786        } else {
10787            return Task::ready(Ok(Navigated::No));
10788        };
10789
10790        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10791            return Task::ready(Ok(Navigated::No));
10792        };
10793
10794        cx.spawn_in(window, |editor, mut cx| async move {
10795            let definitions = definitions.await?;
10796            let navigated = editor
10797                .update_in(&mut cx, |editor, window, cx| {
10798                    editor.navigate_to_hover_links(
10799                        Some(kind),
10800                        definitions
10801                            .into_iter()
10802                            .filter(|location| {
10803                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10804                            })
10805                            .map(HoverLink::Text)
10806                            .collect::<Vec<_>>(),
10807                        split,
10808                        window,
10809                        cx,
10810                    )
10811                })?
10812                .await?;
10813            anyhow::Ok(navigated)
10814        })
10815    }
10816
10817    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10818        let selection = self.selections.newest_anchor();
10819        let head = selection.head();
10820        let tail = selection.tail();
10821
10822        let Some((buffer, start_position)) =
10823            self.buffer.read(cx).text_anchor_for_position(head, cx)
10824        else {
10825            return;
10826        };
10827
10828        let end_position = if head != tail {
10829            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10830                return;
10831            };
10832            Some(pos)
10833        } else {
10834            None
10835        };
10836
10837        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10838            let url = if let Some(end_pos) = end_position {
10839                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10840            } else {
10841                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10842            };
10843
10844            if let Some(url) = url {
10845                editor.update(&mut cx, |_, cx| {
10846                    cx.open_url(&url);
10847                })
10848            } else {
10849                Ok(())
10850            }
10851        });
10852
10853        url_finder.detach();
10854    }
10855
10856    pub fn open_selected_filename(
10857        &mut self,
10858        _: &OpenSelectedFilename,
10859        window: &mut Window,
10860        cx: &mut Context<Self>,
10861    ) {
10862        let Some(workspace) = self.workspace() else {
10863            return;
10864        };
10865
10866        let position = self.selections.newest_anchor().head();
10867
10868        let Some((buffer, buffer_position)) =
10869            self.buffer.read(cx).text_anchor_for_position(position, cx)
10870        else {
10871            return;
10872        };
10873
10874        let project = self.project.clone();
10875
10876        cx.spawn_in(window, |_, mut cx| async move {
10877            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10878
10879            if let Some((_, path)) = result {
10880                workspace
10881                    .update_in(&mut cx, |workspace, window, cx| {
10882                        workspace.open_resolved_path(path, window, cx)
10883                    })?
10884                    .await?;
10885            }
10886            anyhow::Ok(())
10887        })
10888        .detach();
10889    }
10890
10891    pub(crate) fn navigate_to_hover_links(
10892        &mut self,
10893        kind: Option<GotoDefinitionKind>,
10894        mut definitions: Vec<HoverLink>,
10895        split: bool,
10896        window: &mut Window,
10897        cx: &mut Context<Editor>,
10898    ) -> Task<Result<Navigated>> {
10899        // If there is one definition, just open it directly
10900        if definitions.len() == 1 {
10901            let definition = definitions.pop().unwrap();
10902
10903            enum TargetTaskResult {
10904                Location(Option<Location>),
10905                AlreadyNavigated,
10906            }
10907
10908            let target_task = match definition {
10909                HoverLink::Text(link) => {
10910                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10911                }
10912                HoverLink::InlayHint(lsp_location, server_id) => {
10913                    let computation =
10914                        self.compute_target_location(lsp_location, server_id, window, cx);
10915                    cx.background_spawn(async move {
10916                        let location = computation.await?;
10917                        Ok(TargetTaskResult::Location(location))
10918                    })
10919                }
10920                HoverLink::Url(url) => {
10921                    cx.open_url(&url);
10922                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10923                }
10924                HoverLink::File(path) => {
10925                    if let Some(workspace) = self.workspace() {
10926                        cx.spawn_in(window, |_, mut cx| async move {
10927                            workspace
10928                                .update_in(&mut cx, |workspace, window, cx| {
10929                                    workspace.open_resolved_path(path, window, cx)
10930                                })?
10931                                .await
10932                                .map(|_| TargetTaskResult::AlreadyNavigated)
10933                        })
10934                    } else {
10935                        Task::ready(Ok(TargetTaskResult::Location(None)))
10936                    }
10937                }
10938            };
10939            cx.spawn_in(window, |editor, mut cx| async move {
10940                let target = match target_task.await.context("target resolution task")? {
10941                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10942                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10943                    TargetTaskResult::Location(Some(target)) => target,
10944                };
10945
10946                editor.update_in(&mut cx, |editor, window, cx| {
10947                    let Some(workspace) = editor.workspace() else {
10948                        return Navigated::No;
10949                    };
10950                    let pane = workspace.read(cx).active_pane().clone();
10951
10952                    let range = target.range.to_point(target.buffer.read(cx));
10953                    let range = editor.range_for_match(&range);
10954                    let range = collapse_multiline_range(range);
10955
10956                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10957                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10958                    } else {
10959                        window.defer(cx, move |window, cx| {
10960                            let target_editor: Entity<Self> =
10961                                workspace.update(cx, |workspace, cx| {
10962                                    let pane = if split {
10963                                        workspace.adjacent_pane(window, cx)
10964                                    } else {
10965                                        workspace.active_pane().clone()
10966                                    };
10967
10968                                    workspace.open_project_item(
10969                                        pane,
10970                                        target.buffer.clone(),
10971                                        true,
10972                                        true,
10973                                        window,
10974                                        cx,
10975                                    )
10976                                });
10977                            target_editor.update(cx, |target_editor, cx| {
10978                                // When selecting a definition in a different buffer, disable the nav history
10979                                // to avoid creating a history entry at the previous cursor location.
10980                                pane.update(cx, |pane, _| pane.disable_history());
10981                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10982                                pane.update(cx, |pane, _| pane.enable_history());
10983                            });
10984                        });
10985                    }
10986                    Navigated::Yes
10987                })
10988            })
10989        } else if !definitions.is_empty() {
10990            cx.spawn_in(window, |editor, mut cx| async move {
10991                let (title, location_tasks, workspace) = editor
10992                    .update_in(&mut cx, |editor, window, cx| {
10993                        let tab_kind = match kind {
10994                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10995                            _ => "Definitions",
10996                        };
10997                        let title = definitions
10998                            .iter()
10999                            .find_map(|definition| match definition {
11000                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11001                                    let buffer = origin.buffer.read(cx);
11002                                    format!(
11003                                        "{} for {}",
11004                                        tab_kind,
11005                                        buffer
11006                                            .text_for_range(origin.range.clone())
11007                                            .collect::<String>()
11008                                    )
11009                                }),
11010                                HoverLink::InlayHint(_, _) => None,
11011                                HoverLink::Url(_) => None,
11012                                HoverLink::File(_) => None,
11013                            })
11014                            .unwrap_or(tab_kind.to_string());
11015                        let location_tasks = definitions
11016                            .into_iter()
11017                            .map(|definition| match definition {
11018                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11019                                HoverLink::InlayHint(lsp_location, server_id) => editor
11020                                    .compute_target_location(lsp_location, server_id, window, cx),
11021                                HoverLink::Url(_) => Task::ready(Ok(None)),
11022                                HoverLink::File(_) => Task::ready(Ok(None)),
11023                            })
11024                            .collect::<Vec<_>>();
11025                        (title, location_tasks, editor.workspace().clone())
11026                    })
11027                    .context("location tasks preparation")?;
11028
11029                let locations = future::join_all(location_tasks)
11030                    .await
11031                    .into_iter()
11032                    .filter_map(|location| location.transpose())
11033                    .collect::<Result<_>>()
11034                    .context("location tasks")?;
11035
11036                let Some(workspace) = workspace else {
11037                    return Ok(Navigated::No);
11038                };
11039                let opened = workspace
11040                    .update_in(&mut cx, |workspace, window, cx| {
11041                        Self::open_locations_in_multibuffer(
11042                            workspace,
11043                            locations,
11044                            title,
11045                            split,
11046                            MultibufferSelectionMode::First,
11047                            window,
11048                            cx,
11049                        )
11050                    })
11051                    .ok();
11052
11053                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11054            })
11055        } else {
11056            Task::ready(Ok(Navigated::No))
11057        }
11058    }
11059
11060    fn compute_target_location(
11061        &self,
11062        lsp_location: lsp::Location,
11063        server_id: LanguageServerId,
11064        window: &mut Window,
11065        cx: &mut Context<Self>,
11066    ) -> Task<anyhow::Result<Option<Location>>> {
11067        let Some(project) = self.project.clone() else {
11068            return Task::ready(Ok(None));
11069        };
11070
11071        cx.spawn_in(window, move |editor, mut cx| async move {
11072            let location_task = editor.update(&mut cx, |_, cx| {
11073                project.update(cx, |project, cx| {
11074                    let language_server_name = project
11075                        .language_server_statuses(cx)
11076                        .find(|(id, _)| server_id == *id)
11077                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11078                    language_server_name.map(|language_server_name| {
11079                        project.open_local_buffer_via_lsp(
11080                            lsp_location.uri.clone(),
11081                            server_id,
11082                            language_server_name,
11083                            cx,
11084                        )
11085                    })
11086                })
11087            })?;
11088            let location = match location_task {
11089                Some(task) => Some({
11090                    let target_buffer_handle = task.await.context("open local buffer")?;
11091                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11092                        let target_start = target_buffer
11093                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11094                        let target_end = target_buffer
11095                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11096                        target_buffer.anchor_after(target_start)
11097                            ..target_buffer.anchor_before(target_end)
11098                    })?;
11099                    Location {
11100                        buffer: target_buffer_handle,
11101                        range,
11102                    }
11103                }),
11104                None => None,
11105            };
11106            Ok(location)
11107        })
11108    }
11109
11110    pub fn find_all_references(
11111        &mut self,
11112        _: &FindAllReferences,
11113        window: &mut Window,
11114        cx: &mut Context<Self>,
11115    ) -> Option<Task<Result<Navigated>>> {
11116        let selection = self.selections.newest::<usize>(cx);
11117        let multi_buffer = self.buffer.read(cx);
11118        let head = selection.head();
11119
11120        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11121        let head_anchor = multi_buffer_snapshot.anchor_at(
11122            head,
11123            if head < selection.tail() {
11124                Bias::Right
11125            } else {
11126                Bias::Left
11127            },
11128        );
11129
11130        match self
11131            .find_all_references_task_sources
11132            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11133        {
11134            Ok(_) => {
11135                log::info!(
11136                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11137                );
11138                return None;
11139            }
11140            Err(i) => {
11141                self.find_all_references_task_sources.insert(i, head_anchor);
11142            }
11143        }
11144
11145        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11146        let workspace = self.workspace()?;
11147        let project = workspace.read(cx).project().clone();
11148        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11149        Some(cx.spawn_in(window, |editor, mut cx| async move {
11150            let _cleanup = defer({
11151                let mut cx = cx.clone();
11152                move || {
11153                    let _ = editor.update(&mut cx, |editor, _| {
11154                        if let Ok(i) =
11155                            editor
11156                                .find_all_references_task_sources
11157                                .binary_search_by(|anchor| {
11158                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11159                                })
11160                        {
11161                            editor.find_all_references_task_sources.remove(i);
11162                        }
11163                    });
11164                }
11165            });
11166
11167            let locations = references.await?;
11168            if locations.is_empty() {
11169                return anyhow::Ok(Navigated::No);
11170            }
11171
11172            workspace.update_in(&mut cx, |workspace, window, cx| {
11173                let title = locations
11174                    .first()
11175                    .as_ref()
11176                    .map(|location| {
11177                        let buffer = location.buffer.read(cx);
11178                        format!(
11179                            "References to `{}`",
11180                            buffer
11181                                .text_for_range(location.range.clone())
11182                                .collect::<String>()
11183                        )
11184                    })
11185                    .unwrap();
11186                Self::open_locations_in_multibuffer(
11187                    workspace,
11188                    locations,
11189                    title,
11190                    false,
11191                    MultibufferSelectionMode::First,
11192                    window,
11193                    cx,
11194                );
11195                Navigated::Yes
11196            })
11197        }))
11198    }
11199
11200    /// Opens a multibuffer with the given project locations in it
11201    pub fn open_locations_in_multibuffer(
11202        workspace: &mut Workspace,
11203        mut locations: Vec<Location>,
11204        title: String,
11205        split: bool,
11206        multibuffer_selection_mode: MultibufferSelectionMode,
11207        window: &mut Window,
11208        cx: &mut Context<Workspace>,
11209    ) {
11210        // If there are multiple definitions, open them in a multibuffer
11211        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11212        let mut locations = locations.into_iter().peekable();
11213        let mut ranges = Vec::new();
11214        let capability = workspace.project().read(cx).capability();
11215
11216        let excerpt_buffer = cx.new(|cx| {
11217            let mut multibuffer = MultiBuffer::new(capability);
11218            while let Some(location) = locations.next() {
11219                let buffer = location.buffer.read(cx);
11220                let mut ranges_for_buffer = Vec::new();
11221                let range = location.range.to_offset(buffer);
11222                ranges_for_buffer.push(range.clone());
11223
11224                while let Some(next_location) = locations.peek() {
11225                    if next_location.buffer == location.buffer {
11226                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11227                        locations.next();
11228                    } else {
11229                        break;
11230                    }
11231                }
11232
11233                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11234                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11235                    location.buffer.clone(),
11236                    ranges_for_buffer,
11237                    DEFAULT_MULTIBUFFER_CONTEXT,
11238                    cx,
11239                ))
11240            }
11241
11242            multibuffer.with_title(title)
11243        });
11244
11245        let editor = cx.new(|cx| {
11246            Editor::for_multibuffer(
11247                excerpt_buffer,
11248                Some(workspace.project().clone()),
11249                true,
11250                window,
11251                cx,
11252            )
11253        });
11254        editor.update(cx, |editor, cx| {
11255            match multibuffer_selection_mode {
11256                MultibufferSelectionMode::First => {
11257                    if let Some(first_range) = ranges.first() {
11258                        editor.change_selections(None, window, cx, |selections| {
11259                            selections.clear_disjoint();
11260                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11261                        });
11262                    }
11263                    editor.highlight_background::<Self>(
11264                        &ranges,
11265                        |theme| theme.editor_highlighted_line_background,
11266                        cx,
11267                    );
11268                }
11269                MultibufferSelectionMode::All => {
11270                    editor.change_selections(None, window, cx, |selections| {
11271                        selections.clear_disjoint();
11272                        selections.select_anchor_ranges(ranges);
11273                    });
11274                }
11275            }
11276            editor.register_buffers_with_language_servers(cx);
11277        });
11278
11279        let item = Box::new(editor);
11280        let item_id = item.item_id();
11281
11282        if split {
11283            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11284        } else {
11285            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11286                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11287                    pane.close_current_preview_item(window, cx)
11288                } else {
11289                    None
11290                }
11291            });
11292            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11293        }
11294        workspace.active_pane().update(cx, |pane, cx| {
11295            pane.set_preview_item_id(Some(item_id), cx);
11296        });
11297    }
11298
11299    pub fn rename(
11300        &mut self,
11301        _: &Rename,
11302        window: &mut Window,
11303        cx: &mut Context<Self>,
11304    ) -> Option<Task<Result<()>>> {
11305        use language::ToOffset as _;
11306
11307        let provider = self.semantics_provider.clone()?;
11308        let selection = self.selections.newest_anchor().clone();
11309        let (cursor_buffer, cursor_buffer_position) = self
11310            .buffer
11311            .read(cx)
11312            .text_anchor_for_position(selection.head(), cx)?;
11313        let (tail_buffer, cursor_buffer_position_end) = self
11314            .buffer
11315            .read(cx)
11316            .text_anchor_for_position(selection.tail(), cx)?;
11317        if tail_buffer != cursor_buffer {
11318            return None;
11319        }
11320
11321        let snapshot = cursor_buffer.read(cx).snapshot();
11322        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11323        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11324        let prepare_rename = provider
11325            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11326            .unwrap_or_else(|| Task::ready(Ok(None)));
11327        drop(snapshot);
11328
11329        Some(cx.spawn_in(window, |this, mut cx| async move {
11330            let rename_range = if let Some(range) = prepare_rename.await? {
11331                Some(range)
11332            } else {
11333                this.update(&mut cx, |this, cx| {
11334                    let buffer = this.buffer.read(cx).snapshot(cx);
11335                    let mut buffer_highlights = this
11336                        .document_highlights_for_position(selection.head(), &buffer)
11337                        .filter(|highlight| {
11338                            highlight.start.excerpt_id == selection.head().excerpt_id
11339                                && highlight.end.excerpt_id == selection.head().excerpt_id
11340                        });
11341                    buffer_highlights
11342                        .next()
11343                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11344                })?
11345            };
11346            if let Some(rename_range) = rename_range {
11347                this.update_in(&mut cx, |this, window, cx| {
11348                    let snapshot = cursor_buffer.read(cx).snapshot();
11349                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11350                    let cursor_offset_in_rename_range =
11351                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11352                    let cursor_offset_in_rename_range_end =
11353                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11354
11355                    this.take_rename(false, window, cx);
11356                    let buffer = this.buffer.read(cx).read(cx);
11357                    let cursor_offset = selection.head().to_offset(&buffer);
11358                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11359                    let rename_end = rename_start + rename_buffer_range.len();
11360                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11361                    let mut old_highlight_id = None;
11362                    let old_name: Arc<str> = buffer
11363                        .chunks(rename_start..rename_end, true)
11364                        .map(|chunk| {
11365                            if old_highlight_id.is_none() {
11366                                old_highlight_id = chunk.syntax_highlight_id;
11367                            }
11368                            chunk.text
11369                        })
11370                        .collect::<String>()
11371                        .into();
11372
11373                    drop(buffer);
11374
11375                    // Position the selection in the rename editor so that it matches the current selection.
11376                    this.show_local_selections = false;
11377                    let rename_editor = cx.new(|cx| {
11378                        let mut editor = Editor::single_line(window, cx);
11379                        editor.buffer.update(cx, |buffer, cx| {
11380                            buffer.edit([(0..0, old_name.clone())], None, cx)
11381                        });
11382                        let rename_selection_range = match cursor_offset_in_rename_range
11383                            .cmp(&cursor_offset_in_rename_range_end)
11384                        {
11385                            Ordering::Equal => {
11386                                editor.select_all(&SelectAll, window, cx);
11387                                return editor;
11388                            }
11389                            Ordering::Less => {
11390                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11391                            }
11392                            Ordering::Greater => {
11393                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11394                            }
11395                        };
11396                        if rename_selection_range.end > old_name.len() {
11397                            editor.select_all(&SelectAll, window, cx);
11398                        } else {
11399                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11400                                s.select_ranges([rename_selection_range]);
11401                            });
11402                        }
11403                        editor
11404                    });
11405                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11406                        if e == &EditorEvent::Focused {
11407                            cx.emit(EditorEvent::FocusedIn)
11408                        }
11409                    })
11410                    .detach();
11411
11412                    let write_highlights =
11413                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11414                    let read_highlights =
11415                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11416                    let ranges = write_highlights
11417                        .iter()
11418                        .flat_map(|(_, ranges)| ranges.iter())
11419                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11420                        .cloned()
11421                        .collect();
11422
11423                    this.highlight_text::<Rename>(
11424                        ranges,
11425                        HighlightStyle {
11426                            fade_out: Some(0.6),
11427                            ..Default::default()
11428                        },
11429                        cx,
11430                    );
11431                    let rename_focus_handle = rename_editor.focus_handle(cx);
11432                    window.focus(&rename_focus_handle);
11433                    let block_id = this.insert_blocks(
11434                        [BlockProperties {
11435                            style: BlockStyle::Flex,
11436                            placement: BlockPlacement::Below(range.start),
11437                            height: 1,
11438                            render: Arc::new({
11439                                let rename_editor = rename_editor.clone();
11440                                move |cx: &mut BlockContext| {
11441                                    let mut text_style = cx.editor_style.text.clone();
11442                                    if let Some(highlight_style) = old_highlight_id
11443                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11444                                    {
11445                                        text_style = text_style.highlight(highlight_style);
11446                                    }
11447                                    div()
11448                                        .block_mouse_down()
11449                                        .pl(cx.anchor_x)
11450                                        .child(EditorElement::new(
11451                                            &rename_editor,
11452                                            EditorStyle {
11453                                                background: cx.theme().system().transparent,
11454                                                local_player: cx.editor_style.local_player,
11455                                                text: text_style,
11456                                                scrollbar_width: cx.editor_style.scrollbar_width,
11457                                                syntax: cx.editor_style.syntax.clone(),
11458                                                status: cx.editor_style.status.clone(),
11459                                                inlay_hints_style: HighlightStyle {
11460                                                    font_weight: Some(FontWeight::BOLD),
11461                                                    ..make_inlay_hints_style(cx.app)
11462                                                },
11463                                                inline_completion_styles: make_suggestion_styles(
11464                                                    cx.app,
11465                                                ),
11466                                                ..EditorStyle::default()
11467                                            },
11468                                        ))
11469                                        .into_any_element()
11470                                }
11471                            }),
11472                            priority: 0,
11473                        }],
11474                        Some(Autoscroll::fit()),
11475                        cx,
11476                    )[0];
11477                    this.pending_rename = Some(RenameState {
11478                        range,
11479                        old_name,
11480                        editor: rename_editor,
11481                        block_id,
11482                    });
11483                })?;
11484            }
11485
11486            Ok(())
11487        }))
11488    }
11489
11490    pub fn confirm_rename(
11491        &mut self,
11492        _: &ConfirmRename,
11493        window: &mut Window,
11494        cx: &mut Context<Self>,
11495    ) -> Option<Task<Result<()>>> {
11496        let rename = self.take_rename(false, window, cx)?;
11497        let workspace = self.workspace()?.downgrade();
11498        let (buffer, start) = self
11499            .buffer
11500            .read(cx)
11501            .text_anchor_for_position(rename.range.start, cx)?;
11502        let (end_buffer, _) = self
11503            .buffer
11504            .read(cx)
11505            .text_anchor_for_position(rename.range.end, cx)?;
11506        if buffer != end_buffer {
11507            return None;
11508        }
11509
11510        let old_name = rename.old_name;
11511        let new_name = rename.editor.read(cx).text(cx);
11512
11513        let rename = self.semantics_provider.as_ref()?.perform_rename(
11514            &buffer,
11515            start,
11516            new_name.clone(),
11517            cx,
11518        )?;
11519
11520        Some(cx.spawn_in(window, |editor, mut cx| async move {
11521            let project_transaction = rename.await?;
11522            Self::open_project_transaction(
11523                &editor,
11524                workspace,
11525                project_transaction,
11526                format!("Rename: {}{}", old_name, new_name),
11527                cx.clone(),
11528            )
11529            .await?;
11530
11531            editor.update(&mut cx, |editor, cx| {
11532                editor.refresh_document_highlights(cx);
11533            })?;
11534            Ok(())
11535        }))
11536    }
11537
11538    fn take_rename(
11539        &mut self,
11540        moving_cursor: bool,
11541        window: &mut Window,
11542        cx: &mut Context<Self>,
11543    ) -> Option<RenameState> {
11544        let rename = self.pending_rename.take()?;
11545        if rename.editor.focus_handle(cx).is_focused(window) {
11546            window.focus(&self.focus_handle);
11547        }
11548
11549        self.remove_blocks(
11550            [rename.block_id].into_iter().collect(),
11551            Some(Autoscroll::fit()),
11552            cx,
11553        );
11554        self.clear_highlights::<Rename>(cx);
11555        self.show_local_selections = true;
11556
11557        if moving_cursor {
11558            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11559                editor.selections.newest::<usize>(cx).head()
11560            });
11561
11562            // Update the selection to match the position of the selection inside
11563            // the rename editor.
11564            let snapshot = self.buffer.read(cx).read(cx);
11565            let rename_range = rename.range.to_offset(&snapshot);
11566            let cursor_in_editor = snapshot
11567                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11568                .min(rename_range.end);
11569            drop(snapshot);
11570
11571            self.change_selections(None, window, cx, |s| {
11572                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11573            });
11574        } else {
11575            self.refresh_document_highlights(cx);
11576        }
11577
11578        Some(rename)
11579    }
11580
11581    pub fn pending_rename(&self) -> Option<&RenameState> {
11582        self.pending_rename.as_ref()
11583    }
11584
11585    fn format(
11586        &mut self,
11587        _: &Format,
11588        window: &mut Window,
11589        cx: &mut Context<Self>,
11590    ) -> Option<Task<Result<()>>> {
11591        let project = match &self.project {
11592            Some(project) => project.clone(),
11593            None => return None,
11594        };
11595
11596        Some(self.perform_format(
11597            project,
11598            FormatTrigger::Manual,
11599            FormatTarget::Buffers,
11600            window,
11601            cx,
11602        ))
11603    }
11604
11605    fn format_selections(
11606        &mut self,
11607        _: &FormatSelections,
11608        window: &mut Window,
11609        cx: &mut Context<Self>,
11610    ) -> Option<Task<Result<()>>> {
11611        let project = match &self.project {
11612            Some(project) => project.clone(),
11613            None => return None,
11614        };
11615
11616        let ranges = self
11617            .selections
11618            .all_adjusted(cx)
11619            .into_iter()
11620            .map(|selection| selection.range())
11621            .collect_vec();
11622
11623        Some(self.perform_format(
11624            project,
11625            FormatTrigger::Manual,
11626            FormatTarget::Ranges(ranges),
11627            window,
11628            cx,
11629        ))
11630    }
11631
11632    fn perform_format(
11633        &mut self,
11634        project: Entity<Project>,
11635        trigger: FormatTrigger,
11636        target: FormatTarget,
11637        window: &mut Window,
11638        cx: &mut Context<Self>,
11639    ) -> Task<Result<()>> {
11640        let buffer = self.buffer.clone();
11641        let (buffers, target) = match target {
11642            FormatTarget::Buffers => {
11643                let mut buffers = buffer.read(cx).all_buffers();
11644                if trigger == FormatTrigger::Save {
11645                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11646                }
11647                (buffers, LspFormatTarget::Buffers)
11648            }
11649            FormatTarget::Ranges(selection_ranges) => {
11650                let multi_buffer = buffer.read(cx);
11651                let snapshot = multi_buffer.read(cx);
11652                let mut buffers = HashSet::default();
11653                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11654                    BTreeMap::new();
11655                for selection_range in selection_ranges {
11656                    for (buffer, buffer_range, _) in
11657                        snapshot.range_to_buffer_ranges(selection_range)
11658                    {
11659                        let buffer_id = buffer.remote_id();
11660                        let start = buffer.anchor_before(buffer_range.start);
11661                        let end = buffer.anchor_after(buffer_range.end);
11662                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11663                        buffer_id_to_ranges
11664                            .entry(buffer_id)
11665                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11666                            .or_insert_with(|| vec![start..end]);
11667                    }
11668                }
11669                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11670            }
11671        };
11672
11673        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11674        let format = project.update(cx, |project, cx| {
11675            project.format(buffers, target, true, trigger, cx)
11676        });
11677
11678        cx.spawn_in(window, |_, mut cx| async move {
11679            let transaction = futures::select_biased! {
11680                () = timeout => {
11681                    log::warn!("timed out waiting for formatting");
11682                    None
11683                }
11684                transaction = format.log_err().fuse() => transaction,
11685            };
11686
11687            buffer
11688                .update(&mut cx, |buffer, cx| {
11689                    if let Some(transaction) = transaction {
11690                        if !buffer.is_singleton() {
11691                            buffer.push_transaction(&transaction.0, cx);
11692                        }
11693                    }
11694
11695                    cx.notify();
11696                })
11697                .ok();
11698
11699            Ok(())
11700        })
11701    }
11702
11703    fn restart_language_server(
11704        &mut self,
11705        _: &RestartLanguageServer,
11706        _: &mut Window,
11707        cx: &mut Context<Self>,
11708    ) {
11709        if let Some(project) = self.project.clone() {
11710            self.buffer.update(cx, |multi_buffer, cx| {
11711                project.update(cx, |project, cx| {
11712                    project.restart_language_servers_for_buffers(
11713                        multi_buffer.all_buffers().into_iter().collect(),
11714                        cx,
11715                    );
11716                });
11717            })
11718        }
11719    }
11720
11721    fn cancel_language_server_work(
11722        workspace: &mut Workspace,
11723        _: &actions::CancelLanguageServerWork,
11724        _: &mut Window,
11725        cx: &mut Context<Workspace>,
11726    ) {
11727        let project = workspace.project();
11728        let buffers = workspace
11729            .active_item(cx)
11730            .and_then(|item| item.act_as::<Editor>(cx))
11731            .map_or(HashSet::default(), |editor| {
11732                editor.read(cx).buffer.read(cx).all_buffers()
11733            });
11734        project.update(cx, |project, cx| {
11735            project.cancel_language_server_work_for_buffers(buffers, cx);
11736        });
11737    }
11738
11739    fn show_character_palette(
11740        &mut self,
11741        _: &ShowCharacterPalette,
11742        window: &mut Window,
11743        _: &mut Context<Self>,
11744    ) {
11745        window.show_character_palette();
11746    }
11747
11748    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11749        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11750            let buffer = self.buffer.read(cx).snapshot(cx);
11751            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11752            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11753            let is_valid = buffer
11754                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11755                .any(|entry| {
11756                    entry.diagnostic.is_primary
11757                        && !entry.range.is_empty()
11758                        && entry.range.start == primary_range_start
11759                        && entry.diagnostic.message == active_diagnostics.primary_message
11760                });
11761
11762            if is_valid != active_diagnostics.is_valid {
11763                active_diagnostics.is_valid = is_valid;
11764                let mut new_styles = HashMap::default();
11765                for (block_id, diagnostic) in &active_diagnostics.blocks {
11766                    new_styles.insert(
11767                        *block_id,
11768                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11769                    );
11770                }
11771                self.display_map.update(cx, |display_map, _cx| {
11772                    display_map.replace_blocks(new_styles)
11773                });
11774            }
11775        }
11776    }
11777
11778    fn activate_diagnostics(
11779        &mut self,
11780        buffer_id: BufferId,
11781        group_id: usize,
11782        window: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        self.dismiss_diagnostics(cx);
11786        let snapshot = self.snapshot(window, cx);
11787        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11788            let buffer = self.buffer.read(cx).snapshot(cx);
11789
11790            let mut primary_range = None;
11791            let mut primary_message = None;
11792            let diagnostic_group = buffer
11793                .diagnostic_group(buffer_id, group_id)
11794                .filter_map(|entry| {
11795                    let start = entry.range.start;
11796                    let end = entry.range.end;
11797                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11798                        && (start.row == end.row
11799                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11800                    {
11801                        return None;
11802                    }
11803                    if entry.diagnostic.is_primary {
11804                        primary_range = Some(entry.range.clone());
11805                        primary_message = Some(entry.diagnostic.message.clone());
11806                    }
11807                    Some(entry)
11808                })
11809                .collect::<Vec<_>>();
11810            let primary_range = primary_range?;
11811            let primary_message = primary_message?;
11812
11813            let blocks = display_map
11814                .insert_blocks(
11815                    diagnostic_group.iter().map(|entry| {
11816                        let diagnostic = entry.diagnostic.clone();
11817                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11818                        BlockProperties {
11819                            style: BlockStyle::Fixed,
11820                            placement: BlockPlacement::Below(
11821                                buffer.anchor_after(entry.range.start),
11822                            ),
11823                            height: message_height,
11824                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11825                            priority: 0,
11826                        }
11827                    }),
11828                    cx,
11829                )
11830                .into_iter()
11831                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11832                .collect();
11833
11834            Some(ActiveDiagnosticGroup {
11835                primary_range: buffer.anchor_before(primary_range.start)
11836                    ..buffer.anchor_after(primary_range.end),
11837                primary_message,
11838                group_id,
11839                blocks,
11840                is_valid: true,
11841            })
11842        });
11843    }
11844
11845    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11846        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11847            self.display_map.update(cx, |display_map, cx| {
11848                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11849            });
11850            cx.notify();
11851        }
11852    }
11853
11854    pub fn set_selections_from_remote(
11855        &mut self,
11856        selections: Vec<Selection<Anchor>>,
11857        pending_selection: Option<Selection<Anchor>>,
11858        window: &mut Window,
11859        cx: &mut Context<Self>,
11860    ) {
11861        let old_cursor_position = self.selections.newest_anchor().head();
11862        self.selections.change_with(cx, |s| {
11863            s.select_anchors(selections);
11864            if let Some(pending_selection) = pending_selection {
11865                s.set_pending(pending_selection, SelectMode::Character);
11866            } else {
11867                s.clear_pending();
11868            }
11869        });
11870        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11871    }
11872
11873    fn push_to_selection_history(&mut self) {
11874        self.selection_history.push(SelectionHistoryEntry {
11875            selections: self.selections.disjoint_anchors(),
11876            select_next_state: self.select_next_state.clone(),
11877            select_prev_state: self.select_prev_state.clone(),
11878            add_selections_state: self.add_selections_state.clone(),
11879        });
11880    }
11881
11882    pub fn transact(
11883        &mut self,
11884        window: &mut Window,
11885        cx: &mut Context<Self>,
11886        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11887    ) -> Option<TransactionId> {
11888        self.start_transaction_at(Instant::now(), window, cx);
11889        update(self, window, cx);
11890        self.end_transaction_at(Instant::now(), cx)
11891    }
11892
11893    pub fn start_transaction_at(
11894        &mut self,
11895        now: Instant,
11896        window: &mut Window,
11897        cx: &mut Context<Self>,
11898    ) {
11899        self.end_selection(window, cx);
11900        if let Some(tx_id) = self
11901            .buffer
11902            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11903        {
11904            self.selection_history
11905                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11906            cx.emit(EditorEvent::TransactionBegun {
11907                transaction_id: tx_id,
11908            })
11909        }
11910    }
11911
11912    pub fn end_transaction_at(
11913        &mut self,
11914        now: Instant,
11915        cx: &mut Context<Self>,
11916    ) -> Option<TransactionId> {
11917        if let Some(transaction_id) = self
11918            .buffer
11919            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11920        {
11921            if let Some((_, end_selections)) =
11922                self.selection_history.transaction_mut(transaction_id)
11923            {
11924                *end_selections = Some(self.selections.disjoint_anchors());
11925            } else {
11926                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11927            }
11928
11929            cx.emit(EditorEvent::Edited { transaction_id });
11930            Some(transaction_id)
11931        } else {
11932            None
11933        }
11934    }
11935
11936    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11937        if self.selection_mark_mode {
11938            self.change_selections(None, window, cx, |s| {
11939                s.move_with(|_, sel| {
11940                    sel.collapse_to(sel.head(), SelectionGoal::None);
11941                });
11942            })
11943        }
11944        self.selection_mark_mode = true;
11945        cx.notify();
11946    }
11947
11948    pub fn swap_selection_ends(
11949        &mut self,
11950        _: &actions::SwapSelectionEnds,
11951        window: &mut Window,
11952        cx: &mut Context<Self>,
11953    ) {
11954        self.change_selections(None, window, cx, |s| {
11955            s.move_with(|_, sel| {
11956                if sel.start != sel.end {
11957                    sel.reversed = !sel.reversed
11958                }
11959            });
11960        });
11961        self.request_autoscroll(Autoscroll::newest(), cx);
11962        cx.notify();
11963    }
11964
11965    pub fn toggle_fold(
11966        &mut self,
11967        _: &actions::ToggleFold,
11968        window: &mut Window,
11969        cx: &mut Context<Self>,
11970    ) {
11971        if self.is_singleton(cx) {
11972            let selection = self.selections.newest::<Point>(cx);
11973
11974            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11975            let range = if selection.is_empty() {
11976                let point = selection.head().to_display_point(&display_map);
11977                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11978                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11979                    .to_point(&display_map);
11980                start..end
11981            } else {
11982                selection.range()
11983            };
11984            if display_map.folds_in_range(range).next().is_some() {
11985                self.unfold_lines(&Default::default(), window, cx)
11986            } else {
11987                self.fold(&Default::default(), window, cx)
11988            }
11989        } else {
11990            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11991            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11992                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11993                .map(|(snapshot, _, _)| snapshot.remote_id())
11994                .collect();
11995
11996            for buffer_id in buffer_ids {
11997                if self.is_buffer_folded(buffer_id, cx) {
11998                    self.unfold_buffer(buffer_id, cx);
11999                } else {
12000                    self.fold_buffer(buffer_id, cx);
12001                }
12002            }
12003        }
12004    }
12005
12006    pub fn toggle_fold_recursive(
12007        &mut self,
12008        _: &actions::ToggleFoldRecursive,
12009        window: &mut Window,
12010        cx: &mut Context<Self>,
12011    ) {
12012        let selection = self.selections.newest::<Point>(cx);
12013
12014        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12015        let range = if selection.is_empty() {
12016            let point = selection.head().to_display_point(&display_map);
12017            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12018            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12019                .to_point(&display_map);
12020            start..end
12021        } else {
12022            selection.range()
12023        };
12024        if display_map.folds_in_range(range).next().is_some() {
12025            self.unfold_recursive(&Default::default(), window, cx)
12026        } else {
12027            self.fold_recursive(&Default::default(), window, cx)
12028        }
12029    }
12030
12031    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12032        if self.is_singleton(cx) {
12033            let mut to_fold = Vec::new();
12034            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12035            let selections = self.selections.all_adjusted(cx);
12036
12037            for selection in selections {
12038                let range = selection.range().sorted();
12039                let buffer_start_row = range.start.row;
12040
12041                if range.start.row != range.end.row {
12042                    let mut found = false;
12043                    let mut row = range.start.row;
12044                    while row <= range.end.row {
12045                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12046                        {
12047                            found = true;
12048                            row = crease.range().end.row + 1;
12049                            to_fold.push(crease);
12050                        } else {
12051                            row += 1
12052                        }
12053                    }
12054                    if found {
12055                        continue;
12056                    }
12057                }
12058
12059                for row in (0..=range.start.row).rev() {
12060                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12061                        if crease.range().end.row >= buffer_start_row {
12062                            to_fold.push(crease);
12063                            if row <= range.start.row {
12064                                break;
12065                            }
12066                        }
12067                    }
12068                }
12069            }
12070
12071            self.fold_creases(to_fold, true, window, cx);
12072        } else {
12073            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12074
12075            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12076                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12077                .map(|(snapshot, _, _)| snapshot.remote_id())
12078                .collect();
12079            for buffer_id in buffer_ids {
12080                self.fold_buffer(buffer_id, cx);
12081            }
12082        }
12083    }
12084
12085    fn fold_at_level(
12086        &mut self,
12087        fold_at: &FoldAtLevel,
12088        window: &mut Window,
12089        cx: &mut Context<Self>,
12090    ) {
12091        if !self.buffer.read(cx).is_singleton() {
12092            return;
12093        }
12094
12095        let fold_at_level = fold_at.0;
12096        let snapshot = self.buffer.read(cx).snapshot(cx);
12097        let mut to_fold = Vec::new();
12098        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12099
12100        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12101            while start_row < end_row {
12102                match self
12103                    .snapshot(window, cx)
12104                    .crease_for_buffer_row(MultiBufferRow(start_row))
12105                {
12106                    Some(crease) => {
12107                        let nested_start_row = crease.range().start.row + 1;
12108                        let nested_end_row = crease.range().end.row;
12109
12110                        if current_level < fold_at_level {
12111                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12112                        } else if current_level == fold_at_level {
12113                            to_fold.push(crease);
12114                        }
12115
12116                        start_row = nested_end_row + 1;
12117                    }
12118                    None => start_row += 1,
12119                }
12120            }
12121        }
12122
12123        self.fold_creases(to_fold, true, window, cx);
12124    }
12125
12126    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12127        if self.buffer.read(cx).is_singleton() {
12128            let mut fold_ranges = Vec::new();
12129            let snapshot = self.buffer.read(cx).snapshot(cx);
12130
12131            for row in 0..snapshot.max_row().0 {
12132                if let Some(foldable_range) = self
12133                    .snapshot(window, cx)
12134                    .crease_for_buffer_row(MultiBufferRow(row))
12135                {
12136                    fold_ranges.push(foldable_range);
12137                }
12138            }
12139
12140            self.fold_creases(fold_ranges, true, window, cx);
12141        } else {
12142            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12143                editor
12144                    .update_in(&mut cx, |editor, _, cx| {
12145                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12146                            editor.fold_buffer(buffer_id, cx);
12147                        }
12148                    })
12149                    .ok();
12150            });
12151        }
12152    }
12153
12154    pub fn fold_function_bodies(
12155        &mut self,
12156        _: &actions::FoldFunctionBodies,
12157        window: &mut Window,
12158        cx: &mut Context<Self>,
12159    ) {
12160        let snapshot = self.buffer.read(cx).snapshot(cx);
12161
12162        let ranges = snapshot
12163            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12164            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12165            .collect::<Vec<_>>();
12166
12167        let creases = ranges
12168            .into_iter()
12169            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12170            .collect();
12171
12172        self.fold_creases(creases, true, window, cx);
12173    }
12174
12175    pub fn fold_recursive(
12176        &mut self,
12177        _: &actions::FoldRecursive,
12178        window: &mut Window,
12179        cx: &mut Context<Self>,
12180    ) {
12181        let mut to_fold = Vec::new();
12182        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12183        let selections = self.selections.all_adjusted(cx);
12184
12185        for selection in selections {
12186            let range = selection.range().sorted();
12187            let buffer_start_row = range.start.row;
12188
12189            if range.start.row != range.end.row {
12190                let mut found = false;
12191                for row in range.start.row..=range.end.row {
12192                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12193                        found = true;
12194                        to_fold.push(crease);
12195                    }
12196                }
12197                if found {
12198                    continue;
12199                }
12200            }
12201
12202            for row in (0..=range.start.row).rev() {
12203                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12204                    if crease.range().end.row >= buffer_start_row {
12205                        to_fold.push(crease);
12206                    } else {
12207                        break;
12208                    }
12209                }
12210            }
12211        }
12212
12213        self.fold_creases(to_fold, true, window, cx);
12214    }
12215
12216    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12217        let buffer_row = fold_at.buffer_row;
12218        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12219
12220        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12221            let autoscroll = self
12222                .selections
12223                .all::<Point>(cx)
12224                .iter()
12225                .any(|selection| crease.range().overlaps(&selection.range()));
12226
12227            self.fold_creases(vec![crease], autoscroll, window, cx);
12228        }
12229    }
12230
12231    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12232        if self.is_singleton(cx) {
12233            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12234            let buffer = &display_map.buffer_snapshot;
12235            let selections = self.selections.all::<Point>(cx);
12236            let ranges = selections
12237                .iter()
12238                .map(|s| {
12239                    let range = s.display_range(&display_map).sorted();
12240                    let mut start = range.start.to_point(&display_map);
12241                    let mut end = range.end.to_point(&display_map);
12242                    start.column = 0;
12243                    end.column = buffer.line_len(MultiBufferRow(end.row));
12244                    start..end
12245                })
12246                .collect::<Vec<_>>();
12247
12248            self.unfold_ranges(&ranges, true, true, cx);
12249        } else {
12250            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12251            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12252                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12253                .map(|(snapshot, _, _)| snapshot.remote_id())
12254                .collect();
12255            for buffer_id in buffer_ids {
12256                self.unfold_buffer(buffer_id, cx);
12257            }
12258        }
12259    }
12260
12261    pub fn unfold_recursive(
12262        &mut self,
12263        _: &UnfoldRecursive,
12264        _window: &mut Window,
12265        cx: &mut Context<Self>,
12266    ) {
12267        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12268        let selections = self.selections.all::<Point>(cx);
12269        let ranges = selections
12270            .iter()
12271            .map(|s| {
12272                let mut range = s.display_range(&display_map).sorted();
12273                *range.start.column_mut() = 0;
12274                *range.end.column_mut() = display_map.line_len(range.end.row());
12275                let start = range.start.to_point(&display_map);
12276                let end = range.end.to_point(&display_map);
12277                start..end
12278            })
12279            .collect::<Vec<_>>();
12280
12281        self.unfold_ranges(&ranges, true, true, cx);
12282    }
12283
12284    pub fn unfold_at(
12285        &mut self,
12286        unfold_at: &UnfoldAt,
12287        _window: &mut Window,
12288        cx: &mut Context<Self>,
12289    ) {
12290        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12291
12292        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12293            ..Point::new(
12294                unfold_at.buffer_row.0,
12295                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12296            );
12297
12298        let autoscroll = self
12299            .selections
12300            .all::<Point>(cx)
12301            .iter()
12302            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12303
12304        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12305    }
12306
12307    pub fn unfold_all(
12308        &mut self,
12309        _: &actions::UnfoldAll,
12310        _window: &mut Window,
12311        cx: &mut Context<Self>,
12312    ) {
12313        if self.buffer.read(cx).is_singleton() {
12314            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12315            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12316        } else {
12317            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12318                editor
12319                    .update(&mut cx, |editor, cx| {
12320                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12321                            editor.unfold_buffer(buffer_id, cx);
12322                        }
12323                    })
12324                    .ok();
12325            });
12326        }
12327    }
12328
12329    pub fn fold_selected_ranges(
12330        &mut self,
12331        _: &FoldSelectedRanges,
12332        window: &mut Window,
12333        cx: &mut Context<Self>,
12334    ) {
12335        let selections = self.selections.all::<Point>(cx);
12336        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12337        let line_mode = self.selections.line_mode;
12338        let ranges = selections
12339            .into_iter()
12340            .map(|s| {
12341                if line_mode {
12342                    let start = Point::new(s.start.row, 0);
12343                    let end = Point::new(
12344                        s.end.row,
12345                        display_map
12346                            .buffer_snapshot
12347                            .line_len(MultiBufferRow(s.end.row)),
12348                    );
12349                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12350                } else {
12351                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12352                }
12353            })
12354            .collect::<Vec<_>>();
12355        self.fold_creases(ranges, true, window, cx);
12356    }
12357
12358    pub fn fold_ranges<T: ToOffset + Clone>(
12359        &mut self,
12360        ranges: Vec<Range<T>>,
12361        auto_scroll: bool,
12362        window: &mut Window,
12363        cx: &mut Context<Self>,
12364    ) {
12365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12366        let ranges = ranges
12367            .into_iter()
12368            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12369            .collect::<Vec<_>>();
12370        self.fold_creases(ranges, auto_scroll, window, cx);
12371    }
12372
12373    pub fn fold_creases<T: ToOffset + Clone>(
12374        &mut self,
12375        creases: Vec<Crease<T>>,
12376        auto_scroll: bool,
12377        window: &mut Window,
12378        cx: &mut Context<Self>,
12379    ) {
12380        if creases.is_empty() {
12381            return;
12382        }
12383
12384        let mut buffers_affected = HashSet::default();
12385        let multi_buffer = self.buffer().read(cx);
12386        for crease in &creases {
12387            if let Some((_, buffer, _)) =
12388                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12389            {
12390                buffers_affected.insert(buffer.read(cx).remote_id());
12391            };
12392        }
12393
12394        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12395
12396        if auto_scroll {
12397            self.request_autoscroll(Autoscroll::fit(), cx);
12398        }
12399
12400        cx.notify();
12401
12402        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12403            // Clear diagnostics block when folding a range that contains it.
12404            let snapshot = self.snapshot(window, cx);
12405            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12406                drop(snapshot);
12407                self.active_diagnostics = Some(active_diagnostics);
12408                self.dismiss_diagnostics(cx);
12409            } else {
12410                self.active_diagnostics = Some(active_diagnostics);
12411            }
12412        }
12413
12414        self.scrollbar_marker_state.dirty = true;
12415    }
12416
12417    /// Removes any folds whose ranges intersect any of the given ranges.
12418    pub fn unfold_ranges<T: ToOffset + Clone>(
12419        &mut self,
12420        ranges: &[Range<T>],
12421        inclusive: bool,
12422        auto_scroll: bool,
12423        cx: &mut Context<Self>,
12424    ) {
12425        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12426            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12427        });
12428    }
12429
12430    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12431        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12432            return;
12433        }
12434        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12435        self.display_map
12436            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12437        cx.emit(EditorEvent::BufferFoldToggled {
12438            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12439            folded: true,
12440        });
12441        cx.notify();
12442    }
12443
12444    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12445        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12446            return;
12447        }
12448        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12449        self.display_map.update(cx, |display_map, cx| {
12450            display_map.unfold_buffer(buffer_id, cx);
12451        });
12452        cx.emit(EditorEvent::BufferFoldToggled {
12453            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12454            folded: false,
12455        });
12456        cx.notify();
12457    }
12458
12459    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12460        self.display_map.read(cx).is_buffer_folded(buffer)
12461    }
12462
12463    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12464        self.display_map.read(cx).folded_buffers()
12465    }
12466
12467    /// Removes any folds with the given ranges.
12468    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12469        &mut self,
12470        ranges: &[Range<T>],
12471        type_id: TypeId,
12472        auto_scroll: bool,
12473        cx: &mut Context<Self>,
12474    ) {
12475        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12476            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12477        });
12478    }
12479
12480    fn remove_folds_with<T: ToOffset + Clone>(
12481        &mut self,
12482        ranges: &[Range<T>],
12483        auto_scroll: bool,
12484        cx: &mut Context<Self>,
12485        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12486    ) {
12487        if ranges.is_empty() {
12488            return;
12489        }
12490
12491        let mut buffers_affected = HashSet::default();
12492        let multi_buffer = self.buffer().read(cx);
12493        for range in ranges {
12494            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12495                buffers_affected.insert(buffer.read(cx).remote_id());
12496            };
12497        }
12498
12499        self.display_map.update(cx, update);
12500
12501        if auto_scroll {
12502            self.request_autoscroll(Autoscroll::fit(), cx);
12503        }
12504
12505        cx.notify();
12506        self.scrollbar_marker_state.dirty = true;
12507        self.active_indent_guides_state.dirty = true;
12508    }
12509
12510    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12511        self.display_map.read(cx).fold_placeholder.clone()
12512    }
12513
12514    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12515        self.buffer.update(cx, |buffer, cx| {
12516            buffer.set_all_diff_hunks_expanded(cx);
12517        });
12518    }
12519
12520    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12521        self.distinguish_unstaged_diff_hunks = true;
12522    }
12523
12524    pub fn expand_all_diff_hunks(
12525        &mut self,
12526        _: &ExpandAllHunkDiffs,
12527        _window: &mut Window,
12528        cx: &mut Context<Self>,
12529    ) {
12530        self.buffer.update(cx, |buffer, cx| {
12531            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12532        });
12533    }
12534
12535    pub fn toggle_selected_diff_hunks(
12536        &mut self,
12537        _: &ToggleSelectedDiffHunks,
12538        _window: &mut Window,
12539        cx: &mut Context<Self>,
12540    ) {
12541        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12542        self.toggle_diff_hunks_in_ranges(ranges, cx);
12543    }
12544
12545    fn diff_hunks_in_ranges<'a>(
12546        &'a self,
12547        ranges: &'a [Range<Anchor>],
12548        buffer: &'a MultiBufferSnapshot,
12549    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12550        ranges.iter().flat_map(move |range| {
12551            let end_excerpt_id = range.end.excerpt_id;
12552            let range = range.to_point(buffer);
12553            let mut peek_end = range.end;
12554            if range.end.row < buffer.max_row().0 {
12555                peek_end = Point::new(range.end.row + 1, 0);
12556            }
12557            buffer
12558                .diff_hunks_in_range(range.start..peek_end)
12559                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12560        })
12561    }
12562
12563    pub fn has_stageable_diff_hunks_in_ranges(
12564        &self,
12565        ranges: &[Range<Anchor>],
12566        snapshot: &MultiBufferSnapshot,
12567    ) -> bool {
12568        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12569        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12570    }
12571
12572    pub fn toggle_staged_selected_diff_hunks(
12573        &mut self,
12574        _: &::git::ToggleStaged,
12575        _window: &mut Window,
12576        cx: &mut Context<Self>,
12577    ) {
12578        let snapshot = self.buffer.read(cx).snapshot(cx);
12579        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12580        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12581        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12582    }
12583
12584    pub fn stage_and_next(
12585        &mut self,
12586        _: &::git::StageAndNext,
12587        window: &mut Window,
12588        cx: &mut Context<Self>,
12589    ) {
12590        let head = self.selections.newest_anchor().head();
12591        self.stage_or_unstage_diff_hunks(true, &[head..head], cx);
12592        self.go_to_next_hunk(&Default::default(), window, cx);
12593    }
12594
12595    pub fn unstage_and_next(
12596        &mut self,
12597        _: &::git::UnstageAndNext,
12598        window: &mut Window,
12599        cx: &mut Context<Self>,
12600    ) {
12601        let head = self.selections.newest_anchor().head();
12602        self.stage_or_unstage_diff_hunks(false, &[head..head], cx);
12603        self.go_to_next_hunk(&Default::default(), window, cx);
12604    }
12605
12606    pub fn stage_or_unstage_diff_hunks(
12607        &mut self,
12608        stage: bool,
12609        ranges: &[Range<Anchor>],
12610        cx: &mut Context<Self>,
12611    ) {
12612        let snapshot = self.buffer.read(cx).snapshot(cx);
12613        let Some(project) = &self.project else {
12614            return;
12615        };
12616
12617        let chunk_by = self
12618            .diff_hunks_in_ranges(&ranges, &snapshot)
12619            .chunk_by(|hunk| hunk.buffer_id);
12620        for (buffer_id, hunks) in &chunk_by {
12621            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12622        }
12623    }
12624
12625    fn do_stage_or_unstage(
12626        project: &Entity<Project>,
12627        stage: bool,
12628        buffer_id: BufferId,
12629        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12630        snapshot: &MultiBufferSnapshot,
12631        cx: &mut Context<Self>,
12632    ) {
12633        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12634            log::debug!("no buffer for id");
12635            return;
12636        };
12637        let buffer = buffer.read(cx).snapshot();
12638        let Some((repo, path)) = project
12639            .read(cx)
12640            .repository_and_path_for_buffer_id(buffer_id, cx)
12641        else {
12642            log::debug!("no git repo for buffer id");
12643            return;
12644        };
12645        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12646            log::debug!("no diff for buffer id");
12647            return;
12648        };
12649        let Some(secondary_diff) = diff.secondary_diff() else {
12650            log::debug!("no secondary diff for buffer id");
12651            return;
12652        };
12653
12654        let edits = diff.secondary_edits_for_stage_or_unstage(
12655            stage,
12656            hunks.filter_map(|hunk| {
12657                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12658                    return None;
12659                } else if !stage
12660                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12661                {
12662                    return None;
12663                }
12664                Some((
12665                    hunk.diff_base_byte_range.clone(),
12666                    hunk.secondary_diff_base_byte_range.clone(),
12667                    hunk.buffer_range.clone(),
12668                ))
12669            }),
12670            &buffer,
12671        );
12672
12673        let Some(index_base) = secondary_diff
12674            .base_text()
12675            .map(|snapshot| snapshot.text.as_rope().clone())
12676        else {
12677            log::debug!("no index base");
12678            return;
12679        };
12680        let index_buffer = cx.new(|cx| {
12681            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12682        });
12683        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12684            index_buffer.edit(edits, None, cx);
12685            index_buffer.snapshot().as_rope().to_string()
12686        });
12687        let new_index_text = if new_index_text.is_empty()
12688            && (diff.is_single_insertion
12689                || buffer
12690                    .file()
12691                    .map_or(false, |file| file.disk_state() == DiskState::New))
12692        {
12693            log::debug!("removing from index");
12694            None
12695        } else {
12696            Some(new_index_text)
12697        };
12698
12699        let _ = repo.read(cx).set_index_text(&path, new_index_text);
12700    }
12701
12702    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12703        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12704        self.buffer
12705            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12706    }
12707
12708    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12709        self.buffer.update(cx, |buffer, cx| {
12710            let ranges = vec![Anchor::min()..Anchor::max()];
12711            if !buffer.all_diff_hunks_expanded()
12712                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12713            {
12714                buffer.collapse_diff_hunks(ranges, cx);
12715                true
12716            } else {
12717                false
12718            }
12719        })
12720    }
12721
12722    fn toggle_diff_hunks_in_ranges(
12723        &mut self,
12724        ranges: Vec<Range<Anchor>>,
12725        cx: &mut Context<'_, Editor>,
12726    ) {
12727        self.buffer.update(cx, |buffer, cx| {
12728            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12729            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12730        })
12731    }
12732
12733    fn toggle_diff_hunks_in_ranges_narrow(
12734        &mut self,
12735        ranges: Vec<Range<Anchor>>,
12736        cx: &mut Context<'_, Editor>,
12737    ) {
12738        self.buffer.update(cx, |buffer, cx| {
12739            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12740            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12741        })
12742    }
12743
12744    pub(crate) fn apply_all_diff_hunks(
12745        &mut self,
12746        _: &ApplyAllDiffHunks,
12747        window: &mut Window,
12748        cx: &mut Context<Self>,
12749    ) {
12750        let buffers = self.buffer.read(cx).all_buffers();
12751        for branch_buffer in buffers {
12752            branch_buffer.update(cx, |branch_buffer, cx| {
12753                branch_buffer.merge_into_base(Vec::new(), cx);
12754            });
12755        }
12756
12757        if let Some(project) = self.project.clone() {
12758            self.save(true, project, window, cx).detach_and_log_err(cx);
12759        }
12760    }
12761
12762    pub(crate) fn apply_selected_diff_hunks(
12763        &mut self,
12764        _: &ApplyDiffHunk,
12765        window: &mut Window,
12766        cx: &mut Context<Self>,
12767    ) {
12768        let snapshot = self.snapshot(window, cx);
12769        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12770        let mut ranges_by_buffer = HashMap::default();
12771        self.transact(window, cx, |editor, _window, cx| {
12772            for hunk in hunks {
12773                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12774                    ranges_by_buffer
12775                        .entry(buffer.clone())
12776                        .or_insert_with(Vec::new)
12777                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12778                }
12779            }
12780
12781            for (buffer, ranges) in ranges_by_buffer {
12782                buffer.update(cx, |buffer, cx| {
12783                    buffer.merge_into_base(ranges, cx);
12784                });
12785            }
12786        });
12787
12788        if let Some(project) = self.project.clone() {
12789            self.save(true, project, window, cx).detach_and_log_err(cx);
12790        }
12791    }
12792
12793    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12794        if hovered != self.gutter_hovered {
12795            self.gutter_hovered = hovered;
12796            cx.notify();
12797        }
12798    }
12799
12800    pub fn insert_blocks(
12801        &mut self,
12802        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12803        autoscroll: Option<Autoscroll>,
12804        cx: &mut Context<Self>,
12805    ) -> Vec<CustomBlockId> {
12806        let blocks = self
12807            .display_map
12808            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12809        if let Some(autoscroll) = autoscroll {
12810            self.request_autoscroll(autoscroll, cx);
12811        }
12812        cx.notify();
12813        blocks
12814    }
12815
12816    pub fn resize_blocks(
12817        &mut self,
12818        heights: HashMap<CustomBlockId, u32>,
12819        autoscroll: Option<Autoscroll>,
12820        cx: &mut Context<Self>,
12821    ) {
12822        self.display_map
12823            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12824        if let Some(autoscroll) = autoscroll {
12825            self.request_autoscroll(autoscroll, cx);
12826        }
12827        cx.notify();
12828    }
12829
12830    pub fn replace_blocks(
12831        &mut self,
12832        renderers: HashMap<CustomBlockId, RenderBlock>,
12833        autoscroll: Option<Autoscroll>,
12834        cx: &mut Context<Self>,
12835    ) {
12836        self.display_map
12837            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12838        if let Some(autoscroll) = autoscroll {
12839            self.request_autoscroll(autoscroll, cx);
12840        }
12841        cx.notify();
12842    }
12843
12844    pub fn remove_blocks(
12845        &mut self,
12846        block_ids: HashSet<CustomBlockId>,
12847        autoscroll: Option<Autoscroll>,
12848        cx: &mut Context<Self>,
12849    ) {
12850        self.display_map.update(cx, |display_map, cx| {
12851            display_map.remove_blocks(block_ids, cx)
12852        });
12853        if let Some(autoscroll) = autoscroll {
12854            self.request_autoscroll(autoscroll, cx);
12855        }
12856        cx.notify();
12857    }
12858
12859    pub fn row_for_block(
12860        &self,
12861        block_id: CustomBlockId,
12862        cx: &mut Context<Self>,
12863    ) -> Option<DisplayRow> {
12864        self.display_map
12865            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12866    }
12867
12868    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12869        self.focused_block = Some(focused_block);
12870    }
12871
12872    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12873        self.focused_block.take()
12874    }
12875
12876    pub fn insert_creases(
12877        &mut self,
12878        creases: impl IntoIterator<Item = Crease<Anchor>>,
12879        cx: &mut Context<Self>,
12880    ) -> Vec<CreaseId> {
12881        self.display_map
12882            .update(cx, |map, cx| map.insert_creases(creases, cx))
12883    }
12884
12885    pub fn remove_creases(
12886        &mut self,
12887        ids: impl IntoIterator<Item = CreaseId>,
12888        cx: &mut Context<Self>,
12889    ) {
12890        self.display_map
12891            .update(cx, |map, cx| map.remove_creases(ids, cx));
12892    }
12893
12894    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12895        self.display_map
12896            .update(cx, |map, cx| map.snapshot(cx))
12897            .longest_row()
12898    }
12899
12900    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12901        self.display_map
12902            .update(cx, |map, cx| map.snapshot(cx))
12903            .max_point()
12904    }
12905
12906    pub fn text(&self, cx: &App) -> String {
12907        self.buffer.read(cx).read(cx).text()
12908    }
12909
12910    pub fn is_empty(&self, cx: &App) -> bool {
12911        self.buffer.read(cx).read(cx).is_empty()
12912    }
12913
12914    pub fn text_option(&self, cx: &App) -> Option<String> {
12915        let text = self.text(cx);
12916        let text = text.trim();
12917
12918        if text.is_empty() {
12919            return None;
12920        }
12921
12922        Some(text.to_string())
12923    }
12924
12925    pub fn set_text(
12926        &mut self,
12927        text: impl Into<Arc<str>>,
12928        window: &mut Window,
12929        cx: &mut Context<Self>,
12930    ) {
12931        self.transact(window, cx, |this, _, cx| {
12932            this.buffer
12933                .read(cx)
12934                .as_singleton()
12935                .expect("you can only call set_text on editors for singleton buffers")
12936                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12937        });
12938    }
12939
12940    pub fn display_text(&self, cx: &mut App) -> String {
12941        self.display_map
12942            .update(cx, |map, cx| map.snapshot(cx))
12943            .text()
12944    }
12945
12946    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12947        let mut wrap_guides = smallvec::smallvec![];
12948
12949        if self.show_wrap_guides == Some(false) {
12950            return wrap_guides;
12951        }
12952
12953        let settings = self.buffer.read(cx).settings_at(0, cx);
12954        if settings.show_wrap_guides {
12955            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12956                wrap_guides.push((soft_wrap as usize, true));
12957            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12958                wrap_guides.push((soft_wrap as usize, true));
12959            }
12960            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12961        }
12962
12963        wrap_guides
12964    }
12965
12966    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12967        let settings = self.buffer.read(cx).settings_at(0, cx);
12968        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12969        match mode {
12970            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12971                SoftWrap::None
12972            }
12973            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12974            language_settings::SoftWrap::PreferredLineLength => {
12975                SoftWrap::Column(settings.preferred_line_length)
12976            }
12977            language_settings::SoftWrap::Bounded => {
12978                SoftWrap::Bounded(settings.preferred_line_length)
12979            }
12980        }
12981    }
12982
12983    pub fn set_soft_wrap_mode(
12984        &mut self,
12985        mode: language_settings::SoftWrap,
12986
12987        cx: &mut Context<Self>,
12988    ) {
12989        self.soft_wrap_mode_override = Some(mode);
12990        cx.notify();
12991    }
12992
12993    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12994        self.text_style_refinement = Some(style);
12995    }
12996
12997    /// called by the Element so we know what style we were most recently rendered with.
12998    pub(crate) fn set_style(
12999        &mut self,
13000        style: EditorStyle,
13001        window: &mut Window,
13002        cx: &mut Context<Self>,
13003    ) {
13004        let rem_size = window.rem_size();
13005        self.display_map.update(cx, |map, cx| {
13006            map.set_font(
13007                style.text.font(),
13008                style.text.font_size.to_pixels(rem_size),
13009                cx,
13010            )
13011        });
13012        self.style = Some(style);
13013    }
13014
13015    pub fn style(&self) -> Option<&EditorStyle> {
13016        self.style.as_ref()
13017    }
13018
13019    // Called by the element. This method is not designed to be called outside of the editor
13020    // element's layout code because it does not notify when rewrapping is computed synchronously.
13021    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13022        self.display_map
13023            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13024    }
13025
13026    pub fn set_soft_wrap(&mut self) {
13027        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13028    }
13029
13030    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13031        if self.soft_wrap_mode_override.is_some() {
13032            self.soft_wrap_mode_override.take();
13033        } else {
13034            let soft_wrap = match self.soft_wrap_mode(cx) {
13035                SoftWrap::GitDiff => return,
13036                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13037                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13038                    language_settings::SoftWrap::None
13039                }
13040            };
13041            self.soft_wrap_mode_override = Some(soft_wrap);
13042        }
13043        cx.notify();
13044    }
13045
13046    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13047        let Some(workspace) = self.workspace() else {
13048            return;
13049        };
13050        let fs = workspace.read(cx).app_state().fs.clone();
13051        let current_show = TabBarSettings::get_global(cx).show;
13052        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13053            setting.show = Some(!current_show);
13054        });
13055    }
13056
13057    pub fn toggle_indent_guides(
13058        &mut self,
13059        _: &ToggleIndentGuides,
13060        _: &mut Window,
13061        cx: &mut Context<Self>,
13062    ) {
13063        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13064            self.buffer
13065                .read(cx)
13066                .settings_at(0, cx)
13067                .indent_guides
13068                .enabled
13069        });
13070        self.show_indent_guides = Some(!currently_enabled);
13071        cx.notify();
13072    }
13073
13074    fn should_show_indent_guides(&self) -> Option<bool> {
13075        self.show_indent_guides
13076    }
13077
13078    pub fn toggle_line_numbers(
13079        &mut self,
13080        _: &ToggleLineNumbers,
13081        _: &mut Window,
13082        cx: &mut Context<Self>,
13083    ) {
13084        let mut editor_settings = EditorSettings::get_global(cx).clone();
13085        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13086        EditorSettings::override_global(editor_settings, cx);
13087    }
13088
13089    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13090        self.use_relative_line_numbers
13091            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13092    }
13093
13094    pub fn toggle_relative_line_numbers(
13095        &mut self,
13096        _: &ToggleRelativeLineNumbers,
13097        _: &mut Window,
13098        cx: &mut Context<Self>,
13099    ) {
13100        let is_relative = self.should_use_relative_line_numbers(cx);
13101        self.set_relative_line_number(Some(!is_relative), cx)
13102    }
13103
13104    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13105        self.use_relative_line_numbers = is_relative;
13106        cx.notify();
13107    }
13108
13109    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13110        self.show_gutter = show_gutter;
13111        cx.notify();
13112    }
13113
13114    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13115        self.show_scrollbars = show_scrollbars;
13116        cx.notify();
13117    }
13118
13119    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13120        self.show_line_numbers = Some(show_line_numbers);
13121        cx.notify();
13122    }
13123
13124    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13125        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13126        cx.notify();
13127    }
13128
13129    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13130        self.show_code_actions = Some(show_code_actions);
13131        cx.notify();
13132    }
13133
13134    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13135        self.show_runnables = Some(show_runnables);
13136        cx.notify();
13137    }
13138
13139    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13140        if self.display_map.read(cx).masked != masked {
13141            self.display_map.update(cx, |map, _| map.masked = masked);
13142        }
13143        cx.notify()
13144    }
13145
13146    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13147        self.show_wrap_guides = Some(show_wrap_guides);
13148        cx.notify();
13149    }
13150
13151    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13152        self.show_indent_guides = Some(show_indent_guides);
13153        cx.notify();
13154    }
13155
13156    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13157        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13158            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13159                if let Some(dir) = file.abs_path(cx).parent() {
13160                    return Some(dir.to_owned());
13161                }
13162            }
13163
13164            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13165                return Some(project_path.path.to_path_buf());
13166            }
13167        }
13168
13169        None
13170    }
13171
13172    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13173        self.active_excerpt(cx)?
13174            .1
13175            .read(cx)
13176            .file()
13177            .and_then(|f| f.as_local())
13178    }
13179
13180    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13181        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13182            let buffer = buffer.read(cx);
13183            if let Some(project_path) = buffer.project_path(cx) {
13184                let project = self.project.as_ref()?.read(cx);
13185                project.absolute_path(&project_path, cx)
13186            } else {
13187                buffer
13188                    .file()
13189                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13190            }
13191        })
13192    }
13193
13194    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13195        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13196            let project_path = buffer.read(cx).project_path(cx)?;
13197            let project = self.project.as_ref()?.read(cx);
13198            let entry = project.entry_for_path(&project_path, cx)?;
13199            let path = entry.path.to_path_buf();
13200            Some(path)
13201        })
13202    }
13203
13204    pub fn reveal_in_finder(
13205        &mut self,
13206        _: &RevealInFileManager,
13207        _window: &mut Window,
13208        cx: &mut Context<Self>,
13209    ) {
13210        if let Some(target) = self.target_file(cx) {
13211            cx.reveal_path(&target.abs_path(cx));
13212        }
13213    }
13214
13215    pub fn copy_path(
13216        &mut self,
13217        _: &zed_actions::workspace::CopyPath,
13218        _window: &mut Window,
13219        cx: &mut Context<Self>,
13220    ) {
13221        if let Some(path) = self.target_file_abs_path(cx) {
13222            if let Some(path) = path.to_str() {
13223                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13224            }
13225        }
13226    }
13227
13228    pub fn copy_relative_path(
13229        &mut self,
13230        _: &zed_actions::workspace::CopyRelativePath,
13231        _window: &mut Window,
13232        cx: &mut Context<Self>,
13233    ) {
13234        if let Some(path) = self.target_file_path(cx) {
13235            if let Some(path) = path.to_str() {
13236                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13237            }
13238        }
13239    }
13240
13241    pub fn copy_file_name_without_extension(
13242        &mut self,
13243        _: &CopyFileNameWithoutExtension,
13244        _: &mut Window,
13245        cx: &mut Context<Self>,
13246    ) {
13247        if let Some(file) = self.target_file(cx) {
13248            if let Some(file_stem) = file.path().file_stem() {
13249                if let Some(name) = file_stem.to_str() {
13250                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13251                }
13252            }
13253        }
13254    }
13255
13256    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13257        if let Some(file) = self.target_file(cx) {
13258            if let Some(file_name) = file.path().file_name() {
13259                if let Some(name) = file_name.to_str() {
13260                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13261                }
13262            }
13263        }
13264    }
13265
13266    pub fn toggle_git_blame(
13267        &mut self,
13268        _: &ToggleGitBlame,
13269        window: &mut Window,
13270        cx: &mut Context<Self>,
13271    ) {
13272        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13273
13274        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13275            self.start_git_blame(true, window, cx);
13276        }
13277
13278        cx.notify();
13279    }
13280
13281    pub fn toggle_git_blame_inline(
13282        &mut self,
13283        _: &ToggleGitBlameInline,
13284        window: &mut Window,
13285        cx: &mut Context<Self>,
13286    ) {
13287        self.toggle_git_blame_inline_internal(true, window, cx);
13288        cx.notify();
13289    }
13290
13291    pub fn git_blame_inline_enabled(&self) -> bool {
13292        self.git_blame_inline_enabled
13293    }
13294
13295    pub fn toggle_selection_menu(
13296        &mut self,
13297        _: &ToggleSelectionMenu,
13298        _: &mut Window,
13299        cx: &mut Context<Self>,
13300    ) {
13301        self.show_selection_menu = self
13302            .show_selection_menu
13303            .map(|show_selections_menu| !show_selections_menu)
13304            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13305
13306        cx.notify();
13307    }
13308
13309    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13310        self.show_selection_menu
13311            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13312    }
13313
13314    fn start_git_blame(
13315        &mut self,
13316        user_triggered: bool,
13317        window: &mut Window,
13318        cx: &mut Context<Self>,
13319    ) {
13320        if let Some(project) = self.project.as_ref() {
13321            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13322                return;
13323            };
13324
13325            if buffer.read(cx).file().is_none() {
13326                return;
13327            }
13328
13329            let focused = self.focus_handle(cx).contains_focused(window, cx);
13330
13331            let project = project.clone();
13332            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13333            self.blame_subscription =
13334                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13335            self.blame = Some(blame);
13336        }
13337    }
13338
13339    fn toggle_git_blame_inline_internal(
13340        &mut self,
13341        user_triggered: bool,
13342        window: &mut Window,
13343        cx: &mut Context<Self>,
13344    ) {
13345        if self.git_blame_inline_enabled {
13346            self.git_blame_inline_enabled = false;
13347            self.show_git_blame_inline = false;
13348            self.show_git_blame_inline_delay_task.take();
13349        } else {
13350            self.git_blame_inline_enabled = true;
13351            self.start_git_blame_inline(user_triggered, window, cx);
13352        }
13353
13354        cx.notify();
13355    }
13356
13357    fn start_git_blame_inline(
13358        &mut self,
13359        user_triggered: bool,
13360        window: &mut Window,
13361        cx: &mut Context<Self>,
13362    ) {
13363        self.start_git_blame(user_triggered, window, cx);
13364
13365        if ProjectSettings::get_global(cx)
13366            .git
13367            .inline_blame_delay()
13368            .is_some()
13369        {
13370            self.start_inline_blame_timer(window, cx);
13371        } else {
13372            self.show_git_blame_inline = true
13373        }
13374    }
13375
13376    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13377        self.blame.as_ref()
13378    }
13379
13380    pub fn show_git_blame_gutter(&self) -> bool {
13381        self.show_git_blame_gutter
13382    }
13383
13384    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13385        self.show_git_blame_gutter && self.has_blame_entries(cx)
13386    }
13387
13388    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13389        self.show_git_blame_inline
13390            && (self.focus_handle.is_focused(window)
13391                || self
13392                    .git_blame_inline_tooltip
13393                    .as_ref()
13394                    .and_then(|t| t.upgrade())
13395                    .is_some())
13396            && !self.newest_selection_head_on_empty_line(cx)
13397            && self.has_blame_entries(cx)
13398    }
13399
13400    fn has_blame_entries(&self, cx: &App) -> bool {
13401        self.blame()
13402            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13403    }
13404
13405    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13406        let cursor_anchor = self.selections.newest_anchor().head();
13407
13408        let snapshot = self.buffer.read(cx).snapshot(cx);
13409        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13410
13411        snapshot.line_len(buffer_row) == 0
13412    }
13413
13414    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13415        let buffer_and_selection = maybe!({
13416            let selection = self.selections.newest::<Point>(cx);
13417            let selection_range = selection.range();
13418
13419            let multi_buffer = self.buffer().read(cx);
13420            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13421            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13422
13423            let (buffer, range, _) = if selection.reversed {
13424                buffer_ranges.first()
13425            } else {
13426                buffer_ranges.last()
13427            }?;
13428
13429            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13430                ..text::ToPoint::to_point(&range.end, &buffer).row;
13431            Some((
13432                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13433                selection,
13434            ))
13435        });
13436
13437        let Some((buffer, selection)) = buffer_and_selection else {
13438            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13439        };
13440
13441        let Some(project) = self.project.as_ref() else {
13442            return Task::ready(Err(anyhow!("editor does not have project")));
13443        };
13444
13445        project.update(cx, |project, cx| {
13446            project.get_permalink_to_line(&buffer, selection, cx)
13447        })
13448    }
13449
13450    pub fn copy_permalink_to_line(
13451        &mut self,
13452        _: &CopyPermalinkToLine,
13453        window: &mut Window,
13454        cx: &mut Context<Self>,
13455    ) {
13456        let permalink_task = self.get_permalink_to_line(cx);
13457        let workspace = self.workspace();
13458
13459        cx.spawn_in(window, |_, mut cx| async move {
13460            match permalink_task.await {
13461                Ok(permalink) => {
13462                    cx.update(|_, cx| {
13463                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13464                    })
13465                    .ok();
13466                }
13467                Err(err) => {
13468                    let message = format!("Failed to copy permalink: {err}");
13469
13470                    Err::<(), anyhow::Error>(err).log_err();
13471
13472                    if let Some(workspace) = workspace {
13473                        workspace
13474                            .update_in(&mut cx, |workspace, _, cx| {
13475                                struct CopyPermalinkToLine;
13476
13477                                workspace.show_toast(
13478                                    Toast::new(
13479                                        NotificationId::unique::<CopyPermalinkToLine>(),
13480                                        message,
13481                                    ),
13482                                    cx,
13483                                )
13484                            })
13485                            .ok();
13486                    }
13487                }
13488            }
13489        })
13490        .detach();
13491    }
13492
13493    pub fn copy_file_location(
13494        &mut self,
13495        _: &CopyFileLocation,
13496        _: &mut Window,
13497        cx: &mut Context<Self>,
13498    ) {
13499        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13500        if let Some(file) = self.target_file(cx) {
13501            if let Some(path) = file.path().to_str() {
13502                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13503            }
13504        }
13505    }
13506
13507    pub fn open_permalink_to_line(
13508        &mut self,
13509        _: &OpenPermalinkToLine,
13510        window: &mut Window,
13511        cx: &mut Context<Self>,
13512    ) {
13513        let permalink_task = self.get_permalink_to_line(cx);
13514        let workspace = self.workspace();
13515
13516        cx.spawn_in(window, |_, mut cx| async move {
13517            match permalink_task.await {
13518                Ok(permalink) => {
13519                    cx.update(|_, cx| {
13520                        cx.open_url(permalink.as_ref());
13521                    })
13522                    .ok();
13523                }
13524                Err(err) => {
13525                    let message = format!("Failed to open permalink: {err}");
13526
13527                    Err::<(), anyhow::Error>(err).log_err();
13528
13529                    if let Some(workspace) = workspace {
13530                        workspace
13531                            .update(&mut cx, |workspace, cx| {
13532                                struct OpenPermalinkToLine;
13533
13534                                workspace.show_toast(
13535                                    Toast::new(
13536                                        NotificationId::unique::<OpenPermalinkToLine>(),
13537                                        message,
13538                                    ),
13539                                    cx,
13540                                )
13541                            })
13542                            .ok();
13543                    }
13544                }
13545            }
13546        })
13547        .detach();
13548    }
13549
13550    pub fn insert_uuid_v4(
13551        &mut self,
13552        _: &InsertUuidV4,
13553        window: &mut Window,
13554        cx: &mut Context<Self>,
13555    ) {
13556        self.insert_uuid(UuidVersion::V4, window, cx);
13557    }
13558
13559    pub fn insert_uuid_v7(
13560        &mut self,
13561        _: &InsertUuidV7,
13562        window: &mut Window,
13563        cx: &mut Context<Self>,
13564    ) {
13565        self.insert_uuid(UuidVersion::V7, window, cx);
13566    }
13567
13568    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13569        self.transact(window, cx, |this, window, cx| {
13570            let edits = this
13571                .selections
13572                .all::<Point>(cx)
13573                .into_iter()
13574                .map(|selection| {
13575                    let uuid = match version {
13576                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13577                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13578                    };
13579
13580                    (selection.range(), uuid.to_string())
13581                });
13582            this.edit(edits, cx);
13583            this.refresh_inline_completion(true, false, window, cx);
13584        });
13585    }
13586
13587    pub fn open_selections_in_multibuffer(
13588        &mut self,
13589        _: &OpenSelectionsInMultibuffer,
13590        window: &mut Window,
13591        cx: &mut Context<Self>,
13592    ) {
13593        let multibuffer = self.buffer.read(cx);
13594
13595        let Some(buffer) = multibuffer.as_singleton() else {
13596            return;
13597        };
13598
13599        let Some(workspace) = self.workspace() else {
13600            return;
13601        };
13602
13603        let locations = self
13604            .selections
13605            .disjoint_anchors()
13606            .iter()
13607            .map(|range| Location {
13608                buffer: buffer.clone(),
13609                range: range.start.text_anchor..range.end.text_anchor,
13610            })
13611            .collect::<Vec<_>>();
13612
13613        let title = multibuffer.title(cx).to_string();
13614
13615        cx.spawn_in(window, |_, mut cx| async move {
13616            workspace.update_in(&mut cx, |workspace, window, cx| {
13617                Self::open_locations_in_multibuffer(
13618                    workspace,
13619                    locations,
13620                    format!("Selections for '{title}'"),
13621                    false,
13622                    MultibufferSelectionMode::All,
13623                    window,
13624                    cx,
13625                );
13626            })
13627        })
13628        .detach();
13629    }
13630
13631    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13632    /// last highlight added will be used.
13633    ///
13634    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13635    pub fn highlight_rows<T: 'static>(
13636        &mut self,
13637        range: Range<Anchor>,
13638        color: Hsla,
13639        should_autoscroll: bool,
13640        cx: &mut Context<Self>,
13641    ) {
13642        let snapshot = self.buffer().read(cx).snapshot(cx);
13643        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13644        let ix = row_highlights.binary_search_by(|highlight| {
13645            Ordering::Equal
13646                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13647                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13648        });
13649
13650        if let Err(mut ix) = ix {
13651            let index = post_inc(&mut self.highlight_order);
13652
13653            // If this range intersects with the preceding highlight, then merge it with
13654            // the preceding highlight. Otherwise insert a new highlight.
13655            let mut merged = false;
13656            if ix > 0 {
13657                let prev_highlight = &mut row_highlights[ix - 1];
13658                if prev_highlight
13659                    .range
13660                    .end
13661                    .cmp(&range.start, &snapshot)
13662                    .is_ge()
13663                {
13664                    ix -= 1;
13665                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13666                        prev_highlight.range.end = range.end;
13667                    }
13668                    merged = true;
13669                    prev_highlight.index = index;
13670                    prev_highlight.color = color;
13671                    prev_highlight.should_autoscroll = should_autoscroll;
13672                }
13673            }
13674
13675            if !merged {
13676                row_highlights.insert(
13677                    ix,
13678                    RowHighlight {
13679                        range: range.clone(),
13680                        index,
13681                        color,
13682                        should_autoscroll,
13683                    },
13684                );
13685            }
13686
13687            // If any of the following highlights intersect with this one, merge them.
13688            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13689                let highlight = &row_highlights[ix];
13690                if next_highlight
13691                    .range
13692                    .start
13693                    .cmp(&highlight.range.end, &snapshot)
13694                    .is_le()
13695                {
13696                    if next_highlight
13697                        .range
13698                        .end
13699                        .cmp(&highlight.range.end, &snapshot)
13700                        .is_gt()
13701                    {
13702                        row_highlights[ix].range.end = next_highlight.range.end;
13703                    }
13704                    row_highlights.remove(ix + 1);
13705                } else {
13706                    break;
13707                }
13708            }
13709        }
13710    }
13711
13712    /// Remove any highlighted row ranges of the given type that intersect the
13713    /// given ranges.
13714    pub fn remove_highlighted_rows<T: 'static>(
13715        &mut self,
13716        ranges_to_remove: Vec<Range<Anchor>>,
13717        cx: &mut Context<Self>,
13718    ) {
13719        let snapshot = self.buffer().read(cx).snapshot(cx);
13720        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13721        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13722        row_highlights.retain(|highlight| {
13723            while let Some(range_to_remove) = ranges_to_remove.peek() {
13724                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13725                    Ordering::Less | Ordering::Equal => {
13726                        ranges_to_remove.next();
13727                    }
13728                    Ordering::Greater => {
13729                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13730                            Ordering::Less | Ordering::Equal => {
13731                                return false;
13732                            }
13733                            Ordering::Greater => break,
13734                        }
13735                    }
13736                }
13737            }
13738
13739            true
13740        })
13741    }
13742
13743    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13744    pub fn clear_row_highlights<T: 'static>(&mut self) {
13745        self.highlighted_rows.remove(&TypeId::of::<T>());
13746    }
13747
13748    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13749    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13750        self.highlighted_rows
13751            .get(&TypeId::of::<T>())
13752            .map_or(&[] as &[_], |vec| vec.as_slice())
13753            .iter()
13754            .map(|highlight| (highlight.range.clone(), highlight.color))
13755    }
13756
13757    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13758    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13759    /// Allows to ignore certain kinds of highlights.
13760    pub fn highlighted_display_rows(
13761        &self,
13762        window: &mut Window,
13763        cx: &mut App,
13764    ) -> BTreeMap<DisplayRow, Background> {
13765        let snapshot = self.snapshot(window, cx);
13766        let mut used_highlight_orders = HashMap::default();
13767        self.highlighted_rows
13768            .iter()
13769            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13770            .fold(
13771                BTreeMap::<DisplayRow, Background>::new(),
13772                |mut unique_rows, highlight| {
13773                    let start = highlight.range.start.to_display_point(&snapshot);
13774                    let end = highlight.range.end.to_display_point(&snapshot);
13775                    let start_row = start.row().0;
13776                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13777                        && end.column() == 0
13778                    {
13779                        end.row().0.saturating_sub(1)
13780                    } else {
13781                        end.row().0
13782                    };
13783                    for row in start_row..=end_row {
13784                        let used_index =
13785                            used_highlight_orders.entry(row).or_insert(highlight.index);
13786                        if highlight.index >= *used_index {
13787                            *used_index = highlight.index;
13788                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13789                        }
13790                    }
13791                    unique_rows
13792                },
13793            )
13794    }
13795
13796    pub fn highlighted_display_row_for_autoscroll(
13797        &self,
13798        snapshot: &DisplaySnapshot,
13799    ) -> Option<DisplayRow> {
13800        self.highlighted_rows
13801            .values()
13802            .flat_map(|highlighted_rows| highlighted_rows.iter())
13803            .filter_map(|highlight| {
13804                if highlight.should_autoscroll {
13805                    Some(highlight.range.start.to_display_point(snapshot).row())
13806                } else {
13807                    None
13808                }
13809            })
13810            .min()
13811    }
13812
13813    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13814        self.highlight_background::<SearchWithinRange>(
13815            ranges,
13816            |colors| colors.editor_document_highlight_read_background,
13817            cx,
13818        )
13819    }
13820
13821    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13822        self.breadcrumb_header = Some(new_header);
13823    }
13824
13825    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13826        self.clear_background_highlights::<SearchWithinRange>(cx);
13827    }
13828
13829    pub fn highlight_background<T: 'static>(
13830        &mut self,
13831        ranges: &[Range<Anchor>],
13832        color_fetcher: fn(&ThemeColors) -> Hsla,
13833        cx: &mut Context<Self>,
13834    ) {
13835        self.background_highlights
13836            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13837        self.scrollbar_marker_state.dirty = true;
13838        cx.notify();
13839    }
13840
13841    pub fn clear_background_highlights<T: 'static>(
13842        &mut self,
13843        cx: &mut Context<Self>,
13844    ) -> Option<BackgroundHighlight> {
13845        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13846        if !text_highlights.1.is_empty() {
13847            self.scrollbar_marker_state.dirty = true;
13848            cx.notify();
13849        }
13850        Some(text_highlights)
13851    }
13852
13853    pub fn highlight_gutter<T: 'static>(
13854        &mut self,
13855        ranges: &[Range<Anchor>],
13856        color_fetcher: fn(&App) -> Hsla,
13857        cx: &mut Context<Self>,
13858    ) {
13859        self.gutter_highlights
13860            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13861        cx.notify();
13862    }
13863
13864    pub fn clear_gutter_highlights<T: 'static>(
13865        &mut self,
13866        cx: &mut Context<Self>,
13867    ) -> Option<GutterHighlight> {
13868        cx.notify();
13869        self.gutter_highlights.remove(&TypeId::of::<T>())
13870    }
13871
13872    #[cfg(feature = "test-support")]
13873    pub fn all_text_background_highlights(
13874        &self,
13875        window: &mut Window,
13876        cx: &mut Context<Self>,
13877    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13878        let snapshot = self.snapshot(window, cx);
13879        let buffer = &snapshot.buffer_snapshot;
13880        let start = buffer.anchor_before(0);
13881        let end = buffer.anchor_after(buffer.len());
13882        let theme = cx.theme().colors();
13883        self.background_highlights_in_range(start..end, &snapshot, theme)
13884    }
13885
13886    #[cfg(feature = "test-support")]
13887    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13888        let snapshot = self.buffer().read(cx).snapshot(cx);
13889
13890        let highlights = self
13891            .background_highlights
13892            .get(&TypeId::of::<items::BufferSearchHighlights>());
13893
13894        if let Some((_color, ranges)) = highlights {
13895            ranges
13896                .iter()
13897                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13898                .collect_vec()
13899        } else {
13900            vec![]
13901        }
13902    }
13903
13904    fn document_highlights_for_position<'a>(
13905        &'a self,
13906        position: Anchor,
13907        buffer: &'a MultiBufferSnapshot,
13908    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13909        let read_highlights = self
13910            .background_highlights
13911            .get(&TypeId::of::<DocumentHighlightRead>())
13912            .map(|h| &h.1);
13913        let write_highlights = self
13914            .background_highlights
13915            .get(&TypeId::of::<DocumentHighlightWrite>())
13916            .map(|h| &h.1);
13917        let left_position = position.bias_left(buffer);
13918        let right_position = position.bias_right(buffer);
13919        read_highlights
13920            .into_iter()
13921            .chain(write_highlights)
13922            .flat_map(move |ranges| {
13923                let start_ix = match ranges.binary_search_by(|probe| {
13924                    let cmp = probe.end.cmp(&left_position, buffer);
13925                    if cmp.is_ge() {
13926                        Ordering::Greater
13927                    } else {
13928                        Ordering::Less
13929                    }
13930                }) {
13931                    Ok(i) | Err(i) => i,
13932                };
13933
13934                ranges[start_ix..]
13935                    .iter()
13936                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13937            })
13938    }
13939
13940    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13941        self.background_highlights
13942            .get(&TypeId::of::<T>())
13943            .map_or(false, |(_, highlights)| !highlights.is_empty())
13944    }
13945
13946    pub fn background_highlights_in_range(
13947        &self,
13948        search_range: Range<Anchor>,
13949        display_snapshot: &DisplaySnapshot,
13950        theme: &ThemeColors,
13951    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13952        let mut results = Vec::new();
13953        for (color_fetcher, ranges) in self.background_highlights.values() {
13954            let color = color_fetcher(theme);
13955            let start_ix = match ranges.binary_search_by(|probe| {
13956                let cmp = probe
13957                    .end
13958                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13959                if cmp.is_gt() {
13960                    Ordering::Greater
13961                } else {
13962                    Ordering::Less
13963                }
13964            }) {
13965                Ok(i) | Err(i) => i,
13966            };
13967            for range in &ranges[start_ix..] {
13968                if range
13969                    .start
13970                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13971                    .is_ge()
13972                {
13973                    break;
13974                }
13975
13976                let start = range.start.to_display_point(display_snapshot);
13977                let end = range.end.to_display_point(display_snapshot);
13978                results.push((start..end, color))
13979            }
13980        }
13981        results
13982    }
13983
13984    pub fn background_highlight_row_ranges<T: 'static>(
13985        &self,
13986        search_range: Range<Anchor>,
13987        display_snapshot: &DisplaySnapshot,
13988        count: usize,
13989    ) -> Vec<RangeInclusive<DisplayPoint>> {
13990        let mut results = Vec::new();
13991        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13992            return vec![];
13993        };
13994
13995        let start_ix = match ranges.binary_search_by(|probe| {
13996            let cmp = probe
13997                .end
13998                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13999            if cmp.is_gt() {
14000                Ordering::Greater
14001            } else {
14002                Ordering::Less
14003            }
14004        }) {
14005            Ok(i) | Err(i) => i,
14006        };
14007        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14008            if let (Some(start_display), Some(end_display)) = (start, end) {
14009                results.push(
14010                    start_display.to_display_point(display_snapshot)
14011                        ..=end_display.to_display_point(display_snapshot),
14012                );
14013            }
14014        };
14015        let mut start_row: Option<Point> = None;
14016        let mut end_row: Option<Point> = None;
14017        if ranges.len() > count {
14018            return Vec::new();
14019        }
14020        for range in &ranges[start_ix..] {
14021            if range
14022                .start
14023                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14024                .is_ge()
14025            {
14026                break;
14027            }
14028            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14029            if let Some(current_row) = &end_row {
14030                if end.row == current_row.row {
14031                    continue;
14032                }
14033            }
14034            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14035            if start_row.is_none() {
14036                assert_eq!(end_row, None);
14037                start_row = Some(start);
14038                end_row = Some(end);
14039                continue;
14040            }
14041            if let Some(current_end) = end_row.as_mut() {
14042                if start.row > current_end.row + 1 {
14043                    push_region(start_row, end_row);
14044                    start_row = Some(start);
14045                    end_row = Some(end);
14046                } else {
14047                    // Merge two hunks.
14048                    *current_end = end;
14049                }
14050            } else {
14051                unreachable!();
14052            }
14053        }
14054        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14055        push_region(start_row, end_row);
14056        results
14057    }
14058
14059    pub fn gutter_highlights_in_range(
14060        &self,
14061        search_range: Range<Anchor>,
14062        display_snapshot: &DisplaySnapshot,
14063        cx: &App,
14064    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14065        let mut results = Vec::new();
14066        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14067            let color = color_fetcher(cx);
14068            let start_ix = match ranges.binary_search_by(|probe| {
14069                let cmp = probe
14070                    .end
14071                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14072                if cmp.is_gt() {
14073                    Ordering::Greater
14074                } else {
14075                    Ordering::Less
14076                }
14077            }) {
14078                Ok(i) | Err(i) => i,
14079            };
14080            for range in &ranges[start_ix..] {
14081                if range
14082                    .start
14083                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14084                    .is_ge()
14085                {
14086                    break;
14087                }
14088
14089                let start = range.start.to_display_point(display_snapshot);
14090                let end = range.end.to_display_point(display_snapshot);
14091                results.push((start..end, color))
14092            }
14093        }
14094        results
14095    }
14096
14097    /// Get the text ranges corresponding to the redaction query
14098    pub fn redacted_ranges(
14099        &self,
14100        search_range: Range<Anchor>,
14101        display_snapshot: &DisplaySnapshot,
14102        cx: &App,
14103    ) -> Vec<Range<DisplayPoint>> {
14104        display_snapshot
14105            .buffer_snapshot
14106            .redacted_ranges(search_range, |file| {
14107                if let Some(file) = file {
14108                    file.is_private()
14109                        && EditorSettings::get(
14110                            Some(SettingsLocation {
14111                                worktree_id: file.worktree_id(cx),
14112                                path: file.path().as_ref(),
14113                            }),
14114                            cx,
14115                        )
14116                        .redact_private_values
14117                } else {
14118                    false
14119                }
14120            })
14121            .map(|range| {
14122                range.start.to_display_point(display_snapshot)
14123                    ..range.end.to_display_point(display_snapshot)
14124            })
14125            .collect()
14126    }
14127
14128    pub fn highlight_text<T: 'static>(
14129        &mut self,
14130        ranges: Vec<Range<Anchor>>,
14131        style: HighlightStyle,
14132        cx: &mut Context<Self>,
14133    ) {
14134        self.display_map.update(cx, |map, _| {
14135            map.highlight_text(TypeId::of::<T>(), ranges, style)
14136        });
14137        cx.notify();
14138    }
14139
14140    pub(crate) fn highlight_inlays<T: 'static>(
14141        &mut self,
14142        highlights: Vec<InlayHighlight>,
14143        style: HighlightStyle,
14144        cx: &mut Context<Self>,
14145    ) {
14146        self.display_map.update(cx, |map, _| {
14147            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14148        });
14149        cx.notify();
14150    }
14151
14152    pub fn text_highlights<'a, T: 'static>(
14153        &'a self,
14154        cx: &'a App,
14155    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14156        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14157    }
14158
14159    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14160        let cleared = self
14161            .display_map
14162            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14163        if cleared {
14164            cx.notify();
14165        }
14166    }
14167
14168    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14169        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14170            && self.focus_handle.is_focused(window)
14171    }
14172
14173    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14174        self.show_cursor_when_unfocused = is_enabled;
14175        cx.notify();
14176    }
14177
14178    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14179        cx.notify();
14180    }
14181
14182    fn on_buffer_event(
14183        &mut self,
14184        multibuffer: &Entity<MultiBuffer>,
14185        event: &multi_buffer::Event,
14186        window: &mut Window,
14187        cx: &mut Context<Self>,
14188    ) {
14189        match event {
14190            multi_buffer::Event::Edited {
14191                singleton_buffer_edited,
14192                edited_buffer: buffer_edited,
14193            } => {
14194                self.scrollbar_marker_state.dirty = true;
14195                self.active_indent_guides_state.dirty = true;
14196                self.refresh_active_diagnostics(cx);
14197                self.refresh_code_actions(window, cx);
14198                if self.has_active_inline_completion() {
14199                    self.update_visible_inline_completion(window, cx);
14200                }
14201                if let Some(buffer) = buffer_edited {
14202                    let buffer_id = buffer.read(cx).remote_id();
14203                    if !self.registered_buffers.contains_key(&buffer_id) {
14204                        if let Some(project) = self.project.as_ref() {
14205                            project.update(cx, |project, cx| {
14206                                self.registered_buffers.insert(
14207                                    buffer_id,
14208                                    project.register_buffer_with_language_servers(&buffer, cx),
14209                                );
14210                            })
14211                        }
14212                    }
14213                }
14214                cx.emit(EditorEvent::BufferEdited);
14215                cx.emit(SearchEvent::MatchesInvalidated);
14216                if *singleton_buffer_edited {
14217                    if let Some(project) = &self.project {
14218                        #[allow(clippy::mutable_key_type)]
14219                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14220                            multibuffer
14221                                .all_buffers()
14222                                .into_iter()
14223                                .filter_map(|buffer| {
14224                                    buffer.update(cx, |buffer, cx| {
14225                                        let language = buffer.language()?;
14226                                        let should_discard = project.update(cx, |project, cx| {
14227                                            project.is_local()
14228                                                && !project.has_language_servers_for(buffer, cx)
14229                                        });
14230                                        should_discard.not().then_some(language.clone())
14231                                    })
14232                                })
14233                                .collect::<HashSet<_>>()
14234                        });
14235                        if !languages_affected.is_empty() {
14236                            self.refresh_inlay_hints(
14237                                InlayHintRefreshReason::BufferEdited(languages_affected),
14238                                cx,
14239                            );
14240                        }
14241                    }
14242                }
14243
14244                let Some(project) = &self.project else { return };
14245                let (telemetry, is_via_ssh) = {
14246                    let project = project.read(cx);
14247                    let telemetry = project.client().telemetry().clone();
14248                    let is_via_ssh = project.is_via_ssh();
14249                    (telemetry, is_via_ssh)
14250                };
14251                refresh_linked_ranges(self, window, cx);
14252                telemetry.log_edit_event("editor", is_via_ssh);
14253            }
14254            multi_buffer::Event::ExcerptsAdded {
14255                buffer,
14256                predecessor,
14257                excerpts,
14258            } => {
14259                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14260                let buffer_id = buffer.read(cx).remote_id();
14261                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14262                    if let Some(project) = &self.project {
14263                        get_uncommitted_diff_for_buffer(
14264                            project,
14265                            [buffer.clone()],
14266                            self.buffer.clone(),
14267                            cx,
14268                        )
14269                        .detach();
14270                    }
14271                }
14272                cx.emit(EditorEvent::ExcerptsAdded {
14273                    buffer: buffer.clone(),
14274                    predecessor: *predecessor,
14275                    excerpts: excerpts.clone(),
14276                });
14277                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14278            }
14279            multi_buffer::Event::ExcerptsRemoved { ids } => {
14280                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14281                let buffer = self.buffer.read(cx);
14282                self.registered_buffers
14283                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14284                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14285            }
14286            multi_buffer::Event::ExcerptsEdited { ids } => {
14287                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14288            }
14289            multi_buffer::Event::ExcerptsExpanded { ids } => {
14290                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14291                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14292            }
14293            multi_buffer::Event::Reparsed(buffer_id) => {
14294                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14295
14296                cx.emit(EditorEvent::Reparsed(*buffer_id));
14297            }
14298            multi_buffer::Event::DiffHunksToggled => {
14299                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14300            }
14301            multi_buffer::Event::LanguageChanged(buffer_id) => {
14302                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14303                cx.emit(EditorEvent::Reparsed(*buffer_id));
14304                cx.notify();
14305            }
14306            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14307            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14308            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14309                cx.emit(EditorEvent::TitleChanged)
14310            }
14311            // multi_buffer::Event::DiffBaseChanged => {
14312            //     self.scrollbar_marker_state.dirty = true;
14313            //     cx.emit(EditorEvent::DiffBaseChanged);
14314            //     cx.notify();
14315            // }
14316            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14317            multi_buffer::Event::DiagnosticsUpdated => {
14318                self.refresh_active_diagnostics(cx);
14319                self.scrollbar_marker_state.dirty = true;
14320                cx.notify();
14321            }
14322            _ => {}
14323        };
14324    }
14325
14326    fn on_display_map_changed(
14327        &mut self,
14328        _: Entity<DisplayMap>,
14329        _: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        cx.notify();
14333    }
14334
14335    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14336        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14337        self.refresh_inline_completion(true, false, window, cx);
14338        self.refresh_inlay_hints(
14339            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14340                self.selections.newest_anchor().head(),
14341                &self.buffer.read(cx).snapshot(cx),
14342                cx,
14343            )),
14344            cx,
14345        );
14346
14347        let old_cursor_shape = self.cursor_shape;
14348
14349        {
14350            let editor_settings = EditorSettings::get_global(cx);
14351            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14352            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14353            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14354        }
14355
14356        if old_cursor_shape != self.cursor_shape {
14357            cx.emit(EditorEvent::CursorShapeChanged);
14358        }
14359
14360        let project_settings = ProjectSettings::get_global(cx);
14361        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14362
14363        if self.mode == EditorMode::Full {
14364            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14365            if self.git_blame_inline_enabled != inline_blame_enabled {
14366                self.toggle_git_blame_inline_internal(false, window, cx);
14367            }
14368        }
14369
14370        cx.notify();
14371    }
14372
14373    pub fn set_searchable(&mut self, searchable: bool) {
14374        self.searchable = searchable;
14375    }
14376
14377    pub fn searchable(&self) -> bool {
14378        self.searchable
14379    }
14380
14381    fn open_proposed_changes_editor(
14382        &mut self,
14383        _: &OpenProposedChangesEditor,
14384        window: &mut Window,
14385        cx: &mut Context<Self>,
14386    ) {
14387        let Some(workspace) = self.workspace() else {
14388            cx.propagate();
14389            return;
14390        };
14391
14392        let selections = self.selections.all::<usize>(cx);
14393        let multi_buffer = self.buffer.read(cx);
14394        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14395        let mut new_selections_by_buffer = HashMap::default();
14396        for selection in selections {
14397            for (buffer, range, _) in
14398                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14399            {
14400                let mut range = range.to_point(buffer);
14401                range.start.column = 0;
14402                range.end.column = buffer.line_len(range.end.row);
14403                new_selections_by_buffer
14404                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14405                    .or_insert(Vec::new())
14406                    .push(range)
14407            }
14408        }
14409
14410        let proposed_changes_buffers = new_selections_by_buffer
14411            .into_iter()
14412            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14413            .collect::<Vec<_>>();
14414        let proposed_changes_editor = cx.new(|cx| {
14415            ProposedChangesEditor::new(
14416                "Proposed changes",
14417                proposed_changes_buffers,
14418                self.project.clone(),
14419                window,
14420                cx,
14421            )
14422        });
14423
14424        window.defer(cx, move |window, cx| {
14425            workspace.update(cx, |workspace, cx| {
14426                workspace.active_pane().update(cx, |pane, cx| {
14427                    pane.add_item(
14428                        Box::new(proposed_changes_editor),
14429                        true,
14430                        true,
14431                        None,
14432                        window,
14433                        cx,
14434                    );
14435                });
14436            });
14437        });
14438    }
14439
14440    pub fn open_excerpts_in_split(
14441        &mut self,
14442        _: &OpenExcerptsSplit,
14443        window: &mut Window,
14444        cx: &mut Context<Self>,
14445    ) {
14446        self.open_excerpts_common(None, true, window, cx)
14447    }
14448
14449    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14450        self.open_excerpts_common(None, false, window, cx)
14451    }
14452
14453    fn open_excerpts_common(
14454        &mut self,
14455        jump_data: Option<JumpData>,
14456        split: bool,
14457        window: &mut Window,
14458        cx: &mut Context<Self>,
14459    ) {
14460        let Some(workspace) = self.workspace() else {
14461            cx.propagate();
14462            return;
14463        };
14464
14465        if self.buffer.read(cx).is_singleton() {
14466            cx.propagate();
14467            return;
14468        }
14469
14470        let mut new_selections_by_buffer = HashMap::default();
14471        match &jump_data {
14472            Some(JumpData::MultiBufferPoint {
14473                excerpt_id,
14474                position,
14475                anchor,
14476                line_offset_from_top,
14477            }) => {
14478                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14479                if let Some(buffer) = multi_buffer_snapshot
14480                    .buffer_id_for_excerpt(*excerpt_id)
14481                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14482                {
14483                    let buffer_snapshot = buffer.read(cx).snapshot();
14484                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14485                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14486                    } else {
14487                        buffer_snapshot.clip_point(*position, Bias::Left)
14488                    };
14489                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14490                    new_selections_by_buffer.insert(
14491                        buffer,
14492                        (
14493                            vec![jump_to_offset..jump_to_offset],
14494                            Some(*line_offset_from_top),
14495                        ),
14496                    );
14497                }
14498            }
14499            Some(JumpData::MultiBufferRow {
14500                row,
14501                line_offset_from_top,
14502            }) => {
14503                let point = MultiBufferPoint::new(row.0, 0);
14504                if let Some((buffer, buffer_point, _)) =
14505                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14506                {
14507                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14508                    new_selections_by_buffer
14509                        .entry(buffer)
14510                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14511                        .0
14512                        .push(buffer_offset..buffer_offset)
14513                }
14514            }
14515            None => {
14516                let selections = self.selections.all::<usize>(cx);
14517                let multi_buffer = self.buffer.read(cx);
14518                for selection in selections {
14519                    for (buffer, mut range, _) in multi_buffer
14520                        .snapshot(cx)
14521                        .range_to_buffer_ranges(selection.range())
14522                    {
14523                        // When editing branch buffers, jump to the corresponding location
14524                        // in their base buffer.
14525                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14526                        let buffer = buffer_handle.read(cx);
14527                        if let Some(base_buffer) = buffer.base_buffer() {
14528                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14529                            buffer_handle = base_buffer;
14530                        }
14531
14532                        if selection.reversed {
14533                            mem::swap(&mut range.start, &mut range.end);
14534                        }
14535                        new_selections_by_buffer
14536                            .entry(buffer_handle)
14537                            .or_insert((Vec::new(), None))
14538                            .0
14539                            .push(range)
14540                    }
14541                }
14542            }
14543        }
14544
14545        if new_selections_by_buffer.is_empty() {
14546            return;
14547        }
14548
14549        // We defer the pane interaction because we ourselves are a workspace item
14550        // and activating a new item causes the pane to call a method on us reentrantly,
14551        // which panics if we're on the stack.
14552        window.defer(cx, move |window, cx| {
14553            workspace.update(cx, |workspace, cx| {
14554                let pane = if split {
14555                    workspace.adjacent_pane(window, cx)
14556                } else {
14557                    workspace.active_pane().clone()
14558                };
14559
14560                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14561                    let editor = buffer
14562                        .read(cx)
14563                        .file()
14564                        .is_none()
14565                        .then(|| {
14566                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14567                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14568                            // Instead, we try to activate the existing editor in the pane first.
14569                            let (editor, pane_item_index) =
14570                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14571                                    let editor = item.downcast::<Editor>()?;
14572                                    let singleton_buffer =
14573                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14574                                    if singleton_buffer == buffer {
14575                                        Some((editor, i))
14576                                    } else {
14577                                        None
14578                                    }
14579                                })?;
14580                            pane.update(cx, |pane, cx| {
14581                                pane.activate_item(pane_item_index, true, true, window, cx)
14582                            });
14583                            Some(editor)
14584                        })
14585                        .flatten()
14586                        .unwrap_or_else(|| {
14587                            workspace.open_project_item::<Self>(
14588                                pane.clone(),
14589                                buffer,
14590                                true,
14591                                true,
14592                                window,
14593                                cx,
14594                            )
14595                        });
14596
14597                    editor.update(cx, |editor, cx| {
14598                        let autoscroll = match scroll_offset {
14599                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14600                            None => Autoscroll::newest(),
14601                        };
14602                        let nav_history = editor.nav_history.take();
14603                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14604                            s.select_ranges(ranges);
14605                        });
14606                        editor.nav_history = nav_history;
14607                    });
14608                }
14609            })
14610        });
14611    }
14612
14613    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14614        let snapshot = self.buffer.read(cx).read(cx);
14615        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14616        Some(
14617            ranges
14618                .iter()
14619                .map(move |range| {
14620                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14621                })
14622                .collect(),
14623        )
14624    }
14625
14626    fn selection_replacement_ranges(
14627        &self,
14628        range: Range<OffsetUtf16>,
14629        cx: &mut App,
14630    ) -> Vec<Range<OffsetUtf16>> {
14631        let selections = self.selections.all::<OffsetUtf16>(cx);
14632        let newest_selection = selections
14633            .iter()
14634            .max_by_key(|selection| selection.id)
14635            .unwrap();
14636        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14637        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14638        let snapshot = self.buffer.read(cx).read(cx);
14639        selections
14640            .into_iter()
14641            .map(|mut selection| {
14642                selection.start.0 =
14643                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14644                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14645                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14646                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14647            })
14648            .collect()
14649    }
14650
14651    fn report_editor_event(
14652        &self,
14653        event_type: &'static str,
14654        file_extension: Option<String>,
14655        cx: &App,
14656    ) {
14657        if cfg!(any(test, feature = "test-support")) {
14658            return;
14659        }
14660
14661        let Some(project) = &self.project else { return };
14662
14663        // If None, we are in a file without an extension
14664        let file = self
14665            .buffer
14666            .read(cx)
14667            .as_singleton()
14668            .and_then(|b| b.read(cx).file());
14669        let file_extension = file_extension.or(file
14670            .as_ref()
14671            .and_then(|file| Path::new(file.file_name(cx)).extension())
14672            .and_then(|e| e.to_str())
14673            .map(|a| a.to_string()));
14674
14675        let vim_mode = cx
14676            .global::<SettingsStore>()
14677            .raw_user_settings()
14678            .get("vim_mode")
14679            == Some(&serde_json::Value::Bool(true));
14680
14681        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14682        let copilot_enabled = edit_predictions_provider
14683            == language::language_settings::EditPredictionProvider::Copilot;
14684        let copilot_enabled_for_language = self
14685            .buffer
14686            .read(cx)
14687            .settings_at(0, cx)
14688            .show_edit_predictions;
14689
14690        let project = project.read(cx);
14691        telemetry::event!(
14692            event_type,
14693            file_extension,
14694            vim_mode,
14695            copilot_enabled,
14696            copilot_enabled_for_language,
14697            edit_predictions_provider,
14698            is_via_ssh = project.is_via_ssh(),
14699        );
14700    }
14701
14702    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14703    /// with each line being an array of {text, highlight} objects.
14704    fn copy_highlight_json(
14705        &mut self,
14706        _: &CopyHighlightJson,
14707        window: &mut Window,
14708        cx: &mut Context<Self>,
14709    ) {
14710        #[derive(Serialize)]
14711        struct Chunk<'a> {
14712            text: String,
14713            highlight: Option<&'a str>,
14714        }
14715
14716        let snapshot = self.buffer.read(cx).snapshot(cx);
14717        let range = self
14718            .selected_text_range(false, window, cx)
14719            .and_then(|selection| {
14720                if selection.range.is_empty() {
14721                    None
14722                } else {
14723                    Some(selection.range)
14724                }
14725            })
14726            .unwrap_or_else(|| 0..snapshot.len());
14727
14728        let chunks = snapshot.chunks(range, true);
14729        let mut lines = Vec::new();
14730        let mut line: VecDeque<Chunk> = VecDeque::new();
14731
14732        let Some(style) = self.style.as_ref() else {
14733            return;
14734        };
14735
14736        for chunk in chunks {
14737            let highlight = chunk
14738                .syntax_highlight_id
14739                .and_then(|id| id.name(&style.syntax));
14740            let mut chunk_lines = chunk.text.split('\n').peekable();
14741            while let Some(text) = chunk_lines.next() {
14742                let mut merged_with_last_token = false;
14743                if let Some(last_token) = line.back_mut() {
14744                    if last_token.highlight == highlight {
14745                        last_token.text.push_str(text);
14746                        merged_with_last_token = true;
14747                    }
14748                }
14749
14750                if !merged_with_last_token {
14751                    line.push_back(Chunk {
14752                        text: text.into(),
14753                        highlight,
14754                    });
14755                }
14756
14757                if chunk_lines.peek().is_some() {
14758                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14759                        line.pop_front();
14760                    }
14761                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14762                        line.pop_back();
14763                    }
14764
14765                    lines.push(mem::take(&mut line));
14766                }
14767            }
14768        }
14769
14770        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14771            return;
14772        };
14773        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14774    }
14775
14776    pub fn open_context_menu(
14777        &mut self,
14778        _: &OpenContextMenu,
14779        window: &mut Window,
14780        cx: &mut Context<Self>,
14781    ) {
14782        self.request_autoscroll(Autoscroll::newest(), cx);
14783        let position = self.selections.newest_display(cx).start;
14784        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14785    }
14786
14787    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14788        &self.inlay_hint_cache
14789    }
14790
14791    pub fn replay_insert_event(
14792        &mut self,
14793        text: &str,
14794        relative_utf16_range: Option<Range<isize>>,
14795        window: &mut Window,
14796        cx: &mut Context<Self>,
14797    ) {
14798        if !self.input_enabled {
14799            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14800            return;
14801        }
14802        if let Some(relative_utf16_range) = relative_utf16_range {
14803            let selections = self.selections.all::<OffsetUtf16>(cx);
14804            self.change_selections(None, window, cx, |s| {
14805                let new_ranges = selections.into_iter().map(|range| {
14806                    let start = OffsetUtf16(
14807                        range
14808                            .head()
14809                            .0
14810                            .saturating_add_signed(relative_utf16_range.start),
14811                    );
14812                    let end = OffsetUtf16(
14813                        range
14814                            .head()
14815                            .0
14816                            .saturating_add_signed(relative_utf16_range.end),
14817                    );
14818                    start..end
14819                });
14820                s.select_ranges(new_ranges);
14821            });
14822        }
14823
14824        self.handle_input(text, window, cx);
14825    }
14826
14827    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14828        let Some(provider) = self.semantics_provider.as_ref() else {
14829            return false;
14830        };
14831
14832        let mut supports = false;
14833        self.buffer().update(cx, |this, cx| {
14834            this.for_each_buffer(|buffer| {
14835                supports |= provider.supports_inlay_hints(buffer, cx);
14836            });
14837        });
14838
14839        supports
14840    }
14841
14842    pub fn is_focused(&self, window: &Window) -> bool {
14843        self.focus_handle.is_focused(window)
14844    }
14845
14846    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14847        cx.emit(EditorEvent::Focused);
14848
14849        if let Some(descendant) = self
14850            .last_focused_descendant
14851            .take()
14852            .and_then(|descendant| descendant.upgrade())
14853        {
14854            window.focus(&descendant);
14855        } else {
14856            if let Some(blame) = self.blame.as_ref() {
14857                blame.update(cx, GitBlame::focus)
14858            }
14859
14860            self.blink_manager.update(cx, BlinkManager::enable);
14861            self.show_cursor_names(window, cx);
14862            self.buffer.update(cx, |buffer, cx| {
14863                buffer.finalize_last_transaction(cx);
14864                if self.leader_peer_id.is_none() {
14865                    buffer.set_active_selections(
14866                        &self.selections.disjoint_anchors(),
14867                        self.selections.line_mode,
14868                        self.cursor_shape,
14869                        cx,
14870                    );
14871                }
14872            });
14873        }
14874    }
14875
14876    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14877        cx.emit(EditorEvent::FocusedIn)
14878    }
14879
14880    fn handle_focus_out(
14881        &mut self,
14882        event: FocusOutEvent,
14883        _window: &mut Window,
14884        _cx: &mut Context<Self>,
14885    ) {
14886        if event.blurred != self.focus_handle {
14887            self.last_focused_descendant = Some(event.blurred);
14888        }
14889    }
14890
14891    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14892        self.blink_manager.update(cx, BlinkManager::disable);
14893        self.buffer
14894            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14895
14896        if let Some(blame) = self.blame.as_ref() {
14897            blame.update(cx, GitBlame::blur)
14898        }
14899        if !self.hover_state.focused(window, cx) {
14900            hide_hover(self, cx);
14901        }
14902        if !self
14903            .context_menu
14904            .borrow()
14905            .as_ref()
14906            .is_some_and(|context_menu| context_menu.focused(window, cx))
14907        {
14908            self.hide_context_menu(window, cx);
14909        }
14910        self.discard_inline_completion(false, cx);
14911        cx.emit(EditorEvent::Blurred);
14912        cx.notify();
14913    }
14914
14915    pub fn register_action<A: Action>(
14916        &mut self,
14917        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14918    ) -> Subscription {
14919        let id = self.next_editor_action_id.post_inc();
14920        let listener = Arc::new(listener);
14921        self.editor_actions.borrow_mut().insert(
14922            id,
14923            Box::new(move |window, _| {
14924                let listener = listener.clone();
14925                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14926                    let action = action.downcast_ref().unwrap();
14927                    if phase == DispatchPhase::Bubble {
14928                        listener(action, window, cx)
14929                    }
14930                })
14931            }),
14932        );
14933
14934        let editor_actions = self.editor_actions.clone();
14935        Subscription::new(move || {
14936            editor_actions.borrow_mut().remove(&id);
14937        })
14938    }
14939
14940    pub fn file_header_size(&self) -> u32 {
14941        FILE_HEADER_HEIGHT
14942    }
14943
14944    pub fn revert(
14945        &mut self,
14946        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14947        window: &mut Window,
14948        cx: &mut Context<Self>,
14949    ) {
14950        self.buffer().update(cx, |multi_buffer, cx| {
14951            for (buffer_id, changes) in revert_changes {
14952                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14953                    buffer.update(cx, |buffer, cx| {
14954                        buffer.edit(
14955                            changes.into_iter().map(|(range, text)| {
14956                                (range, text.to_string().map(Arc::<str>::from))
14957                            }),
14958                            None,
14959                            cx,
14960                        );
14961                    });
14962                }
14963            }
14964        });
14965        self.change_selections(None, window, cx, |selections| selections.refresh());
14966    }
14967
14968    pub fn to_pixel_point(
14969        &self,
14970        source: multi_buffer::Anchor,
14971        editor_snapshot: &EditorSnapshot,
14972        window: &mut Window,
14973    ) -> Option<gpui::Point<Pixels>> {
14974        let source_point = source.to_display_point(editor_snapshot);
14975        self.display_to_pixel_point(source_point, editor_snapshot, window)
14976    }
14977
14978    pub fn display_to_pixel_point(
14979        &self,
14980        source: DisplayPoint,
14981        editor_snapshot: &EditorSnapshot,
14982        window: &mut Window,
14983    ) -> Option<gpui::Point<Pixels>> {
14984        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14985        let text_layout_details = self.text_layout_details(window);
14986        let scroll_top = text_layout_details
14987            .scroll_anchor
14988            .scroll_position(editor_snapshot)
14989            .y;
14990
14991        if source.row().as_f32() < scroll_top.floor() {
14992            return None;
14993        }
14994        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14995        let source_y = line_height * (source.row().as_f32() - scroll_top);
14996        Some(gpui::Point::new(source_x, source_y))
14997    }
14998
14999    pub fn has_visible_completions_menu(&self) -> bool {
15000        !self.edit_prediction_preview_is_active()
15001            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15002                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15003            })
15004    }
15005
15006    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15007        self.addons
15008            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15009    }
15010
15011    pub fn unregister_addon<T: Addon>(&mut self) {
15012        self.addons.remove(&std::any::TypeId::of::<T>());
15013    }
15014
15015    pub fn addon<T: Addon>(&self) -> Option<&T> {
15016        let type_id = std::any::TypeId::of::<T>();
15017        self.addons
15018            .get(&type_id)
15019            .and_then(|item| item.to_any().downcast_ref::<T>())
15020    }
15021
15022    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15023        let text_layout_details = self.text_layout_details(window);
15024        let style = &text_layout_details.editor_style;
15025        let font_id = window.text_system().resolve_font(&style.text.font());
15026        let font_size = style.text.font_size.to_pixels(window.rem_size());
15027        let line_height = style.text.line_height_in_pixels(window.rem_size());
15028        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15029
15030        gpui::Size::new(em_width, line_height)
15031    }
15032
15033    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15034        self.load_diff_task.clone()
15035    }
15036
15037    fn read_selections_from_db(
15038        &mut self,
15039        item_id: u64,
15040        workspace_id: WorkspaceId,
15041        window: &mut Window,
15042        cx: &mut Context<Editor>,
15043    ) {
15044        if !self.is_singleton(cx)
15045            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15046        {
15047            return;
15048        }
15049        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15050            return;
15051        };
15052        if selections.is_empty() {
15053            return;
15054        }
15055
15056        let snapshot = self.buffer.read(cx).snapshot(cx);
15057        self.change_selections(None, window, cx, |s| {
15058            s.select_ranges(selections.into_iter().map(|(start, end)| {
15059                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15060            }));
15061        });
15062    }
15063}
15064
15065fn insert_extra_newline_brackets(
15066    buffer: &MultiBufferSnapshot,
15067    range: Range<usize>,
15068    language: &language::LanguageScope,
15069) -> bool {
15070    let leading_whitespace_len = buffer
15071        .reversed_chars_at(range.start)
15072        .take_while(|c| c.is_whitespace() && *c != '\n')
15073        .map(|c| c.len_utf8())
15074        .sum::<usize>();
15075    let trailing_whitespace_len = buffer
15076        .chars_at(range.end)
15077        .take_while(|c| c.is_whitespace() && *c != '\n')
15078        .map(|c| c.len_utf8())
15079        .sum::<usize>();
15080    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15081
15082    language.brackets().any(|(pair, enabled)| {
15083        let pair_start = pair.start.trim_end();
15084        let pair_end = pair.end.trim_start();
15085
15086        enabled
15087            && pair.newline
15088            && buffer.contains_str_at(range.end, pair_end)
15089            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15090    })
15091}
15092
15093fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15094    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15095        [(buffer, range, _)] => (*buffer, range.clone()),
15096        _ => return false,
15097    };
15098    let pair = {
15099        let mut result: Option<BracketMatch> = None;
15100
15101        for pair in buffer
15102            .all_bracket_ranges(range.clone())
15103            .filter(move |pair| {
15104                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15105            })
15106        {
15107            let len = pair.close_range.end - pair.open_range.start;
15108
15109            if let Some(existing) = &result {
15110                let existing_len = existing.close_range.end - existing.open_range.start;
15111                if len > existing_len {
15112                    continue;
15113                }
15114            }
15115
15116            result = Some(pair);
15117        }
15118
15119        result
15120    };
15121    let Some(pair) = pair else {
15122        return false;
15123    };
15124    pair.newline_only
15125        && buffer
15126            .chars_for_range(pair.open_range.end..range.start)
15127            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15128            .all(|c| c.is_whitespace() && c != '\n')
15129}
15130
15131fn get_uncommitted_diff_for_buffer(
15132    project: &Entity<Project>,
15133    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15134    buffer: Entity<MultiBuffer>,
15135    cx: &mut App,
15136) -> Task<()> {
15137    let mut tasks = Vec::new();
15138    project.update(cx, |project, cx| {
15139        for buffer in buffers {
15140            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15141        }
15142    });
15143    cx.spawn(|mut cx| async move {
15144        let diffs = futures::future::join_all(tasks).await;
15145        buffer
15146            .update(&mut cx, |buffer, cx| {
15147                for diff in diffs.into_iter().flatten() {
15148                    buffer.add_diff(diff, cx);
15149                }
15150            })
15151            .ok();
15152    })
15153}
15154
15155fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15156    let tab_size = tab_size.get() as usize;
15157    let mut width = offset;
15158
15159    for ch in text.chars() {
15160        width += if ch == '\t' {
15161            tab_size - (width % tab_size)
15162        } else {
15163            1
15164        };
15165    }
15166
15167    width - offset
15168}
15169
15170#[cfg(test)]
15171mod tests {
15172    use super::*;
15173
15174    #[test]
15175    fn test_string_size_with_expanded_tabs() {
15176        let nz = |val| NonZeroU32::new(val).unwrap();
15177        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15178        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15179        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15180        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15181        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15182        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15183        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15184        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15185    }
15186}
15187
15188/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15189struct WordBreakingTokenizer<'a> {
15190    input: &'a str,
15191}
15192
15193impl<'a> WordBreakingTokenizer<'a> {
15194    fn new(input: &'a str) -> Self {
15195        Self { input }
15196    }
15197}
15198
15199fn is_char_ideographic(ch: char) -> bool {
15200    use unicode_script::Script::*;
15201    use unicode_script::UnicodeScript;
15202    matches!(ch.script(), Han | Tangut | Yi)
15203}
15204
15205fn is_grapheme_ideographic(text: &str) -> bool {
15206    text.chars().any(is_char_ideographic)
15207}
15208
15209fn is_grapheme_whitespace(text: &str) -> bool {
15210    text.chars().any(|x| x.is_whitespace())
15211}
15212
15213fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15214    text.chars().next().map_or(false, |ch| {
15215        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15216    })
15217}
15218
15219#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15220struct WordBreakToken<'a> {
15221    token: &'a str,
15222    grapheme_len: usize,
15223    is_whitespace: bool,
15224}
15225
15226impl<'a> Iterator for WordBreakingTokenizer<'a> {
15227    /// Yields a span, the count of graphemes in the token, and whether it was
15228    /// whitespace. Note that it also breaks at word boundaries.
15229    type Item = WordBreakToken<'a>;
15230
15231    fn next(&mut self) -> Option<Self::Item> {
15232        use unicode_segmentation::UnicodeSegmentation;
15233        if self.input.is_empty() {
15234            return None;
15235        }
15236
15237        let mut iter = self.input.graphemes(true).peekable();
15238        let mut offset = 0;
15239        let mut graphemes = 0;
15240        if let Some(first_grapheme) = iter.next() {
15241            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15242            offset += first_grapheme.len();
15243            graphemes += 1;
15244            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15245                if let Some(grapheme) = iter.peek().copied() {
15246                    if should_stay_with_preceding_ideograph(grapheme) {
15247                        offset += grapheme.len();
15248                        graphemes += 1;
15249                    }
15250                }
15251            } else {
15252                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15253                let mut next_word_bound = words.peek().copied();
15254                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15255                    next_word_bound = words.next();
15256                }
15257                while let Some(grapheme) = iter.peek().copied() {
15258                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15259                        break;
15260                    };
15261                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15262                        break;
15263                    };
15264                    offset += grapheme.len();
15265                    graphemes += 1;
15266                    iter.next();
15267                }
15268            }
15269            let token = &self.input[..offset];
15270            self.input = &self.input[offset..];
15271            if is_whitespace {
15272                Some(WordBreakToken {
15273                    token: " ",
15274                    grapheme_len: 1,
15275                    is_whitespace: true,
15276                })
15277            } else {
15278                Some(WordBreakToken {
15279                    token,
15280                    grapheme_len: graphemes,
15281                    is_whitespace: false,
15282                })
15283            }
15284        } else {
15285            None
15286        }
15287    }
15288}
15289
15290#[test]
15291fn test_word_breaking_tokenizer() {
15292    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15293        ("", &[]),
15294        ("  ", &[(" ", 1, true)]),
15295        ("Ʒ", &[("Ʒ", 1, false)]),
15296        ("Ǽ", &[("Ǽ", 1, false)]),
15297        ("", &[("", 1, false)]),
15298        ("⋑⋑", &[("⋑⋑", 2, false)]),
15299        (
15300            "原理,进而",
15301            &[
15302                ("", 1, false),
15303                ("理,", 2, false),
15304                ("", 1, false),
15305                ("", 1, false),
15306            ],
15307        ),
15308        (
15309            "hello world",
15310            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15311        ),
15312        (
15313            "hello, world",
15314            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15315        ),
15316        (
15317            "  hello world",
15318            &[
15319                (" ", 1, true),
15320                ("hello", 5, false),
15321                (" ", 1, true),
15322                ("world", 5, false),
15323            ],
15324        ),
15325        (
15326            "这是什么 \n 钢笔",
15327            &[
15328                ("", 1, false),
15329                ("", 1, false),
15330                ("", 1, false),
15331                ("", 1, false),
15332                (" ", 1, true),
15333                ("", 1, false),
15334                ("", 1, false),
15335            ],
15336        ),
15337        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15338    ];
15339
15340    for (input, result) in tests {
15341        assert_eq!(
15342            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15343            result
15344                .iter()
15345                .copied()
15346                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15347                    token,
15348                    grapheme_len,
15349                    is_whitespace,
15350                })
15351                .collect::<Vec<_>>()
15352        );
15353    }
15354}
15355
15356fn wrap_with_prefix(
15357    line_prefix: String,
15358    unwrapped_text: String,
15359    wrap_column: usize,
15360    tab_size: NonZeroU32,
15361) -> String {
15362    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15363    let mut wrapped_text = String::new();
15364    let mut current_line = line_prefix.clone();
15365
15366    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15367    let mut current_line_len = line_prefix_len;
15368    for WordBreakToken {
15369        token,
15370        grapheme_len,
15371        is_whitespace,
15372    } in tokenizer
15373    {
15374        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15375            wrapped_text.push_str(current_line.trim_end());
15376            wrapped_text.push('\n');
15377            current_line.truncate(line_prefix.len());
15378            current_line_len = line_prefix_len;
15379            if !is_whitespace {
15380                current_line.push_str(token);
15381                current_line_len += grapheme_len;
15382            }
15383        } else if !is_whitespace {
15384            current_line.push_str(token);
15385            current_line_len += grapheme_len;
15386        } else if current_line_len != line_prefix_len {
15387            current_line.push(' ');
15388            current_line_len += 1;
15389        }
15390    }
15391
15392    if !current_line.is_empty() {
15393        wrapped_text.push_str(&current_line);
15394    }
15395    wrapped_text
15396}
15397
15398#[test]
15399fn test_wrap_with_prefix() {
15400    assert_eq!(
15401        wrap_with_prefix(
15402            "# ".to_string(),
15403            "abcdefg".to_string(),
15404            4,
15405            NonZeroU32::new(4).unwrap()
15406        ),
15407        "# abcdefg"
15408    );
15409    assert_eq!(
15410        wrap_with_prefix(
15411            "".to_string(),
15412            "\thello world".to_string(),
15413            8,
15414            NonZeroU32::new(4).unwrap()
15415        ),
15416        "hello\nworld"
15417    );
15418    assert_eq!(
15419        wrap_with_prefix(
15420            "// ".to_string(),
15421            "xx \nyy zz aa bb cc".to_string(),
15422            12,
15423            NonZeroU32::new(4).unwrap()
15424        ),
15425        "// xx yy zz\n// aa bb cc"
15426    );
15427    assert_eq!(
15428        wrap_with_prefix(
15429            String::new(),
15430            "这是什么 \n 钢笔".to_string(),
15431            3,
15432            NonZeroU32::new(4).unwrap()
15433        ),
15434        "这是什\n么 钢\n"
15435    );
15436}
15437
15438pub trait CollaborationHub {
15439    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15440    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15441    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15442}
15443
15444impl CollaborationHub for Entity<Project> {
15445    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15446        self.read(cx).collaborators()
15447    }
15448
15449    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15450        self.read(cx).user_store().read(cx).participant_indices()
15451    }
15452
15453    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15454        let this = self.read(cx);
15455        let user_ids = this.collaborators().values().map(|c| c.user_id);
15456        this.user_store().read_with(cx, |user_store, cx| {
15457            user_store.participant_names(user_ids, cx)
15458        })
15459    }
15460}
15461
15462pub trait SemanticsProvider {
15463    fn hover(
15464        &self,
15465        buffer: &Entity<Buffer>,
15466        position: text::Anchor,
15467        cx: &mut App,
15468    ) -> Option<Task<Vec<project::Hover>>>;
15469
15470    fn inlay_hints(
15471        &self,
15472        buffer_handle: Entity<Buffer>,
15473        range: Range<text::Anchor>,
15474        cx: &mut App,
15475    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15476
15477    fn resolve_inlay_hint(
15478        &self,
15479        hint: InlayHint,
15480        buffer_handle: Entity<Buffer>,
15481        server_id: LanguageServerId,
15482        cx: &mut App,
15483    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15484
15485    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15486
15487    fn document_highlights(
15488        &self,
15489        buffer: &Entity<Buffer>,
15490        position: text::Anchor,
15491        cx: &mut App,
15492    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15493
15494    fn definitions(
15495        &self,
15496        buffer: &Entity<Buffer>,
15497        position: text::Anchor,
15498        kind: GotoDefinitionKind,
15499        cx: &mut App,
15500    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15501
15502    fn range_for_rename(
15503        &self,
15504        buffer: &Entity<Buffer>,
15505        position: text::Anchor,
15506        cx: &mut App,
15507    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15508
15509    fn perform_rename(
15510        &self,
15511        buffer: &Entity<Buffer>,
15512        position: text::Anchor,
15513        new_name: String,
15514        cx: &mut App,
15515    ) -> Option<Task<Result<ProjectTransaction>>>;
15516}
15517
15518pub trait CompletionProvider {
15519    fn completions(
15520        &self,
15521        buffer: &Entity<Buffer>,
15522        buffer_position: text::Anchor,
15523        trigger: CompletionContext,
15524        window: &mut Window,
15525        cx: &mut Context<Editor>,
15526    ) -> Task<Result<Vec<Completion>>>;
15527
15528    fn resolve_completions(
15529        &self,
15530        buffer: Entity<Buffer>,
15531        completion_indices: Vec<usize>,
15532        completions: Rc<RefCell<Box<[Completion]>>>,
15533        cx: &mut Context<Editor>,
15534    ) -> Task<Result<bool>>;
15535
15536    fn apply_additional_edits_for_completion(
15537        &self,
15538        _buffer: Entity<Buffer>,
15539        _completions: Rc<RefCell<Box<[Completion]>>>,
15540        _completion_index: usize,
15541        _push_to_history: bool,
15542        _cx: &mut Context<Editor>,
15543    ) -> Task<Result<Option<language::Transaction>>> {
15544        Task::ready(Ok(None))
15545    }
15546
15547    fn is_completion_trigger(
15548        &self,
15549        buffer: &Entity<Buffer>,
15550        position: language::Anchor,
15551        text: &str,
15552        trigger_in_words: bool,
15553        cx: &mut Context<Editor>,
15554    ) -> bool;
15555
15556    fn sort_completions(&self) -> bool {
15557        true
15558    }
15559}
15560
15561pub trait CodeActionProvider {
15562    fn id(&self) -> Arc<str>;
15563
15564    fn code_actions(
15565        &self,
15566        buffer: &Entity<Buffer>,
15567        range: Range<text::Anchor>,
15568        window: &mut Window,
15569        cx: &mut App,
15570    ) -> Task<Result<Vec<CodeAction>>>;
15571
15572    fn apply_code_action(
15573        &self,
15574        buffer_handle: Entity<Buffer>,
15575        action: CodeAction,
15576        excerpt_id: ExcerptId,
15577        push_to_history: bool,
15578        window: &mut Window,
15579        cx: &mut App,
15580    ) -> Task<Result<ProjectTransaction>>;
15581}
15582
15583impl CodeActionProvider for Entity<Project> {
15584    fn id(&self) -> Arc<str> {
15585        "project".into()
15586    }
15587
15588    fn code_actions(
15589        &self,
15590        buffer: &Entity<Buffer>,
15591        range: Range<text::Anchor>,
15592        _window: &mut Window,
15593        cx: &mut App,
15594    ) -> Task<Result<Vec<CodeAction>>> {
15595        self.update(cx, |project, cx| {
15596            project.code_actions(buffer, range, None, cx)
15597        })
15598    }
15599
15600    fn apply_code_action(
15601        &self,
15602        buffer_handle: Entity<Buffer>,
15603        action: CodeAction,
15604        _excerpt_id: ExcerptId,
15605        push_to_history: bool,
15606        _window: &mut Window,
15607        cx: &mut App,
15608    ) -> Task<Result<ProjectTransaction>> {
15609        self.update(cx, |project, cx| {
15610            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15611        })
15612    }
15613}
15614
15615fn snippet_completions(
15616    project: &Project,
15617    buffer: &Entity<Buffer>,
15618    buffer_position: text::Anchor,
15619    cx: &mut App,
15620) -> Task<Result<Vec<Completion>>> {
15621    let language = buffer.read(cx).language_at(buffer_position);
15622    let language_name = language.as_ref().map(|language| language.lsp_id());
15623    let snippet_store = project.snippets().read(cx);
15624    let snippets = snippet_store.snippets_for(language_name, cx);
15625
15626    if snippets.is_empty() {
15627        return Task::ready(Ok(vec![]));
15628    }
15629    let snapshot = buffer.read(cx).text_snapshot();
15630    let chars: String = snapshot
15631        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15632        .collect();
15633
15634    let scope = language.map(|language| language.default_scope());
15635    let executor = cx.background_executor().clone();
15636
15637    cx.background_spawn(async move {
15638        let classifier = CharClassifier::new(scope).for_completion(true);
15639        let mut last_word = chars
15640            .chars()
15641            .take_while(|c| classifier.is_word(*c))
15642            .collect::<String>();
15643        last_word = last_word.chars().rev().collect();
15644
15645        if last_word.is_empty() {
15646            return Ok(vec![]);
15647        }
15648
15649        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15650        let to_lsp = |point: &text::Anchor| {
15651            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15652            point_to_lsp(end)
15653        };
15654        let lsp_end = to_lsp(&buffer_position);
15655
15656        let candidates = snippets
15657            .iter()
15658            .enumerate()
15659            .flat_map(|(ix, snippet)| {
15660                snippet
15661                    .prefix
15662                    .iter()
15663                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15664            })
15665            .collect::<Vec<StringMatchCandidate>>();
15666
15667        let mut matches = fuzzy::match_strings(
15668            &candidates,
15669            &last_word,
15670            last_word.chars().any(|c| c.is_uppercase()),
15671            100,
15672            &Default::default(),
15673            executor,
15674        )
15675        .await;
15676
15677        // Remove all candidates where the query's start does not match the start of any word in the candidate
15678        if let Some(query_start) = last_word.chars().next() {
15679            matches.retain(|string_match| {
15680                split_words(&string_match.string).any(|word| {
15681                    // Check that the first codepoint of the word as lowercase matches the first
15682                    // codepoint of the query as lowercase
15683                    word.chars()
15684                        .flat_map(|codepoint| codepoint.to_lowercase())
15685                        .zip(query_start.to_lowercase())
15686                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15687                })
15688            });
15689        }
15690
15691        let matched_strings = matches
15692            .into_iter()
15693            .map(|m| m.string)
15694            .collect::<HashSet<_>>();
15695
15696        let result: Vec<Completion> = snippets
15697            .into_iter()
15698            .filter_map(|snippet| {
15699                let matching_prefix = snippet
15700                    .prefix
15701                    .iter()
15702                    .find(|prefix| matched_strings.contains(*prefix))?;
15703                let start = as_offset - last_word.len();
15704                let start = snapshot.anchor_before(start);
15705                let range = start..buffer_position;
15706                let lsp_start = to_lsp(&start);
15707                let lsp_range = lsp::Range {
15708                    start: lsp_start,
15709                    end: lsp_end,
15710                };
15711                Some(Completion {
15712                    old_range: range,
15713                    new_text: snippet.body.clone(),
15714                    resolved: false,
15715                    label: CodeLabel {
15716                        text: matching_prefix.clone(),
15717                        runs: vec![],
15718                        filter_range: 0..matching_prefix.len(),
15719                    },
15720                    server_id: LanguageServerId(usize::MAX),
15721                    documentation: snippet
15722                        .description
15723                        .clone()
15724                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15725                    lsp_completion: lsp::CompletionItem {
15726                        label: snippet.prefix.first().unwrap().clone(),
15727                        kind: Some(CompletionItemKind::SNIPPET),
15728                        label_details: snippet.description.as_ref().map(|description| {
15729                            lsp::CompletionItemLabelDetails {
15730                                detail: Some(description.clone()),
15731                                description: None,
15732                            }
15733                        }),
15734                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15735                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15736                            lsp::InsertReplaceEdit {
15737                                new_text: snippet.body.clone(),
15738                                insert: lsp_range,
15739                                replace: lsp_range,
15740                            },
15741                        )),
15742                        filter_text: Some(snippet.body.clone()),
15743                        sort_text: Some(char::MAX.to_string()),
15744                        ..Default::default()
15745                    },
15746                    confirm: None,
15747                })
15748            })
15749            .collect();
15750
15751        Ok(result)
15752    })
15753}
15754
15755impl CompletionProvider for Entity<Project> {
15756    fn completions(
15757        &self,
15758        buffer: &Entity<Buffer>,
15759        buffer_position: text::Anchor,
15760        options: CompletionContext,
15761        _window: &mut Window,
15762        cx: &mut Context<Editor>,
15763    ) -> Task<Result<Vec<Completion>>> {
15764        self.update(cx, |project, cx| {
15765            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15766            let project_completions = project.completions(buffer, buffer_position, options, cx);
15767            cx.background_spawn(async move {
15768                let mut completions = project_completions.await?;
15769                let snippets_completions = snippets.await?;
15770                completions.extend(snippets_completions);
15771                Ok(completions)
15772            })
15773        })
15774    }
15775
15776    fn resolve_completions(
15777        &self,
15778        buffer: Entity<Buffer>,
15779        completion_indices: Vec<usize>,
15780        completions: Rc<RefCell<Box<[Completion]>>>,
15781        cx: &mut Context<Editor>,
15782    ) -> Task<Result<bool>> {
15783        self.update(cx, |project, cx| {
15784            project.lsp_store().update(cx, |lsp_store, cx| {
15785                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15786            })
15787        })
15788    }
15789
15790    fn apply_additional_edits_for_completion(
15791        &self,
15792        buffer: Entity<Buffer>,
15793        completions: Rc<RefCell<Box<[Completion]>>>,
15794        completion_index: usize,
15795        push_to_history: bool,
15796        cx: &mut Context<Editor>,
15797    ) -> Task<Result<Option<language::Transaction>>> {
15798        self.update(cx, |project, cx| {
15799            project.lsp_store().update(cx, |lsp_store, cx| {
15800                lsp_store.apply_additional_edits_for_completion(
15801                    buffer,
15802                    completions,
15803                    completion_index,
15804                    push_to_history,
15805                    cx,
15806                )
15807            })
15808        })
15809    }
15810
15811    fn is_completion_trigger(
15812        &self,
15813        buffer: &Entity<Buffer>,
15814        position: language::Anchor,
15815        text: &str,
15816        trigger_in_words: bool,
15817        cx: &mut Context<Editor>,
15818    ) -> bool {
15819        let mut chars = text.chars();
15820        let char = if let Some(char) = chars.next() {
15821            char
15822        } else {
15823            return false;
15824        };
15825        if chars.next().is_some() {
15826            return false;
15827        }
15828
15829        let buffer = buffer.read(cx);
15830        let snapshot = buffer.snapshot();
15831        if !snapshot.settings_at(position, cx).show_completions_on_input {
15832            return false;
15833        }
15834        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15835        if trigger_in_words && classifier.is_word(char) {
15836            return true;
15837        }
15838
15839        buffer.completion_triggers().contains(text)
15840    }
15841}
15842
15843impl SemanticsProvider for Entity<Project> {
15844    fn hover(
15845        &self,
15846        buffer: &Entity<Buffer>,
15847        position: text::Anchor,
15848        cx: &mut App,
15849    ) -> Option<Task<Vec<project::Hover>>> {
15850        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15851    }
15852
15853    fn document_highlights(
15854        &self,
15855        buffer: &Entity<Buffer>,
15856        position: text::Anchor,
15857        cx: &mut App,
15858    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15859        Some(self.update(cx, |project, cx| {
15860            project.document_highlights(buffer, position, cx)
15861        }))
15862    }
15863
15864    fn definitions(
15865        &self,
15866        buffer: &Entity<Buffer>,
15867        position: text::Anchor,
15868        kind: GotoDefinitionKind,
15869        cx: &mut App,
15870    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15871        Some(self.update(cx, |project, cx| match kind {
15872            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15873            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15874            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15875            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15876        }))
15877    }
15878
15879    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15880        // TODO: make this work for remote projects
15881        self.update(cx, |this, cx| {
15882            buffer.update(cx, |buffer, cx| {
15883                this.any_language_server_supports_inlay_hints(buffer, cx)
15884            })
15885        })
15886    }
15887
15888    fn inlay_hints(
15889        &self,
15890        buffer_handle: Entity<Buffer>,
15891        range: Range<text::Anchor>,
15892        cx: &mut App,
15893    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15894        Some(self.update(cx, |project, cx| {
15895            project.inlay_hints(buffer_handle, range, cx)
15896        }))
15897    }
15898
15899    fn resolve_inlay_hint(
15900        &self,
15901        hint: InlayHint,
15902        buffer_handle: Entity<Buffer>,
15903        server_id: LanguageServerId,
15904        cx: &mut App,
15905    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15906        Some(self.update(cx, |project, cx| {
15907            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15908        }))
15909    }
15910
15911    fn range_for_rename(
15912        &self,
15913        buffer: &Entity<Buffer>,
15914        position: text::Anchor,
15915        cx: &mut App,
15916    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15917        Some(self.update(cx, |project, cx| {
15918            let buffer = buffer.clone();
15919            let task = project.prepare_rename(buffer.clone(), position, cx);
15920            cx.spawn(|_, mut cx| async move {
15921                Ok(match task.await? {
15922                    PrepareRenameResponse::Success(range) => Some(range),
15923                    PrepareRenameResponse::InvalidPosition => None,
15924                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15925                        // Fallback on using TreeSitter info to determine identifier range
15926                        buffer.update(&mut cx, |buffer, _| {
15927                            let snapshot = buffer.snapshot();
15928                            let (range, kind) = snapshot.surrounding_word(position);
15929                            if kind != Some(CharKind::Word) {
15930                                return None;
15931                            }
15932                            Some(
15933                                snapshot.anchor_before(range.start)
15934                                    ..snapshot.anchor_after(range.end),
15935                            )
15936                        })?
15937                    }
15938                })
15939            })
15940        }))
15941    }
15942
15943    fn perform_rename(
15944        &self,
15945        buffer: &Entity<Buffer>,
15946        position: text::Anchor,
15947        new_name: String,
15948        cx: &mut App,
15949    ) -> Option<Task<Result<ProjectTransaction>>> {
15950        Some(self.update(cx, |project, cx| {
15951            project.perform_rename(buffer.clone(), position, new_name, cx)
15952        }))
15953    }
15954}
15955
15956fn inlay_hint_settings(
15957    location: Anchor,
15958    snapshot: &MultiBufferSnapshot,
15959    cx: &mut Context<Editor>,
15960) -> InlayHintSettings {
15961    let file = snapshot.file_at(location);
15962    let language = snapshot.language_at(location).map(|l| l.name());
15963    language_settings(language, file, cx).inlay_hints
15964}
15965
15966fn consume_contiguous_rows(
15967    contiguous_row_selections: &mut Vec<Selection<Point>>,
15968    selection: &Selection<Point>,
15969    display_map: &DisplaySnapshot,
15970    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15971) -> (MultiBufferRow, MultiBufferRow) {
15972    contiguous_row_selections.push(selection.clone());
15973    let start_row = MultiBufferRow(selection.start.row);
15974    let mut end_row = ending_row(selection, display_map);
15975
15976    while let Some(next_selection) = selections.peek() {
15977        if next_selection.start.row <= end_row.0 {
15978            end_row = ending_row(next_selection, display_map);
15979            contiguous_row_selections.push(selections.next().unwrap().clone());
15980        } else {
15981            break;
15982        }
15983    }
15984    (start_row, end_row)
15985}
15986
15987fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15988    if next_selection.end.column > 0 || next_selection.is_empty() {
15989        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15990    } else {
15991        MultiBufferRow(next_selection.end.row)
15992    }
15993}
15994
15995impl EditorSnapshot {
15996    pub fn remote_selections_in_range<'a>(
15997        &'a self,
15998        range: &'a Range<Anchor>,
15999        collaboration_hub: &dyn CollaborationHub,
16000        cx: &'a App,
16001    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16002        let participant_names = collaboration_hub.user_names(cx);
16003        let participant_indices = collaboration_hub.user_participant_indices(cx);
16004        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16005        let collaborators_by_replica_id = collaborators_by_peer_id
16006            .iter()
16007            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16008            .collect::<HashMap<_, _>>();
16009        self.buffer_snapshot
16010            .selections_in_range(range, false)
16011            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16012                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16013                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16014                let user_name = participant_names.get(&collaborator.user_id).cloned();
16015                Some(RemoteSelection {
16016                    replica_id,
16017                    selection,
16018                    cursor_shape,
16019                    line_mode,
16020                    participant_index,
16021                    peer_id: collaborator.peer_id,
16022                    user_name,
16023                })
16024            })
16025    }
16026
16027    pub fn hunks_for_ranges(
16028        &self,
16029        ranges: impl Iterator<Item = Range<Point>>,
16030    ) -> Vec<MultiBufferDiffHunk> {
16031        let mut hunks = Vec::new();
16032        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16033            HashMap::default();
16034        for query_range in ranges {
16035            let query_rows =
16036                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16037            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16038                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16039            ) {
16040                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16041                // when the caret is just above or just below the deleted hunk.
16042                let allow_adjacent = hunk.status().is_deleted();
16043                let related_to_selection = if allow_adjacent {
16044                    hunk.row_range.overlaps(&query_rows)
16045                        || hunk.row_range.start == query_rows.end
16046                        || hunk.row_range.end == query_rows.start
16047                } else {
16048                    hunk.row_range.overlaps(&query_rows)
16049                };
16050                if related_to_selection {
16051                    if !processed_buffer_rows
16052                        .entry(hunk.buffer_id)
16053                        .or_default()
16054                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16055                    {
16056                        continue;
16057                    }
16058                    hunks.push(hunk);
16059                }
16060            }
16061        }
16062
16063        hunks
16064    }
16065
16066    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16067        self.display_snapshot.buffer_snapshot.language_at(position)
16068    }
16069
16070    pub fn is_focused(&self) -> bool {
16071        self.is_focused
16072    }
16073
16074    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16075        self.placeholder_text.as_ref()
16076    }
16077
16078    pub fn scroll_position(&self) -> gpui::Point<f32> {
16079        self.scroll_anchor.scroll_position(&self.display_snapshot)
16080    }
16081
16082    fn gutter_dimensions(
16083        &self,
16084        font_id: FontId,
16085        font_size: Pixels,
16086        max_line_number_width: Pixels,
16087        cx: &App,
16088    ) -> Option<GutterDimensions> {
16089        if !self.show_gutter {
16090            return None;
16091        }
16092
16093        let descent = cx.text_system().descent(font_id, font_size);
16094        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16095        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16096
16097        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16098            matches!(
16099                ProjectSettings::get_global(cx).git.git_gutter,
16100                Some(GitGutterSetting::TrackedFiles)
16101            )
16102        });
16103        let gutter_settings = EditorSettings::get_global(cx).gutter;
16104        let show_line_numbers = self
16105            .show_line_numbers
16106            .unwrap_or(gutter_settings.line_numbers);
16107        let line_gutter_width = if show_line_numbers {
16108            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16109            let min_width_for_number_on_gutter = em_advance * 4.0;
16110            max_line_number_width.max(min_width_for_number_on_gutter)
16111        } else {
16112            0.0.into()
16113        };
16114
16115        let show_code_actions = self
16116            .show_code_actions
16117            .unwrap_or(gutter_settings.code_actions);
16118
16119        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16120
16121        let git_blame_entries_width =
16122            self.git_blame_gutter_max_author_length
16123                .map(|max_author_length| {
16124                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16125
16126                    /// The number of characters to dedicate to gaps and margins.
16127                    const SPACING_WIDTH: usize = 4;
16128
16129                    let max_char_count = max_author_length
16130                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16131                        + ::git::SHORT_SHA_LENGTH
16132                        + MAX_RELATIVE_TIMESTAMP.len()
16133                        + SPACING_WIDTH;
16134
16135                    em_advance * max_char_count
16136                });
16137
16138        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16139        left_padding += if show_code_actions || show_runnables {
16140            em_width * 3.0
16141        } else if show_git_gutter && show_line_numbers {
16142            em_width * 2.0
16143        } else if show_git_gutter || show_line_numbers {
16144            em_width
16145        } else {
16146            px(0.)
16147        };
16148
16149        let right_padding = if gutter_settings.folds && show_line_numbers {
16150            em_width * 4.0
16151        } else if gutter_settings.folds {
16152            em_width * 3.0
16153        } else if show_line_numbers {
16154            em_width
16155        } else {
16156            px(0.)
16157        };
16158
16159        Some(GutterDimensions {
16160            left_padding,
16161            right_padding,
16162            width: line_gutter_width + left_padding + right_padding,
16163            margin: -descent,
16164            git_blame_entries_width,
16165        })
16166    }
16167
16168    pub fn render_crease_toggle(
16169        &self,
16170        buffer_row: MultiBufferRow,
16171        row_contains_cursor: bool,
16172        editor: Entity<Editor>,
16173        window: &mut Window,
16174        cx: &mut App,
16175    ) -> Option<AnyElement> {
16176        let folded = self.is_line_folded(buffer_row);
16177        let mut is_foldable = false;
16178
16179        if let Some(crease) = self
16180            .crease_snapshot
16181            .query_row(buffer_row, &self.buffer_snapshot)
16182        {
16183            is_foldable = true;
16184            match crease {
16185                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16186                    if let Some(render_toggle) = render_toggle {
16187                        let toggle_callback =
16188                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16189                                if folded {
16190                                    editor.update(cx, |editor, cx| {
16191                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16192                                    });
16193                                } else {
16194                                    editor.update(cx, |editor, cx| {
16195                                        editor.unfold_at(
16196                                            &crate::UnfoldAt { buffer_row },
16197                                            window,
16198                                            cx,
16199                                        )
16200                                    });
16201                                }
16202                            });
16203                        return Some((render_toggle)(
16204                            buffer_row,
16205                            folded,
16206                            toggle_callback,
16207                            window,
16208                            cx,
16209                        ));
16210                    }
16211                }
16212            }
16213        }
16214
16215        is_foldable |= self.starts_indent(buffer_row);
16216
16217        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16218            Some(
16219                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16220                    .toggle_state(folded)
16221                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16222                        if folded {
16223                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16224                        } else {
16225                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16226                        }
16227                    }))
16228                    .into_any_element(),
16229            )
16230        } else {
16231            None
16232        }
16233    }
16234
16235    pub fn render_crease_trailer(
16236        &self,
16237        buffer_row: MultiBufferRow,
16238        window: &mut Window,
16239        cx: &mut App,
16240    ) -> Option<AnyElement> {
16241        let folded = self.is_line_folded(buffer_row);
16242        if let Crease::Inline { render_trailer, .. } = self
16243            .crease_snapshot
16244            .query_row(buffer_row, &self.buffer_snapshot)?
16245        {
16246            let render_trailer = render_trailer.as_ref()?;
16247            Some(render_trailer(buffer_row, folded, window, cx))
16248        } else {
16249            None
16250        }
16251    }
16252}
16253
16254impl Deref for EditorSnapshot {
16255    type Target = DisplaySnapshot;
16256
16257    fn deref(&self) -> &Self::Target {
16258        &self.display_snapshot
16259    }
16260}
16261
16262#[derive(Clone, Debug, PartialEq, Eq)]
16263pub enum EditorEvent {
16264    InputIgnored {
16265        text: Arc<str>,
16266    },
16267    InputHandled {
16268        utf16_range_to_replace: Option<Range<isize>>,
16269        text: Arc<str>,
16270    },
16271    ExcerptsAdded {
16272        buffer: Entity<Buffer>,
16273        predecessor: ExcerptId,
16274        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16275    },
16276    ExcerptsRemoved {
16277        ids: Vec<ExcerptId>,
16278    },
16279    BufferFoldToggled {
16280        ids: Vec<ExcerptId>,
16281        folded: bool,
16282    },
16283    ExcerptsEdited {
16284        ids: Vec<ExcerptId>,
16285    },
16286    ExcerptsExpanded {
16287        ids: Vec<ExcerptId>,
16288    },
16289    BufferEdited,
16290    Edited {
16291        transaction_id: clock::Lamport,
16292    },
16293    Reparsed(BufferId),
16294    Focused,
16295    FocusedIn,
16296    Blurred,
16297    DirtyChanged,
16298    Saved,
16299    TitleChanged,
16300    DiffBaseChanged,
16301    SelectionsChanged {
16302        local: bool,
16303    },
16304    ScrollPositionChanged {
16305        local: bool,
16306        autoscroll: bool,
16307    },
16308    Closed,
16309    TransactionUndone {
16310        transaction_id: clock::Lamport,
16311    },
16312    TransactionBegun {
16313        transaction_id: clock::Lamport,
16314    },
16315    Reloaded,
16316    CursorShapeChanged,
16317}
16318
16319impl EventEmitter<EditorEvent> for Editor {}
16320
16321impl Focusable for Editor {
16322    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16323        self.focus_handle.clone()
16324    }
16325}
16326
16327impl Render for Editor {
16328    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16329        let settings = ThemeSettings::get_global(cx);
16330
16331        let mut text_style = match self.mode {
16332            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16333                color: cx.theme().colors().editor_foreground,
16334                font_family: settings.ui_font.family.clone(),
16335                font_features: settings.ui_font.features.clone(),
16336                font_fallbacks: settings.ui_font.fallbacks.clone(),
16337                font_size: rems(0.875).into(),
16338                font_weight: settings.ui_font.weight,
16339                line_height: relative(settings.buffer_line_height.value()),
16340                ..Default::default()
16341            },
16342            EditorMode::Full => TextStyle {
16343                color: cx.theme().colors().editor_foreground,
16344                font_family: settings.buffer_font.family.clone(),
16345                font_features: settings.buffer_font.features.clone(),
16346                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16347                font_size: settings.buffer_font_size(cx).into(),
16348                font_weight: settings.buffer_font.weight,
16349                line_height: relative(settings.buffer_line_height.value()),
16350                ..Default::default()
16351            },
16352        };
16353        if let Some(text_style_refinement) = &self.text_style_refinement {
16354            text_style.refine(text_style_refinement)
16355        }
16356
16357        let background = match self.mode {
16358            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16359            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16360            EditorMode::Full => cx.theme().colors().editor_background,
16361        };
16362
16363        EditorElement::new(
16364            &cx.entity(),
16365            EditorStyle {
16366                background,
16367                local_player: cx.theme().players().local(),
16368                text: text_style,
16369                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16370                syntax: cx.theme().syntax().clone(),
16371                status: cx.theme().status().clone(),
16372                inlay_hints_style: make_inlay_hints_style(cx),
16373                inline_completion_styles: make_suggestion_styles(cx),
16374                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16375            },
16376        )
16377    }
16378}
16379
16380impl EntityInputHandler for Editor {
16381    fn text_for_range(
16382        &mut self,
16383        range_utf16: Range<usize>,
16384        adjusted_range: &mut Option<Range<usize>>,
16385        _: &mut Window,
16386        cx: &mut Context<Self>,
16387    ) -> Option<String> {
16388        let snapshot = self.buffer.read(cx).read(cx);
16389        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16390        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16391        if (start.0..end.0) != range_utf16 {
16392            adjusted_range.replace(start.0..end.0);
16393        }
16394        Some(snapshot.text_for_range(start..end).collect())
16395    }
16396
16397    fn selected_text_range(
16398        &mut self,
16399        ignore_disabled_input: bool,
16400        _: &mut Window,
16401        cx: &mut Context<Self>,
16402    ) -> Option<UTF16Selection> {
16403        // Prevent the IME menu from appearing when holding down an alphabetic key
16404        // while input is disabled.
16405        if !ignore_disabled_input && !self.input_enabled {
16406            return None;
16407        }
16408
16409        let selection = self.selections.newest::<OffsetUtf16>(cx);
16410        let range = selection.range();
16411
16412        Some(UTF16Selection {
16413            range: range.start.0..range.end.0,
16414            reversed: selection.reversed,
16415        })
16416    }
16417
16418    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16419        let snapshot = self.buffer.read(cx).read(cx);
16420        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16421        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16422    }
16423
16424    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16425        self.clear_highlights::<InputComposition>(cx);
16426        self.ime_transaction.take();
16427    }
16428
16429    fn replace_text_in_range(
16430        &mut self,
16431        range_utf16: Option<Range<usize>>,
16432        text: &str,
16433        window: &mut Window,
16434        cx: &mut Context<Self>,
16435    ) {
16436        if !self.input_enabled {
16437            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16438            return;
16439        }
16440
16441        self.transact(window, cx, |this, window, cx| {
16442            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16443                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16444                Some(this.selection_replacement_ranges(range_utf16, cx))
16445            } else {
16446                this.marked_text_ranges(cx)
16447            };
16448
16449            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16450                let newest_selection_id = this.selections.newest_anchor().id;
16451                this.selections
16452                    .all::<OffsetUtf16>(cx)
16453                    .iter()
16454                    .zip(ranges_to_replace.iter())
16455                    .find_map(|(selection, range)| {
16456                        if selection.id == newest_selection_id {
16457                            Some(
16458                                (range.start.0 as isize - selection.head().0 as isize)
16459                                    ..(range.end.0 as isize - selection.head().0 as isize),
16460                            )
16461                        } else {
16462                            None
16463                        }
16464                    })
16465            });
16466
16467            cx.emit(EditorEvent::InputHandled {
16468                utf16_range_to_replace: range_to_replace,
16469                text: text.into(),
16470            });
16471
16472            if let Some(new_selected_ranges) = new_selected_ranges {
16473                this.change_selections(None, window, cx, |selections| {
16474                    selections.select_ranges(new_selected_ranges)
16475                });
16476                this.backspace(&Default::default(), window, cx);
16477            }
16478
16479            this.handle_input(text, window, cx);
16480        });
16481
16482        if let Some(transaction) = self.ime_transaction {
16483            self.buffer.update(cx, |buffer, cx| {
16484                buffer.group_until_transaction(transaction, cx);
16485            });
16486        }
16487
16488        self.unmark_text(window, cx);
16489    }
16490
16491    fn replace_and_mark_text_in_range(
16492        &mut self,
16493        range_utf16: Option<Range<usize>>,
16494        text: &str,
16495        new_selected_range_utf16: Option<Range<usize>>,
16496        window: &mut Window,
16497        cx: &mut Context<Self>,
16498    ) {
16499        if !self.input_enabled {
16500            return;
16501        }
16502
16503        let transaction = self.transact(window, cx, |this, window, cx| {
16504            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16505                let snapshot = this.buffer.read(cx).read(cx);
16506                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16507                    for marked_range in &mut marked_ranges {
16508                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16509                        marked_range.start.0 += relative_range_utf16.start;
16510                        marked_range.start =
16511                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16512                        marked_range.end =
16513                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16514                    }
16515                }
16516                Some(marked_ranges)
16517            } else if let Some(range_utf16) = range_utf16 {
16518                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16519                Some(this.selection_replacement_ranges(range_utf16, cx))
16520            } else {
16521                None
16522            };
16523
16524            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16525                let newest_selection_id = this.selections.newest_anchor().id;
16526                this.selections
16527                    .all::<OffsetUtf16>(cx)
16528                    .iter()
16529                    .zip(ranges_to_replace.iter())
16530                    .find_map(|(selection, range)| {
16531                        if selection.id == newest_selection_id {
16532                            Some(
16533                                (range.start.0 as isize - selection.head().0 as isize)
16534                                    ..(range.end.0 as isize - selection.head().0 as isize),
16535                            )
16536                        } else {
16537                            None
16538                        }
16539                    })
16540            });
16541
16542            cx.emit(EditorEvent::InputHandled {
16543                utf16_range_to_replace: range_to_replace,
16544                text: text.into(),
16545            });
16546
16547            if let Some(ranges) = ranges_to_replace {
16548                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16549            }
16550
16551            let marked_ranges = {
16552                let snapshot = this.buffer.read(cx).read(cx);
16553                this.selections
16554                    .disjoint_anchors()
16555                    .iter()
16556                    .map(|selection| {
16557                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16558                    })
16559                    .collect::<Vec<_>>()
16560            };
16561
16562            if text.is_empty() {
16563                this.unmark_text(window, cx);
16564            } else {
16565                this.highlight_text::<InputComposition>(
16566                    marked_ranges.clone(),
16567                    HighlightStyle {
16568                        underline: Some(UnderlineStyle {
16569                            thickness: px(1.),
16570                            color: None,
16571                            wavy: false,
16572                        }),
16573                        ..Default::default()
16574                    },
16575                    cx,
16576                );
16577            }
16578
16579            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16580            let use_autoclose = this.use_autoclose;
16581            let use_auto_surround = this.use_auto_surround;
16582            this.set_use_autoclose(false);
16583            this.set_use_auto_surround(false);
16584            this.handle_input(text, window, cx);
16585            this.set_use_autoclose(use_autoclose);
16586            this.set_use_auto_surround(use_auto_surround);
16587
16588            if let Some(new_selected_range) = new_selected_range_utf16 {
16589                let snapshot = this.buffer.read(cx).read(cx);
16590                let new_selected_ranges = marked_ranges
16591                    .into_iter()
16592                    .map(|marked_range| {
16593                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16594                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16595                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16596                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16597                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16598                    })
16599                    .collect::<Vec<_>>();
16600
16601                drop(snapshot);
16602                this.change_selections(None, window, cx, |selections| {
16603                    selections.select_ranges(new_selected_ranges)
16604                });
16605            }
16606        });
16607
16608        self.ime_transaction = self.ime_transaction.or(transaction);
16609        if let Some(transaction) = self.ime_transaction {
16610            self.buffer.update(cx, |buffer, cx| {
16611                buffer.group_until_transaction(transaction, cx);
16612            });
16613        }
16614
16615        if self.text_highlights::<InputComposition>(cx).is_none() {
16616            self.ime_transaction.take();
16617        }
16618    }
16619
16620    fn bounds_for_range(
16621        &mut self,
16622        range_utf16: Range<usize>,
16623        element_bounds: gpui::Bounds<Pixels>,
16624        window: &mut Window,
16625        cx: &mut Context<Self>,
16626    ) -> Option<gpui::Bounds<Pixels>> {
16627        let text_layout_details = self.text_layout_details(window);
16628        let gpui::Size {
16629            width: em_width,
16630            height: line_height,
16631        } = self.character_size(window);
16632
16633        let snapshot = self.snapshot(window, cx);
16634        let scroll_position = snapshot.scroll_position();
16635        let scroll_left = scroll_position.x * em_width;
16636
16637        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16638        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16639            + self.gutter_dimensions.width
16640            + self.gutter_dimensions.margin;
16641        let y = line_height * (start.row().as_f32() - scroll_position.y);
16642
16643        Some(Bounds {
16644            origin: element_bounds.origin + point(x, y),
16645            size: size(em_width, line_height),
16646        })
16647    }
16648
16649    fn character_index_for_point(
16650        &mut self,
16651        point: gpui::Point<Pixels>,
16652        _window: &mut Window,
16653        _cx: &mut Context<Self>,
16654    ) -> Option<usize> {
16655        let position_map = self.last_position_map.as_ref()?;
16656        if !position_map.text_hitbox.contains(&point) {
16657            return None;
16658        }
16659        let display_point = position_map.point_for_position(point).previous_valid;
16660        let anchor = position_map
16661            .snapshot
16662            .display_point_to_anchor(display_point, Bias::Left);
16663        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16664        Some(utf16_offset.0)
16665    }
16666}
16667
16668trait SelectionExt {
16669    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16670    fn spanned_rows(
16671        &self,
16672        include_end_if_at_line_start: bool,
16673        map: &DisplaySnapshot,
16674    ) -> Range<MultiBufferRow>;
16675}
16676
16677impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16678    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16679        let start = self
16680            .start
16681            .to_point(&map.buffer_snapshot)
16682            .to_display_point(map);
16683        let end = self
16684            .end
16685            .to_point(&map.buffer_snapshot)
16686            .to_display_point(map);
16687        if self.reversed {
16688            end..start
16689        } else {
16690            start..end
16691        }
16692    }
16693
16694    fn spanned_rows(
16695        &self,
16696        include_end_if_at_line_start: bool,
16697        map: &DisplaySnapshot,
16698    ) -> Range<MultiBufferRow> {
16699        let start = self.start.to_point(&map.buffer_snapshot);
16700        let mut end = self.end.to_point(&map.buffer_snapshot);
16701        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16702            end.row -= 1;
16703        }
16704
16705        let buffer_start = map.prev_line_boundary(start).0;
16706        let buffer_end = map.next_line_boundary(end).0;
16707        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16708    }
16709}
16710
16711impl<T: InvalidationRegion> InvalidationStack<T> {
16712    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16713    where
16714        S: Clone + ToOffset,
16715    {
16716        while let Some(region) = self.last() {
16717            let all_selections_inside_invalidation_ranges =
16718                if selections.len() == region.ranges().len() {
16719                    selections
16720                        .iter()
16721                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16722                        .all(|(selection, invalidation_range)| {
16723                            let head = selection.head().to_offset(buffer);
16724                            invalidation_range.start <= head && invalidation_range.end >= head
16725                        })
16726                } else {
16727                    false
16728                };
16729
16730            if all_selections_inside_invalidation_ranges {
16731                break;
16732            } else {
16733                self.pop();
16734            }
16735        }
16736    }
16737}
16738
16739impl<T> Default for InvalidationStack<T> {
16740    fn default() -> Self {
16741        Self(Default::default())
16742    }
16743}
16744
16745impl<T> Deref for InvalidationStack<T> {
16746    type Target = Vec<T>;
16747
16748    fn deref(&self) -> &Self::Target {
16749        &self.0
16750    }
16751}
16752
16753impl<T> DerefMut for InvalidationStack<T> {
16754    fn deref_mut(&mut self) -> &mut Self::Target {
16755        &mut self.0
16756    }
16757}
16758
16759impl InvalidationRegion for SnippetState {
16760    fn ranges(&self) -> &[Range<Anchor>] {
16761        &self.ranges[self.active_index]
16762    }
16763}
16764
16765pub fn diagnostic_block_renderer(
16766    diagnostic: Diagnostic,
16767    max_message_rows: Option<u8>,
16768    allow_closing: bool,
16769    _is_valid: bool,
16770) -> RenderBlock {
16771    let (text_without_backticks, code_ranges) =
16772        highlight_diagnostic_message(&diagnostic, max_message_rows);
16773
16774    Arc::new(move |cx: &mut BlockContext| {
16775        let group_id: SharedString = cx.block_id.to_string().into();
16776
16777        let mut text_style = cx.window.text_style().clone();
16778        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16779        let theme_settings = ThemeSettings::get_global(cx);
16780        text_style.font_family = theme_settings.buffer_font.family.clone();
16781        text_style.font_style = theme_settings.buffer_font.style;
16782        text_style.font_features = theme_settings.buffer_font.features.clone();
16783        text_style.font_weight = theme_settings.buffer_font.weight;
16784
16785        let multi_line_diagnostic = diagnostic.message.contains('\n');
16786
16787        let buttons = |diagnostic: &Diagnostic| {
16788            if multi_line_diagnostic {
16789                v_flex()
16790            } else {
16791                h_flex()
16792            }
16793            .when(allow_closing, |div| {
16794                div.children(diagnostic.is_primary.then(|| {
16795                    IconButton::new("close-block", IconName::XCircle)
16796                        .icon_color(Color::Muted)
16797                        .size(ButtonSize::Compact)
16798                        .style(ButtonStyle::Transparent)
16799                        .visible_on_hover(group_id.clone())
16800                        .on_click(move |_click, window, cx| {
16801                            window.dispatch_action(Box::new(Cancel), cx)
16802                        })
16803                        .tooltip(|window, cx| {
16804                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16805                        })
16806                }))
16807            })
16808            .child(
16809                IconButton::new("copy-block", IconName::Copy)
16810                    .icon_color(Color::Muted)
16811                    .size(ButtonSize::Compact)
16812                    .style(ButtonStyle::Transparent)
16813                    .visible_on_hover(group_id.clone())
16814                    .on_click({
16815                        let message = diagnostic.message.clone();
16816                        move |_click, _, cx| {
16817                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16818                        }
16819                    })
16820                    .tooltip(Tooltip::text("Copy diagnostic message")),
16821            )
16822        };
16823
16824        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16825            AvailableSpace::min_size(),
16826            cx.window,
16827            cx.app,
16828        );
16829
16830        h_flex()
16831            .id(cx.block_id)
16832            .group(group_id.clone())
16833            .relative()
16834            .size_full()
16835            .block_mouse_down()
16836            .pl(cx.gutter_dimensions.width)
16837            .w(cx.max_width - cx.gutter_dimensions.full_width())
16838            .child(
16839                div()
16840                    .flex()
16841                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16842                    .flex_shrink(),
16843            )
16844            .child(buttons(&diagnostic))
16845            .child(div().flex().flex_shrink_0().child(
16846                StyledText::new(text_without_backticks.clone()).with_highlights(
16847                    &text_style,
16848                    code_ranges.iter().map(|range| {
16849                        (
16850                            range.clone(),
16851                            HighlightStyle {
16852                                font_weight: Some(FontWeight::BOLD),
16853                                ..Default::default()
16854                            },
16855                        )
16856                    }),
16857                ),
16858            ))
16859            .into_any_element()
16860    })
16861}
16862
16863fn inline_completion_edit_text(
16864    current_snapshot: &BufferSnapshot,
16865    edits: &[(Range<Anchor>, String)],
16866    edit_preview: &EditPreview,
16867    include_deletions: bool,
16868    cx: &App,
16869) -> HighlightedText {
16870    let edits = edits
16871        .iter()
16872        .map(|(anchor, text)| {
16873            (
16874                anchor.start.text_anchor..anchor.end.text_anchor,
16875                text.clone(),
16876            )
16877        })
16878        .collect::<Vec<_>>();
16879
16880    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16881}
16882
16883pub fn highlight_diagnostic_message(
16884    diagnostic: &Diagnostic,
16885    mut max_message_rows: Option<u8>,
16886) -> (SharedString, Vec<Range<usize>>) {
16887    let mut text_without_backticks = String::new();
16888    let mut code_ranges = Vec::new();
16889
16890    if let Some(source) = &diagnostic.source {
16891        text_without_backticks.push_str(source);
16892        code_ranges.push(0..source.len());
16893        text_without_backticks.push_str(": ");
16894    }
16895
16896    let mut prev_offset = 0;
16897    let mut in_code_block = false;
16898    let has_row_limit = max_message_rows.is_some();
16899    let mut newline_indices = diagnostic
16900        .message
16901        .match_indices('\n')
16902        .filter(|_| has_row_limit)
16903        .map(|(ix, _)| ix)
16904        .fuse()
16905        .peekable();
16906
16907    for (quote_ix, _) in diagnostic
16908        .message
16909        .match_indices('`')
16910        .chain([(diagnostic.message.len(), "")])
16911    {
16912        let mut first_newline_ix = None;
16913        let mut last_newline_ix = None;
16914        while let Some(newline_ix) = newline_indices.peek() {
16915            if *newline_ix < quote_ix {
16916                if first_newline_ix.is_none() {
16917                    first_newline_ix = Some(*newline_ix);
16918                }
16919                last_newline_ix = Some(*newline_ix);
16920
16921                if let Some(rows_left) = &mut max_message_rows {
16922                    if *rows_left == 0 {
16923                        break;
16924                    } else {
16925                        *rows_left -= 1;
16926                    }
16927                }
16928                let _ = newline_indices.next();
16929            } else {
16930                break;
16931            }
16932        }
16933        let prev_len = text_without_backticks.len();
16934        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16935        text_without_backticks.push_str(new_text);
16936        if in_code_block {
16937            code_ranges.push(prev_len..text_without_backticks.len());
16938        }
16939        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16940        in_code_block = !in_code_block;
16941        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16942            text_without_backticks.push_str("...");
16943            break;
16944        }
16945    }
16946
16947    (text_without_backticks.into(), code_ranges)
16948}
16949
16950fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16951    match severity {
16952        DiagnosticSeverity::ERROR => colors.error,
16953        DiagnosticSeverity::WARNING => colors.warning,
16954        DiagnosticSeverity::INFORMATION => colors.info,
16955        DiagnosticSeverity::HINT => colors.info,
16956        _ => colors.ignored,
16957    }
16958}
16959
16960pub fn styled_runs_for_code_label<'a>(
16961    label: &'a CodeLabel,
16962    syntax_theme: &'a theme::SyntaxTheme,
16963) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16964    let fade_out = HighlightStyle {
16965        fade_out: Some(0.35),
16966        ..Default::default()
16967    };
16968
16969    let mut prev_end = label.filter_range.end;
16970    label
16971        .runs
16972        .iter()
16973        .enumerate()
16974        .flat_map(move |(ix, (range, highlight_id))| {
16975            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16976                style
16977            } else {
16978                return Default::default();
16979            };
16980            let mut muted_style = style;
16981            muted_style.highlight(fade_out);
16982
16983            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16984            if range.start >= label.filter_range.end {
16985                if range.start > prev_end {
16986                    runs.push((prev_end..range.start, fade_out));
16987                }
16988                runs.push((range.clone(), muted_style));
16989            } else if range.end <= label.filter_range.end {
16990                runs.push((range.clone(), style));
16991            } else {
16992                runs.push((range.start..label.filter_range.end, style));
16993                runs.push((label.filter_range.end..range.end, muted_style));
16994            }
16995            prev_end = cmp::max(prev_end, range.end);
16996
16997            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16998                runs.push((prev_end..label.text.len(), fade_out));
16999            }
17000
17001            runs
17002        })
17003}
17004
17005pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17006    let mut prev_index = 0;
17007    let mut prev_codepoint: Option<char> = None;
17008    text.char_indices()
17009        .chain([(text.len(), '\0')])
17010        .filter_map(move |(index, codepoint)| {
17011            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17012            let is_boundary = index == text.len()
17013                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17014                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17015            if is_boundary {
17016                let chunk = &text[prev_index..index];
17017                prev_index = index;
17018                Some(chunk)
17019            } else {
17020                None
17021            }
17022        })
17023}
17024
17025pub trait RangeToAnchorExt: Sized {
17026    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17027
17028    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17029        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17030        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17031    }
17032}
17033
17034impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17035    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17036        let start_offset = self.start.to_offset(snapshot);
17037        let end_offset = self.end.to_offset(snapshot);
17038        if start_offset == end_offset {
17039            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17040        } else {
17041            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17042        }
17043    }
17044}
17045
17046pub trait RowExt {
17047    fn as_f32(&self) -> f32;
17048
17049    fn next_row(&self) -> Self;
17050
17051    fn previous_row(&self) -> Self;
17052
17053    fn minus(&self, other: Self) -> u32;
17054}
17055
17056impl RowExt for DisplayRow {
17057    fn as_f32(&self) -> f32 {
17058        self.0 as f32
17059    }
17060
17061    fn next_row(&self) -> Self {
17062        Self(self.0 + 1)
17063    }
17064
17065    fn previous_row(&self) -> Self {
17066        Self(self.0.saturating_sub(1))
17067    }
17068
17069    fn minus(&self, other: Self) -> u32 {
17070        self.0 - other.0
17071    }
17072}
17073
17074impl RowExt for MultiBufferRow {
17075    fn as_f32(&self) -> f32 {
17076        self.0 as f32
17077    }
17078
17079    fn next_row(&self) -> Self {
17080        Self(self.0 + 1)
17081    }
17082
17083    fn previous_row(&self) -> Self {
17084        Self(self.0.saturating_sub(1))
17085    }
17086
17087    fn minus(&self, other: Self) -> u32 {
17088        self.0 - other.0
17089    }
17090}
17091
17092trait RowRangeExt {
17093    type Row;
17094
17095    fn len(&self) -> usize;
17096
17097    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17098}
17099
17100impl RowRangeExt for Range<MultiBufferRow> {
17101    type Row = MultiBufferRow;
17102
17103    fn len(&self) -> usize {
17104        (self.end.0 - self.start.0) as usize
17105    }
17106
17107    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17108        (self.start.0..self.end.0).map(MultiBufferRow)
17109    }
17110}
17111
17112impl RowRangeExt for Range<DisplayRow> {
17113    type Row = DisplayRow;
17114
17115    fn len(&self) -> usize {
17116        (self.end.0 - self.start.0) as usize
17117    }
17118
17119    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17120        (self.start.0..self.end.0).map(DisplayRow)
17121    }
17122}
17123
17124/// If select range has more than one line, we
17125/// just point the cursor to range.start.
17126fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17127    if range.start.row == range.end.row {
17128        range
17129    } else {
17130        range.start..range.start
17131    }
17132}
17133pub struct KillRing(ClipboardItem);
17134impl Global for KillRing {}
17135
17136const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17137
17138fn all_edits_insertions_or_deletions(
17139    edits: &Vec<(Range<Anchor>, String)>,
17140    snapshot: &MultiBufferSnapshot,
17141) -> bool {
17142    let mut all_insertions = true;
17143    let mut all_deletions = true;
17144
17145    for (range, new_text) in edits.iter() {
17146        let range_is_empty = range.to_offset(&snapshot).is_empty();
17147        let text_is_empty = new_text.is_empty();
17148
17149        if range_is_empty != text_is_empty {
17150            if range_is_empty {
17151                all_deletions = false;
17152            } else {
17153                all_insertions = false;
17154            }
17155        } else {
17156            return false;
17157        }
17158
17159        if !all_insertions && !all_deletions {
17160            return false;
17161        }
17162    }
17163    all_insertions || all_deletions
17164}