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 blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   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 client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use display_map::*;
   60pub use display_map::{DisplayPoint, FoldPlaceholder};
   61pub use editor_settings::{
   62    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   63};
   64pub use editor_settings_controls::*;
   65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   66pub use element::{
   67    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   68};
   69use futures::{future, FutureExt};
   70use fuzzy::StringMatchCandidate;
   71
   72use code_context_menus::{
   73    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   74    CompletionsMenu, ContextMenuOrigin,
   75};
   76use diff::DiffHunkStatus;
   77use git::blame::GitBlame;
   78use gpui::{
   79    div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
   80    px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
   81    AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
   82    Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
   84    MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
   85    StyledText, Subscription, Task, TextRun, TextStyle, TextStyleRefinement, UTF16Selection,
   86    UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
  100    IndentSize, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
  101    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  128    ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  194pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
  195    "edit_prediction_requires_modifier";
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakEntity<Workspace>>,
  202    cx: &mut App,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(
  247        link_ranges,
  248        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  249            markdown::Link::Web { url } => cx.open_url(url),
  250            markdown::Link::Path { path } => {
  251                if let Some(workspace) = &workspace {
  252                    _ = workspace.update(cx, |workspace, cx| {
  253                        workspace
  254                            .open_abs_path(path.clone(), false, window, cx)
  255                            .detach();
  256                    });
  257                }
  258            }
  259        },
  260    )
  261}
  262
  263#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  264pub enum InlayId {
  265    InlineCompletion(usize),
  266    Hint(usize),
  267}
  268
  269impl InlayId {
  270    fn id(&self) -> usize {
  271        match self {
  272            Self::InlineCompletion(id) => *id,
  273            Self::Hint(id) => *id,
  274        }
  275    }
  276}
  277
  278enum DocumentHighlightRead {}
  279enum DocumentHighlightWrite {}
  280enum InputComposition {}
  281
  282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  283pub enum Navigated {
  284    Yes,
  285    No,
  286}
  287
  288impl Navigated {
  289    pub fn from_bool(yes: bool) -> Navigated {
  290        if yes {
  291            Navigated::Yes
  292        } else {
  293            Navigated::No
  294        }
  295    }
  296}
  297
  298pub fn init_settings(cx: &mut App) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut App) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new(
  310        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314            workspace.register_action(Editor::cancel_language_server_work);
  315        },
  316    )
  317    .detach();
  318
  319    cx.on_action(move |_: &workspace::NewFile, cx| {
  320        let app_state = workspace::AppState::global(cx);
  321        if let Some(app_state) = app_state.upgrade() {
  322            workspace::open_new(
  323                Default::default(),
  324                app_state,
  325                cx,
  326                |workspace, window, cx| {
  327                    Editor::new_file(workspace, &Default::default(), window, cx)
  328                },
  329            )
  330            .detach();
  331        }
  332    });
  333    cx.on_action(move |_: &workspace::NewWindow, cx| {
  334        let app_state = workspace::AppState::global(cx);
  335        if let Some(app_state) = app_state.upgrade() {
  336            workspace::open_new(
  337                Default::default(),
  338                app_state,
  339                cx,
  340                |workspace, window, cx| {
  341                    cx.activate(true);
  342                    Editor::new_file(workspace, &Default::default(), window, cx)
  343                },
  344            )
  345            .detach();
  346        }
  347    });
  348}
  349
  350pub struct SearchWithinRange;
  351
  352trait InvalidationRegion {
  353    fn ranges(&self) -> &[Range<Anchor>];
  354}
  355
  356#[derive(Clone, Debug, PartialEq)]
  357pub enum SelectPhase {
  358    Begin {
  359        position: DisplayPoint,
  360        add: bool,
  361        click_count: usize,
  362    },
  363    BeginColumnar {
  364        position: DisplayPoint,
  365        reset: bool,
  366        goal_column: u32,
  367    },
  368    Extend {
  369        position: DisplayPoint,
  370        click_count: usize,
  371    },
  372    Update {
  373        position: DisplayPoint,
  374        goal_column: u32,
  375        scroll_delta: gpui::Point<f32>,
  376    },
  377    End,
  378}
  379
  380#[derive(Clone, Debug)]
  381pub enum SelectMode {
  382    Character,
  383    Word(Range<Anchor>),
  384    Line(Range<Anchor>),
  385    All,
  386}
  387
  388#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  389pub enum EditorMode {
  390    SingleLine { auto_width: bool },
  391    AutoHeight { max_lines: usize },
  392    Full,
  393}
  394
  395#[derive(Copy, Clone, Debug)]
  396pub enum SoftWrap {
  397    /// Prefer not to wrap at all.
  398    ///
  399    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  400    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  401    GitDiff,
  402    /// Prefer a single line generally, unless an overly long line is encountered.
  403    None,
  404    /// Soft wrap lines that exceed the editor width.
  405    EditorWidth,
  406    /// Soft wrap lines at the preferred line length.
  407    Column(u32),
  408    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  409    Bounded(u32),
  410}
  411
  412#[derive(Clone)]
  413pub struct EditorStyle {
  414    pub background: Hsla,
  415    pub local_player: PlayerColor,
  416    pub text: TextStyle,
  417    pub scrollbar_width: Pixels,
  418    pub syntax: Arc<SyntaxTheme>,
  419    pub status: StatusColors,
  420    pub inlay_hints_style: HighlightStyle,
  421    pub inline_completion_styles: InlineCompletionStyles,
  422    pub unnecessary_code_fade: f32,
  423}
  424
  425impl Default for EditorStyle {
  426    fn default() -> Self {
  427        Self {
  428            background: Hsla::default(),
  429            local_player: PlayerColor::default(),
  430            text: TextStyle::default(),
  431            scrollbar_width: Pixels::default(),
  432            syntax: Default::default(),
  433            // HACK: Status colors don't have a real default.
  434            // We should look into removing the status colors from the editor
  435            // style and retrieve them directly from the theme.
  436            status: StatusColors::dark(),
  437            inlay_hints_style: HighlightStyle::default(),
  438            inline_completion_styles: InlineCompletionStyles {
  439                insertion: HighlightStyle::default(),
  440                whitespace: HighlightStyle::default(),
  441            },
  442            unnecessary_code_fade: Default::default(),
  443        }
  444    }
  445}
  446
  447pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  448    let show_background = language_settings::language_settings(None, None, cx)
  449        .inlay_hints
  450        .show_background;
  451
  452    HighlightStyle {
  453        color: Some(cx.theme().status().hint),
  454        background_color: show_background.then(|| cx.theme().status().hint_background),
  455        ..HighlightStyle::default()
  456    }
  457}
  458
  459pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  460    InlineCompletionStyles {
  461        insertion: HighlightStyle {
  462            color: Some(cx.theme().status().predictive),
  463            ..HighlightStyle::default()
  464        },
  465        whitespace: HighlightStyle {
  466            background_color: Some(cx.theme().status().created_background),
  467            ..HighlightStyle::default()
  468        },
  469    }
  470}
  471
  472type CompletionId = usize;
  473
  474pub(crate) enum EditDisplayMode {
  475    TabAccept,
  476    DiffPopover,
  477    Inline,
  478}
  479
  480enum InlineCompletion {
  481    Edit {
  482        edits: Vec<(Range<Anchor>, String)>,
  483        edit_preview: Option<EditPreview>,
  484        display_mode: EditDisplayMode,
  485        snapshot: BufferSnapshot,
  486    },
  487    Move {
  488        target: Anchor,
  489        range_around_target: Range<text::Anchor>,
  490        snapshot: BufferSnapshot,
  491    },
  492}
  493
  494struct InlineCompletionState {
  495    inlay_ids: Vec<InlayId>,
  496    completion: InlineCompletion,
  497    completion_id: Option<SharedString>,
  498    invalidation_range: Range<Anchor>,
  499}
  500
  501enum EditPredictionSettings {
  502    Disabled,
  503    Enabled {
  504        show_in_menu: bool,
  505        preview_requires_modifier: bool,
  506    },
  507}
  508
  509impl EditPredictionSettings {
  510    pub fn is_enabled(&self) -> bool {
  511        match self {
  512            EditPredictionSettings::Disabled => false,
  513            EditPredictionSettings::Enabled { .. } => true,
  514        }
  515    }
  516}
  517
  518enum InlineCompletionHighlight {}
  519
  520pub enum MenuInlineCompletionsPolicy {
  521    Never,
  522    ByProvider,
  523}
  524
  525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  526struct EditorActionId(usize);
  527
  528impl EditorActionId {
  529    pub fn post_inc(&mut self) -> Self {
  530        let answer = self.0;
  531
  532        *self = Self(answer + 1);
  533
  534        Self(answer)
  535    }
  536}
  537
  538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  540
  541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  543
  544#[derive(Default)]
  545struct ScrollbarMarkerState {
  546    scrollbar_size: Size<Pixels>,
  547    dirty: bool,
  548    markers: Arc<[PaintQuad]>,
  549    pending_refresh: Option<Task<Result<()>>>,
  550}
  551
  552impl ScrollbarMarkerState {
  553    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  554        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  555    }
  556}
  557
  558#[derive(Clone, Debug)]
  559struct RunnableTasks {
  560    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  561    offset: MultiBufferOffset,
  562    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  563    column: u32,
  564    // Values of all named captures, including those starting with '_'
  565    extra_variables: HashMap<String, String>,
  566    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  567    context_range: Range<BufferOffset>,
  568}
  569
  570impl RunnableTasks {
  571    fn resolve<'a>(
  572        &'a self,
  573        cx: &'a task::TaskContext,
  574    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  575        self.templates.iter().filter_map(|(kind, template)| {
  576            template
  577                .resolve_task(&kind.to_id_base(), cx)
  578                .map(|task| (kind.clone(), task))
  579        })
  580    }
  581}
  582
  583#[derive(Clone)]
  584struct ResolvedTasks {
  585    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  586    position: Anchor,
  587}
  588#[derive(Copy, Clone, Debug)]
  589struct MultiBufferOffset(usize);
  590#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  591struct BufferOffset(usize);
  592
  593// Addons allow storing per-editor state in other crates (e.g. Vim)
  594pub trait Addon: 'static {
  595    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  596
  597    fn render_buffer_header_controls(
  598        &self,
  599        _: &ExcerptInfo,
  600        _: &Window,
  601        _: &App,
  602    ) -> Option<AnyElement> {
  603        None
  604    }
  605
  606    fn to_any(&self) -> &dyn std::any::Any;
  607}
  608
  609#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  610pub enum IsVimMode {
  611    Yes,
  612    No,
  613}
  614
  615/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  616///
  617/// See the [module level documentation](self) for more information.
  618pub struct Editor {
  619    focus_handle: FocusHandle,
  620    last_focused_descendant: Option<WeakFocusHandle>,
  621    /// The text buffer being edited
  622    buffer: Entity<MultiBuffer>,
  623    /// Map of how text in the buffer should be displayed.
  624    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  625    pub display_map: Entity<DisplayMap>,
  626    pub selections: SelectionsCollection,
  627    pub scroll_manager: ScrollManager,
  628    /// When inline assist editors are linked, they all render cursors because
  629    /// typing enters text into each of them, even the ones that aren't focused.
  630    pub(crate) show_cursor_when_unfocused: bool,
  631    columnar_selection_tail: Option<Anchor>,
  632    add_selections_state: Option<AddSelectionsState>,
  633    select_next_state: Option<SelectNextState>,
  634    select_prev_state: Option<SelectNextState>,
  635    selection_history: SelectionHistory,
  636    autoclose_regions: Vec<AutocloseRegion>,
  637    snippet_stack: InvalidationStack<SnippetState>,
  638    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  639    ime_transaction: Option<TransactionId>,
  640    active_diagnostics: Option<ActiveDiagnosticGroup>,
  641    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  642
  643    // TODO: make this a access method
  644    pub project: Option<Entity<Project>>,
  645    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  646    completion_provider: Option<Box<dyn CompletionProvider>>,
  647    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  648    blink_manager: Entity<BlinkManager>,
  649    show_cursor_names: bool,
  650    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  651    pub show_local_selections: bool,
  652    mode: EditorMode,
  653    show_breadcrumbs: bool,
  654    show_gutter: bool,
  655    show_scrollbars: bool,
  656    show_line_numbers: Option<bool>,
  657    use_relative_line_numbers: Option<bool>,
  658    show_git_diff_gutter: Option<bool>,
  659    show_code_actions: Option<bool>,
  660    show_runnables: Option<bool>,
  661    show_wrap_guides: Option<bool>,
  662    show_indent_guides: Option<bool>,
  663    placeholder_text: Option<Arc<str>>,
  664    highlight_order: usize,
  665    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  666    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  667    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  668    scrollbar_marker_state: ScrollbarMarkerState,
  669    active_indent_guides_state: ActiveIndentGuidesState,
  670    nav_history: Option<ItemNavHistory>,
  671    context_menu: RefCell<Option<CodeContextMenu>>,
  672    mouse_context_menu: Option<MouseContextMenu>,
  673    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  674    signature_help_state: SignatureHelpState,
  675    auto_signature_help: Option<bool>,
  676    find_all_references_task_sources: Vec<Anchor>,
  677    next_completion_id: CompletionId,
  678    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  679    code_actions_task: Option<Task<Result<()>>>,
  680    document_highlights_task: Option<Task<()>>,
  681    linked_editing_range_task: Option<Task<Option<()>>>,
  682    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  683    pending_rename: Option<RenameState>,
  684    searchable: bool,
  685    cursor_shape: CursorShape,
  686    current_line_highlight: Option<CurrentLineHighlight>,
  687    collapse_matches: bool,
  688    autoindent_mode: Option<AutoindentMode>,
  689    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  690    input_enabled: bool,
  691    use_modal_editing: bool,
  692    read_only: bool,
  693    leader_peer_id: Option<PeerId>,
  694    remote_id: Option<ViewId>,
  695    hover_state: HoverState,
  696    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  697    gutter_hovered: bool,
  698    hovered_link_state: Option<HoveredLinkState>,
  699    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  700    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  701    active_inline_completion: Option<InlineCompletionState>,
  702    /// Used to prevent flickering as the user types while the menu is open
  703    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  704    edit_prediction_settings: EditPredictionSettings,
  705    inline_completions_hidden_for_vim_mode: bool,
  706    show_inline_completions_override: Option<bool>,
  707    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  708    previewing_inline_completion: bool,
  709    inlay_hint_cache: InlayHintCache,
  710    next_inlay_id: usize,
  711    _subscriptions: Vec<Subscription>,
  712    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  713    gutter_dimensions: GutterDimensions,
  714    style: Option<EditorStyle>,
  715    text_style_refinement: Option<TextStyleRefinement>,
  716    next_editor_action_id: EditorActionId,
  717    editor_actions:
  718        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  719    use_autoclose: bool,
  720    use_auto_surround: bool,
  721    auto_replace_emoji_shortcode: bool,
  722    show_git_blame_gutter: bool,
  723    show_git_blame_inline: bool,
  724    show_git_blame_inline_delay_task: Option<Task<()>>,
  725    git_blame_inline_enabled: bool,
  726    serialize_dirty_buffers: bool,
  727    show_selection_menu: Option<bool>,
  728    blame: Option<Entity<GitBlame>>,
  729    blame_subscription: Option<Subscription>,
  730    custom_context_menu: Option<
  731        Box<
  732            dyn 'static
  733                + Fn(
  734                    &mut Self,
  735                    DisplayPoint,
  736                    &mut Window,
  737                    &mut Context<Self>,
  738                ) -> Option<Entity<ui::ContextMenu>>,
  739        >,
  740    >,
  741    last_bounds: Option<Bounds<Pixels>>,
  742    last_position_map: Option<Rc<PositionMap>>,
  743    expect_bounds_change: Option<Bounds<Pixels>>,
  744    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  745    tasks_update_task: Option<Task<()>>,
  746    in_project_search: bool,
  747    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  748    breadcrumb_header: Option<String>,
  749    focused_block: Option<FocusedBlock>,
  750    next_scroll_position: NextScrollCursorCenterTopBottom,
  751    addons: HashMap<TypeId, Box<dyn Addon>>,
  752    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  753    selection_mark_mode: bool,
  754    toggle_fold_multiple_buffers: Task<()>,
  755    _scroll_cursor_center_top_bottom_task: Task<()>,
  756}
  757
  758#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  759enum NextScrollCursorCenterTopBottom {
  760    #[default]
  761    Center,
  762    Top,
  763    Bottom,
  764}
  765
  766impl NextScrollCursorCenterTopBottom {
  767    fn next(&self) -> Self {
  768        match self {
  769            Self::Center => Self::Top,
  770            Self::Top => Self::Bottom,
  771            Self::Bottom => Self::Center,
  772        }
  773    }
  774}
  775
  776#[derive(Clone)]
  777pub struct EditorSnapshot {
  778    pub mode: EditorMode,
  779    show_gutter: bool,
  780    show_line_numbers: Option<bool>,
  781    show_git_diff_gutter: Option<bool>,
  782    show_code_actions: Option<bool>,
  783    show_runnables: Option<bool>,
  784    git_blame_gutter_max_author_length: Option<usize>,
  785    pub display_snapshot: DisplaySnapshot,
  786    pub placeholder_text: Option<Arc<str>>,
  787    is_focused: bool,
  788    scroll_anchor: ScrollAnchor,
  789    ongoing_scroll: OngoingScroll,
  790    current_line_highlight: CurrentLineHighlight,
  791    gutter_hovered: bool,
  792}
  793
  794const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  795
  796#[derive(Default, Debug, Clone, Copy)]
  797pub struct GutterDimensions {
  798    pub left_padding: Pixels,
  799    pub right_padding: Pixels,
  800    pub width: Pixels,
  801    pub margin: Pixels,
  802    pub git_blame_entries_width: Option<Pixels>,
  803}
  804
  805impl GutterDimensions {
  806    /// The full width of the space taken up by the gutter.
  807    pub fn full_width(&self) -> Pixels {
  808        self.margin + self.width
  809    }
  810
  811    /// The width of the space reserved for the fold indicators,
  812    /// use alongside 'justify_end' and `gutter_width` to
  813    /// right align content with the line numbers
  814    pub fn fold_area_width(&self) -> Pixels {
  815        self.margin + self.right_padding
  816    }
  817}
  818
  819#[derive(Debug)]
  820pub struct RemoteSelection {
  821    pub replica_id: ReplicaId,
  822    pub selection: Selection<Anchor>,
  823    pub cursor_shape: CursorShape,
  824    pub peer_id: PeerId,
  825    pub line_mode: bool,
  826    pub participant_index: Option<ParticipantIndex>,
  827    pub user_name: Option<SharedString>,
  828}
  829
  830#[derive(Clone, Debug)]
  831struct SelectionHistoryEntry {
  832    selections: Arc<[Selection<Anchor>]>,
  833    select_next_state: Option<SelectNextState>,
  834    select_prev_state: Option<SelectNextState>,
  835    add_selections_state: Option<AddSelectionsState>,
  836}
  837
  838enum SelectionHistoryMode {
  839    Normal,
  840    Undoing,
  841    Redoing,
  842}
  843
  844#[derive(Clone, PartialEq, Eq, Hash)]
  845struct HoveredCursor {
  846    replica_id: u16,
  847    selection_id: usize,
  848}
  849
  850impl Default for SelectionHistoryMode {
  851    fn default() -> Self {
  852        Self::Normal
  853    }
  854}
  855
  856#[derive(Default)]
  857struct SelectionHistory {
  858    #[allow(clippy::type_complexity)]
  859    selections_by_transaction:
  860        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  861    mode: SelectionHistoryMode,
  862    undo_stack: VecDeque<SelectionHistoryEntry>,
  863    redo_stack: VecDeque<SelectionHistoryEntry>,
  864}
  865
  866impl SelectionHistory {
  867    fn insert_transaction(
  868        &mut self,
  869        transaction_id: TransactionId,
  870        selections: Arc<[Selection<Anchor>]>,
  871    ) {
  872        self.selections_by_transaction
  873            .insert(transaction_id, (selections, None));
  874    }
  875
  876    #[allow(clippy::type_complexity)]
  877    fn transaction(
  878        &self,
  879        transaction_id: TransactionId,
  880    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  881        self.selections_by_transaction.get(&transaction_id)
  882    }
  883
  884    #[allow(clippy::type_complexity)]
  885    fn transaction_mut(
  886        &mut self,
  887        transaction_id: TransactionId,
  888    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  889        self.selections_by_transaction.get_mut(&transaction_id)
  890    }
  891
  892    fn push(&mut self, entry: SelectionHistoryEntry) {
  893        if !entry.selections.is_empty() {
  894            match self.mode {
  895                SelectionHistoryMode::Normal => {
  896                    self.push_undo(entry);
  897                    self.redo_stack.clear();
  898                }
  899                SelectionHistoryMode::Undoing => self.push_redo(entry),
  900                SelectionHistoryMode::Redoing => self.push_undo(entry),
  901            }
  902        }
  903    }
  904
  905    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  906        if self
  907            .undo_stack
  908            .back()
  909            .map_or(true, |e| e.selections != entry.selections)
  910        {
  911            self.undo_stack.push_back(entry);
  912            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  913                self.undo_stack.pop_front();
  914            }
  915        }
  916    }
  917
  918    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  919        if self
  920            .redo_stack
  921            .back()
  922            .map_or(true, |e| e.selections != entry.selections)
  923        {
  924            self.redo_stack.push_back(entry);
  925            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  926                self.redo_stack.pop_front();
  927            }
  928        }
  929    }
  930}
  931
  932struct RowHighlight {
  933    index: usize,
  934    range: Range<Anchor>,
  935    color: Hsla,
  936    should_autoscroll: bool,
  937}
  938
  939#[derive(Clone, Debug)]
  940struct AddSelectionsState {
  941    above: bool,
  942    stack: Vec<usize>,
  943}
  944
  945#[derive(Clone)]
  946struct SelectNextState {
  947    query: AhoCorasick,
  948    wordwise: bool,
  949    done: bool,
  950}
  951
  952impl std::fmt::Debug for SelectNextState {
  953    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  954        f.debug_struct(std::any::type_name::<Self>())
  955            .field("wordwise", &self.wordwise)
  956            .field("done", &self.done)
  957            .finish()
  958    }
  959}
  960
  961#[derive(Debug)]
  962struct AutocloseRegion {
  963    selection_id: usize,
  964    range: Range<Anchor>,
  965    pair: BracketPair,
  966}
  967
  968#[derive(Debug)]
  969struct SnippetState {
  970    ranges: Vec<Vec<Range<Anchor>>>,
  971    active_index: usize,
  972    choices: Vec<Option<Vec<String>>>,
  973}
  974
  975#[doc(hidden)]
  976pub struct RenameState {
  977    pub range: Range<Anchor>,
  978    pub old_name: Arc<str>,
  979    pub editor: Entity<Editor>,
  980    block_id: CustomBlockId,
  981}
  982
  983struct InvalidationStack<T>(Vec<T>);
  984
  985struct RegisteredInlineCompletionProvider {
  986    provider: Arc<dyn InlineCompletionProviderHandle>,
  987    _subscription: Subscription,
  988}
  989
  990#[derive(Debug)]
  991struct ActiveDiagnosticGroup {
  992    primary_range: Range<Anchor>,
  993    primary_message: String,
  994    group_id: usize,
  995    blocks: HashMap<CustomBlockId, Diagnostic>,
  996    is_valid: bool,
  997}
  998
  999#[derive(Serialize, Deserialize, Clone, Debug)]
 1000pub struct ClipboardSelection {
 1001    pub len: usize,
 1002    pub is_entire_line: bool,
 1003    pub first_line_indent: u32,
 1004}
 1005
 1006#[derive(Debug)]
 1007pub(crate) struct NavigationData {
 1008    cursor_anchor: Anchor,
 1009    cursor_position: Point,
 1010    scroll_anchor: ScrollAnchor,
 1011    scroll_top_row: u32,
 1012}
 1013
 1014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1015pub enum GotoDefinitionKind {
 1016    Symbol,
 1017    Declaration,
 1018    Type,
 1019    Implementation,
 1020}
 1021
 1022#[derive(Debug, Clone)]
 1023enum InlayHintRefreshReason {
 1024    Toggle(bool),
 1025    SettingsChange(InlayHintSettings),
 1026    NewLinesShown,
 1027    BufferEdited(HashSet<Arc<Language>>),
 1028    RefreshRequested,
 1029    ExcerptsRemoved(Vec<ExcerptId>),
 1030}
 1031
 1032impl InlayHintRefreshReason {
 1033    fn description(&self) -> &'static str {
 1034        match self {
 1035            Self::Toggle(_) => "toggle",
 1036            Self::SettingsChange(_) => "settings change",
 1037            Self::NewLinesShown => "new lines shown",
 1038            Self::BufferEdited(_) => "buffer edited",
 1039            Self::RefreshRequested => "refresh requested",
 1040            Self::ExcerptsRemoved(_) => "excerpts removed",
 1041        }
 1042    }
 1043}
 1044
 1045pub enum FormatTarget {
 1046    Buffers,
 1047    Ranges(Vec<Range<MultiBufferPoint>>),
 1048}
 1049
 1050pub(crate) struct FocusedBlock {
 1051    id: BlockId,
 1052    focus_handle: WeakFocusHandle,
 1053}
 1054
 1055#[derive(Clone)]
 1056enum JumpData {
 1057    MultiBufferRow {
 1058        row: MultiBufferRow,
 1059        line_offset_from_top: u32,
 1060    },
 1061    MultiBufferPoint {
 1062        excerpt_id: ExcerptId,
 1063        position: Point,
 1064        anchor: text::Anchor,
 1065        line_offset_from_top: u32,
 1066    },
 1067}
 1068
 1069pub enum MultibufferSelectionMode {
 1070    First,
 1071    All,
 1072}
 1073
 1074impl Editor {
 1075    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1076        let buffer = cx.new(|cx| Buffer::local("", cx));
 1077        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1078        Self::new(
 1079            EditorMode::SingleLine { auto_width: false },
 1080            buffer,
 1081            None,
 1082            false,
 1083            window,
 1084            cx,
 1085        )
 1086    }
 1087
 1088    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1089        let buffer = cx.new(|cx| Buffer::local("", cx));
 1090        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1091        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1092    }
 1093
 1094    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1095        let buffer = cx.new(|cx| Buffer::local("", cx));
 1096        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1097        Self::new(
 1098            EditorMode::SingleLine { auto_width: true },
 1099            buffer,
 1100            None,
 1101            false,
 1102            window,
 1103            cx,
 1104        )
 1105    }
 1106
 1107    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1108        let buffer = cx.new(|cx| Buffer::local("", cx));
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(
 1111            EditorMode::AutoHeight { max_lines },
 1112            buffer,
 1113            None,
 1114            false,
 1115            window,
 1116            cx,
 1117        )
 1118    }
 1119
 1120    pub fn for_buffer(
 1121        buffer: Entity<Buffer>,
 1122        project: Option<Entity<Project>>,
 1123        window: &mut Window,
 1124        cx: &mut Context<Self>,
 1125    ) -> Self {
 1126        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1127        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1128    }
 1129
 1130    pub fn for_multibuffer(
 1131        buffer: Entity<MultiBuffer>,
 1132        project: Option<Entity<Project>>,
 1133        show_excerpt_controls: bool,
 1134        window: &mut Window,
 1135        cx: &mut Context<Self>,
 1136    ) -> Self {
 1137        Self::new(
 1138            EditorMode::Full,
 1139            buffer,
 1140            project,
 1141            show_excerpt_controls,
 1142            window,
 1143            cx,
 1144        )
 1145    }
 1146
 1147    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1148        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1149        let mut clone = Self::new(
 1150            self.mode,
 1151            self.buffer.clone(),
 1152            self.project.clone(),
 1153            show_excerpt_controls,
 1154            window,
 1155            cx,
 1156        );
 1157        self.display_map.update(cx, |display_map, cx| {
 1158            let snapshot = display_map.snapshot(cx);
 1159            clone.display_map.update(cx, |display_map, cx| {
 1160                display_map.set_state(&snapshot, cx);
 1161            });
 1162        });
 1163        clone.selections.clone_state(&self.selections);
 1164        clone.scroll_manager.clone_state(&self.scroll_manager);
 1165        clone.searchable = self.searchable;
 1166        clone
 1167    }
 1168
 1169    pub fn new(
 1170        mode: EditorMode,
 1171        buffer: Entity<MultiBuffer>,
 1172        project: Option<Entity<Project>>,
 1173        show_excerpt_controls: bool,
 1174        window: &mut Window,
 1175        cx: &mut Context<Self>,
 1176    ) -> Self {
 1177        let style = window.text_style();
 1178        let font_size = style.font_size.to_pixels(window.rem_size());
 1179        let editor = cx.entity().downgrade();
 1180        let fold_placeholder = FoldPlaceholder {
 1181            constrain_width: true,
 1182            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1183                let editor = editor.clone();
 1184                div()
 1185                    .id(fold_id)
 1186                    .bg(cx.theme().colors().ghost_element_background)
 1187                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1188                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1189                    .rounded_sm()
 1190                    .size_full()
 1191                    .cursor_pointer()
 1192                    .child("")
 1193                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1194                    .on_click(move |_, _window, cx| {
 1195                        editor
 1196                            .update(cx, |editor, cx| {
 1197                                editor.unfold_ranges(
 1198                                    &[fold_range.start..fold_range.end],
 1199                                    true,
 1200                                    false,
 1201                                    cx,
 1202                                );
 1203                                cx.stop_propagation();
 1204                            })
 1205                            .ok();
 1206                    })
 1207                    .into_any()
 1208            }),
 1209            merge_adjacent: true,
 1210            ..Default::default()
 1211        };
 1212        let display_map = cx.new(|cx| {
 1213            DisplayMap::new(
 1214                buffer.clone(),
 1215                style.font(),
 1216                font_size,
 1217                None,
 1218                show_excerpt_controls,
 1219                FILE_HEADER_HEIGHT,
 1220                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1221                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1222                fold_placeholder,
 1223                cx,
 1224            )
 1225        });
 1226
 1227        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1228
 1229        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1230
 1231        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1232            .then(|| language_settings::SoftWrap::None);
 1233
 1234        let mut project_subscriptions = Vec::new();
 1235        if mode == EditorMode::Full {
 1236            if let Some(project) = project.as_ref() {
 1237                if buffer.read(cx).is_singleton() {
 1238                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1239                        cx.emit(EditorEvent::TitleChanged);
 1240                    }));
 1241                }
 1242                project_subscriptions.push(cx.subscribe_in(
 1243                    project,
 1244                    window,
 1245                    |editor, _, event, window, cx| {
 1246                        if let project::Event::RefreshInlayHints = event {
 1247                            editor
 1248                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1249                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1250                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1251                                let focus_handle = editor.focus_handle(cx);
 1252                                if focus_handle.is_focused(window) {
 1253                                    let snapshot = buffer.read(cx).snapshot();
 1254                                    for (range, snippet) in snippet_edits {
 1255                                        let editor_range =
 1256                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1257                                        editor
 1258                                            .insert_snippet(
 1259                                                &[editor_range],
 1260                                                snippet.clone(),
 1261                                                window,
 1262                                                cx,
 1263                                            )
 1264                                            .ok();
 1265                                    }
 1266                                }
 1267                            }
 1268                        }
 1269                    },
 1270                ));
 1271                if let Some(task_inventory) = project
 1272                    .read(cx)
 1273                    .task_store()
 1274                    .read(cx)
 1275                    .task_inventory()
 1276                    .cloned()
 1277                {
 1278                    project_subscriptions.push(cx.observe_in(
 1279                        &task_inventory,
 1280                        window,
 1281                        |editor, _, window, cx| {
 1282                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1283                        },
 1284                    ));
 1285                }
 1286            }
 1287        }
 1288
 1289        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1290
 1291        let inlay_hint_settings =
 1292            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1293        let focus_handle = cx.focus_handle();
 1294        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1295            .detach();
 1296        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1297            .detach();
 1298        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1299            .detach();
 1300        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1301            .detach();
 1302
 1303        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1304            Some(false)
 1305        } else {
 1306            None
 1307        };
 1308
 1309        let mut code_action_providers = Vec::new();
 1310        if let Some(project) = project.clone() {
 1311            get_uncommitted_diff_for_buffer(
 1312                &project,
 1313                buffer.read(cx).all_buffers(),
 1314                buffer.clone(),
 1315                cx,
 1316            );
 1317            code_action_providers.push(Rc::new(project) as Rc<_>);
 1318        }
 1319
 1320        let mut this = Self {
 1321            focus_handle,
 1322            show_cursor_when_unfocused: false,
 1323            last_focused_descendant: None,
 1324            buffer: buffer.clone(),
 1325            display_map: display_map.clone(),
 1326            selections,
 1327            scroll_manager: ScrollManager::new(cx),
 1328            columnar_selection_tail: None,
 1329            add_selections_state: None,
 1330            select_next_state: None,
 1331            select_prev_state: None,
 1332            selection_history: Default::default(),
 1333            autoclose_regions: Default::default(),
 1334            snippet_stack: Default::default(),
 1335            select_larger_syntax_node_stack: Vec::new(),
 1336            ime_transaction: Default::default(),
 1337            active_diagnostics: None,
 1338            soft_wrap_mode_override,
 1339            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1340            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1341            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1342            project,
 1343            blink_manager: blink_manager.clone(),
 1344            show_local_selections: true,
 1345            show_scrollbars: true,
 1346            mode,
 1347            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1348            show_gutter: mode == EditorMode::Full,
 1349            show_line_numbers: None,
 1350            use_relative_line_numbers: None,
 1351            show_git_diff_gutter: None,
 1352            show_code_actions: None,
 1353            show_runnables: None,
 1354            show_wrap_guides: None,
 1355            show_indent_guides,
 1356            placeholder_text: None,
 1357            highlight_order: 0,
 1358            highlighted_rows: HashMap::default(),
 1359            background_highlights: Default::default(),
 1360            gutter_highlights: TreeMap::default(),
 1361            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1362            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1363            nav_history: None,
 1364            context_menu: RefCell::new(None),
 1365            mouse_context_menu: None,
 1366            completion_tasks: Default::default(),
 1367            signature_help_state: SignatureHelpState::default(),
 1368            auto_signature_help: None,
 1369            find_all_references_task_sources: Vec::new(),
 1370            next_completion_id: 0,
 1371            next_inlay_id: 0,
 1372            code_action_providers,
 1373            available_code_actions: Default::default(),
 1374            code_actions_task: Default::default(),
 1375            document_highlights_task: Default::default(),
 1376            linked_editing_range_task: Default::default(),
 1377            pending_rename: Default::default(),
 1378            searchable: true,
 1379            cursor_shape: EditorSettings::get_global(cx)
 1380                .cursor_shape
 1381                .unwrap_or_default(),
 1382            current_line_highlight: None,
 1383            autoindent_mode: Some(AutoindentMode::EachLine),
 1384            collapse_matches: false,
 1385            workspace: None,
 1386            input_enabled: true,
 1387            use_modal_editing: mode == EditorMode::Full,
 1388            read_only: false,
 1389            use_autoclose: true,
 1390            use_auto_surround: true,
 1391            auto_replace_emoji_shortcode: false,
 1392            leader_peer_id: None,
 1393            remote_id: None,
 1394            hover_state: Default::default(),
 1395            pending_mouse_down: None,
 1396            hovered_link_state: Default::default(),
 1397            edit_prediction_provider: None,
 1398            active_inline_completion: None,
 1399            stale_inline_completion_in_menu: None,
 1400            previewing_inline_completion: false,
 1401            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1402
 1403            gutter_hovered: false,
 1404            pixel_position_of_newest_cursor: None,
 1405            last_bounds: None,
 1406            last_position_map: None,
 1407            expect_bounds_change: None,
 1408            gutter_dimensions: GutterDimensions::default(),
 1409            style: None,
 1410            show_cursor_names: false,
 1411            hovered_cursors: Default::default(),
 1412            next_editor_action_id: EditorActionId::default(),
 1413            editor_actions: Rc::default(),
 1414            inline_completions_hidden_for_vim_mode: false,
 1415            show_inline_completions_override: None,
 1416            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1417            edit_prediction_settings: EditPredictionSettings::Disabled,
 1418            custom_context_menu: None,
 1419            show_git_blame_gutter: false,
 1420            show_git_blame_inline: false,
 1421            show_selection_menu: None,
 1422            show_git_blame_inline_delay_task: None,
 1423            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1424            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1425                .session
 1426                .restore_unsaved_buffers,
 1427            blame: None,
 1428            blame_subscription: None,
 1429            tasks: Default::default(),
 1430            _subscriptions: vec![
 1431                cx.observe(&buffer, Self::on_buffer_changed),
 1432                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1433                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1434                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1435                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1436                cx.observe_window_activation(window, |editor, window, cx| {
 1437                    let active = window.is_window_active();
 1438                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1439                        if active {
 1440                            blink_manager.enable(cx);
 1441                        } else {
 1442                            blink_manager.disable(cx);
 1443                        }
 1444                    });
 1445                }),
 1446            ],
 1447            tasks_update_task: None,
 1448            linked_edit_ranges: Default::default(),
 1449            in_project_search: false,
 1450            previous_search_ranges: None,
 1451            breadcrumb_header: None,
 1452            focused_block: None,
 1453            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1454            addons: HashMap::default(),
 1455            registered_buffers: HashMap::default(),
 1456            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1457            selection_mark_mode: false,
 1458            toggle_fold_multiple_buffers: Task::ready(()),
 1459            text_style_refinement: None,
 1460        };
 1461        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1462        this._subscriptions.extend(project_subscriptions);
 1463
 1464        this.end_selection(window, cx);
 1465        this.scroll_manager.show_scrollbar(window, cx);
 1466
 1467        if mode == EditorMode::Full {
 1468            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1469            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1470
 1471            if this.git_blame_inline_enabled {
 1472                this.git_blame_inline_enabled = true;
 1473                this.start_git_blame_inline(false, window, cx);
 1474            }
 1475
 1476            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1477                if let Some(project) = this.project.as_ref() {
 1478                    let lsp_store = project.read(cx).lsp_store();
 1479                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1480                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1481                    });
 1482                    this.registered_buffers
 1483                        .insert(buffer.read(cx).remote_id(), handle);
 1484                }
 1485            }
 1486        }
 1487
 1488        this.report_editor_event("Editor Opened", None, cx);
 1489        this
 1490    }
 1491
 1492    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1493        self.mouse_context_menu
 1494            .as_ref()
 1495            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1496    }
 1497
 1498    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1499        let mut key_context = KeyContext::new_with_defaults();
 1500        key_context.add("Editor");
 1501        let mode = match self.mode {
 1502            EditorMode::SingleLine { .. } => "single_line",
 1503            EditorMode::AutoHeight { .. } => "auto_height",
 1504            EditorMode::Full => "full",
 1505        };
 1506
 1507        if EditorSettings::jupyter_enabled(cx) {
 1508            key_context.add("jupyter");
 1509        }
 1510
 1511        key_context.set("mode", mode);
 1512        if self.pending_rename.is_some() {
 1513            key_context.add("renaming");
 1514        }
 1515
 1516        let mut showing_completions = false;
 1517
 1518        match self.context_menu.borrow().as_ref() {
 1519            Some(CodeContextMenu::Completions(_)) => {
 1520                key_context.add("menu");
 1521                key_context.add("showing_completions");
 1522                showing_completions = true;
 1523            }
 1524            Some(CodeContextMenu::CodeActions(_)) => {
 1525                key_context.add("menu");
 1526                key_context.add("showing_code_actions")
 1527            }
 1528            None => {}
 1529        }
 1530
 1531        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1532        if !self.focus_handle(cx).contains_focused(window, cx)
 1533            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1534        {
 1535            for addon in self.addons.values() {
 1536                addon.extend_key_context(&mut key_context, cx)
 1537            }
 1538        }
 1539
 1540        if let Some(extension) = self
 1541            .buffer
 1542            .read(cx)
 1543            .as_singleton()
 1544            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1545        {
 1546            key_context.set("extension", extension.to_string());
 1547        }
 1548
 1549        if self.has_active_inline_completion() {
 1550            key_context.add("copilot_suggestion");
 1551            key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1552
 1553            if showing_completions || self.edit_prediction_requires_modifier() {
 1554                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1555            }
 1556        }
 1557
 1558        if self.selection_mark_mode {
 1559            key_context.add("selection_mode");
 1560        }
 1561
 1562        key_context
 1563    }
 1564
 1565    pub fn accept_edit_prediction_keybind(
 1566        &self,
 1567        window: &Window,
 1568        cx: &App,
 1569    ) -> AcceptEditPredictionBinding {
 1570        let mut context = self.key_context(window, cx);
 1571        context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1572
 1573        AcceptEditPredictionBinding(
 1574            window
 1575                .bindings_for_action_in_context(&AcceptEditPrediction, context)
 1576                .into_iter()
 1577                .rev()
 1578                .next(),
 1579        )
 1580    }
 1581
 1582    pub fn new_file(
 1583        workspace: &mut Workspace,
 1584        _: &workspace::NewFile,
 1585        window: &mut Window,
 1586        cx: &mut Context<Workspace>,
 1587    ) {
 1588        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1589            "Failed to create buffer",
 1590            window,
 1591            cx,
 1592            |e, _, _| match e.error_code() {
 1593                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1594                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1595                e.error_tag("required").unwrap_or("the latest version")
 1596            )),
 1597                _ => None,
 1598            },
 1599        );
 1600    }
 1601
 1602    pub fn new_in_workspace(
 1603        workspace: &mut Workspace,
 1604        window: &mut Window,
 1605        cx: &mut Context<Workspace>,
 1606    ) -> Task<Result<Entity<Editor>>> {
 1607        let project = workspace.project().clone();
 1608        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1609
 1610        cx.spawn_in(window, |workspace, mut cx| async move {
 1611            let buffer = create.await?;
 1612            workspace.update_in(&mut cx, |workspace, window, cx| {
 1613                let editor =
 1614                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1615                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1616                editor
 1617            })
 1618        })
 1619    }
 1620
 1621    fn new_file_vertical(
 1622        workspace: &mut Workspace,
 1623        _: &workspace::NewFileSplitVertical,
 1624        window: &mut Window,
 1625        cx: &mut Context<Workspace>,
 1626    ) {
 1627        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1628    }
 1629
 1630    fn new_file_horizontal(
 1631        workspace: &mut Workspace,
 1632        _: &workspace::NewFileSplitHorizontal,
 1633        window: &mut Window,
 1634        cx: &mut Context<Workspace>,
 1635    ) {
 1636        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1637    }
 1638
 1639    fn new_file_in_direction(
 1640        workspace: &mut Workspace,
 1641        direction: SplitDirection,
 1642        window: &mut Window,
 1643        cx: &mut Context<Workspace>,
 1644    ) {
 1645        let project = workspace.project().clone();
 1646        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1647
 1648        cx.spawn_in(window, |workspace, mut cx| async move {
 1649            let buffer = create.await?;
 1650            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1651                workspace.split_item(
 1652                    direction,
 1653                    Box::new(
 1654                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1655                    ),
 1656                    window,
 1657                    cx,
 1658                )
 1659            })?;
 1660            anyhow::Ok(())
 1661        })
 1662        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1663            match e.error_code() {
 1664                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1665                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1666                e.error_tag("required").unwrap_or("the latest version")
 1667            )),
 1668                _ => None,
 1669            }
 1670        });
 1671    }
 1672
 1673    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1674        self.leader_peer_id
 1675    }
 1676
 1677    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1678        &self.buffer
 1679    }
 1680
 1681    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1682        self.workspace.as_ref()?.0.upgrade()
 1683    }
 1684
 1685    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1686        self.buffer().read(cx).title(cx)
 1687    }
 1688
 1689    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1690        let git_blame_gutter_max_author_length = self
 1691            .render_git_blame_gutter(cx)
 1692            .then(|| {
 1693                if let Some(blame) = self.blame.as_ref() {
 1694                    let max_author_length =
 1695                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1696                    Some(max_author_length)
 1697                } else {
 1698                    None
 1699                }
 1700            })
 1701            .flatten();
 1702
 1703        EditorSnapshot {
 1704            mode: self.mode,
 1705            show_gutter: self.show_gutter,
 1706            show_line_numbers: self.show_line_numbers,
 1707            show_git_diff_gutter: self.show_git_diff_gutter,
 1708            show_code_actions: self.show_code_actions,
 1709            show_runnables: self.show_runnables,
 1710            git_blame_gutter_max_author_length,
 1711            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1712            scroll_anchor: self.scroll_manager.anchor(),
 1713            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1714            placeholder_text: self.placeholder_text.clone(),
 1715            is_focused: self.focus_handle.is_focused(window),
 1716            current_line_highlight: self
 1717                .current_line_highlight
 1718                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1719            gutter_hovered: self.gutter_hovered,
 1720        }
 1721    }
 1722
 1723    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1724        self.buffer.read(cx).language_at(point, cx)
 1725    }
 1726
 1727    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1728        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1729    }
 1730
 1731    pub fn active_excerpt(
 1732        &self,
 1733        cx: &App,
 1734    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1735        self.buffer
 1736            .read(cx)
 1737            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1738    }
 1739
 1740    pub fn mode(&self) -> EditorMode {
 1741        self.mode
 1742    }
 1743
 1744    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1745        self.collaboration_hub.as_deref()
 1746    }
 1747
 1748    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1749        self.collaboration_hub = Some(hub);
 1750    }
 1751
 1752    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1753        self.in_project_search = in_project_search;
 1754    }
 1755
 1756    pub fn set_custom_context_menu(
 1757        &mut self,
 1758        f: impl 'static
 1759            + Fn(
 1760                &mut Self,
 1761                DisplayPoint,
 1762                &mut Window,
 1763                &mut Context<Self>,
 1764            ) -> Option<Entity<ui::ContextMenu>>,
 1765    ) {
 1766        self.custom_context_menu = Some(Box::new(f))
 1767    }
 1768
 1769    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1770        self.completion_provider = provider;
 1771    }
 1772
 1773    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1774        self.semantics_provider.clone()
 1775    }
 1776
 1777    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1778        self.semantics_provider = provider;
 1779    }
 1780
 1781    pub fn set_edit_prediction_provider<T>(
 1782        &mut self,
 1783        provider: Option<Entity<T>>,
 1784        window: &mut Window,
 1785        cx: &mut Context<Self>,
 1786    ) where
 1787        T: EditPredictionProvider,
 1788    {
 1789        self.edit_prediction_provider =
 1790            provider.map(|provider| RegisteredInlineCompletionProvider {
 1791                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1792                    if this.focus_handle.is_focused(window) {
 1793                        this.update_visible_inline_completion(window, cx);
 1794                    }
 1795                }),
 1796                provider: Arc::new(provider),
 1797            });
 1798        self.refresh_inline_completion(false, false, window, cx);
 1799    }
 1800
 1801    pub fn placeholder_text(&self) -> Option<&str> {
 1802        self.placeholder_text.as_deref()
 1803    }
 1804
 1805    pub fn set_placeholder_text(
 1806        &mut self,
 1807        placeholder_text: impl Into<Arc<str>>,
 1808        cx: &mut Context<Self>,
 1809    ) {
 1810        let placeholder_text = Some(placeholder_text.into());
 1811        if self.placeholder_text != placeholder_text {
 1812            self.placeholder_text = placeholder_text;
 1813            cx.notify();
 1814        }
 1815    }
 1816
 1817    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1818        self.cursor_shape = cursor_shape;
 1819
 1820        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1821        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1822
 1823        cx.notify();
 1824    }
 1825
 1826    pub fn set_current_line_highlight(
 1827        &mut self,
 1828        current_line_highlight: Option<CurrentLineHighlight>,
 1829    ) {
 1830        self.current_line_highlight = current_line_highlight;
 1831    }
 1832
 1833    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1834        self.collapse_matches = collapse_matches;
 1835    }
 1836
 1837    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1838        let buffers = self.buffer.read(cx).all_buffers();
 1839        let Some(lsp_store) = self.lsp_store(cx) else {
 1840            return;
 1841        };
 1842        lsp_store.update(cx, |lsp_store, cx| {
 1843            for buffer in buffers {
 1844                self.registered_buffers
 1845                    .entry(buffer.read(cx).remote_id())
 1846                    .or_insert_with(|| {
 1847                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1848                    });
 1849            }
 1850        })
 1851    }
 1852
 1853    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1854        if self.collapse_matches {
 1855            return range.start..range.start;
 1856        }
 1857        range.clone()
 1858    }
 1859
 1860    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1861        if self.display_map.read(cx).clip_at_line_ends != clip {
 1862            self.display_map
 1863                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1864        }
 1865    }
 1866
 1867    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1868        self.input_enabled = input_enabled;
 1869    }
 1870
 1871    pub fn set_inline_completions_hidden_for_vim_mode(
 1872        &mut self,
 1873        hidden: bool,
 1874        window: &mut Window,
 1875        cx: &mut Context<Self>,
 1876    ) {
 1877        if hidden != self.inline_completions_hidden_for_vim_mode {
 1878            self.inline_completions_hidden_for_vim_mode = hidden;
 1879            if hidden {
 1880                self.update_visible_inline_completion(window, cx);
 1881            } else {
 1882                self.refresh_inline_completion(true, false, window, cx);
 1883            }
 1884        }
 1885    }
 1886
 1887    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1888        self.menu_inline_completions_policy = value;
 1889    }
 1890
 1891    pub fn set_autoindent(&mut self, autoindent: bool) {
 1892        if autoindent {
 1893            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1894        } else {
 1895            self.autoindent_mode = None;
 1896        }
 1897    }
 1898
 1899    pub fn read_only(&self, cx: &App) -> bool {
 1900        self.read_only || self.buffer.read(cx).read_only()
 1901    }
 1902
 1903    pub fn set_read_only(&mut self, read_only: bool) {
 1904        self.read_only = read_only;
 1905    }
 1906
 1907    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1908        self.use_autoclose = autoclose;
 1909    }
 1910
 1911    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1912        self.use_auto_surround = auto_surround;
 1913    }
 1914
 1915    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1916        self.auto_replace_emoji_shortcode = auto_replace;
 1917    }
 1918
 1919    pub fn toggle_inline_completions(
 1920        &mut self,
 1921        _: &ToggleEditPrediction,
 1922        window: &mut Window,
 1923        cx: &mut Context<Self>,
 1924    ) {
 1925        if self.show_inline_completions_override.is_some() {
 1926            self.set_show_edit_predictions(None, window, cx);
 1927        } else {
 1928            let show_edit_predictions = !self.edit_predictions_enabled();
 1929            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1930        }
 1931    }
 1932
 1933    pub fn set_show_edit_predictions(
 1934        &mut self,
 1935        show_edit_predictions: Option<bool>,
 1936        window: &mut Window,
 1937        cx: &mut Context<Self>,
 1938    ) {
 1939        self.show_inline_completions_override = show_edit_predictions;
 1940        self.refresh_inline_completion(false, true, window, cx);
 1941    }
 1942
 1943    fn inline_completions_disabled_in_scope(
 1944        &self,
 1945        buffer: &Entity<Buffer>,
 1946        buffer_position: language::Anchor,
 1947        cx: &App,
 1948    ) -> bool {
 1949        let snapshot = buffer.read(cx).snapshot();
 1950        let settings = snapshot.settings_at(buffer_position, cx);
 1951
 1952        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1953            return false;
 1954        };
 1955
 1956        scope.override_name().map_or(false, |scope_name| {
 1957            settings
 1958                .edit_predictions_disabled_in
 1959                .iter()
 1960                .any(|s| s == scope_name)
 1961        })
 1962    }
 1963
 1964    pub fn set_use_modal_editing(&mut self, to: bool) {
 1965        self.use_modal_editing = to;
 1966    }
 1967
 1968    pub fn use_modal_editing(&self) -> bool {
 1969        self.use_modal_editing
 1970    }
 1971
 1972    fn selections_did_change(
 1973        &mut self,
 1974        local: bool,
 1975        old_cursor_position: &Anchor,
 1976        show_completions: bool,
 1977        window: &mut Window,
 1978        cx: &mut Context<Self>,
 1979    ) {
 1980        window.invalidate_character_coordinates();
 1981
 1982        // Copy selections to primary selection buffer
 1983        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1984        if local {
 1985            let selections = self.selections.all::<usize>(cx);
 1986            let buffer_handle = self.buffer.read(cx).read(cx);
 1987
 1988            let mut text = String::new();
 1989            for (index, selection) in selections.iter().enumerate() {
 1990                let text_for_selection = buffer_handle
 1991                    .text_for_range(selection.start..selection.end)
 1992                    .collect::<String>();
 1993
 1994                text.push_str(&text_for_selection);
 1995                if index != selections.len() - 1 {
 1996                    text.push('\n');
 1997                }
 1998            }
 1999
 2000            if !text.is_empty() {
 2001                cx.write_to_primary(ClipboardItem::new_string(text));
 2002            }
 2003        }
 2004
 2005        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2006            self.buffer.update(cx, |buffer, cx| {
 2007                buffer.set_active_selections(
 2008                    &self.selections.disjoint_anchors(),
 2009                    self.selections.line_mode,
 2010                    self.cursor_shape,
 2011                    cx,
 2012                )
 2013            });
 2014        }
 2015        let display_map = self
 2016            .display_map
 2017            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2018        let buffer = &display_map.buffer_snapshot;
 2019        self.add_selections_state = None;
 2020        self.select_next_state = None;
 2021        self.select_prev_state = None;
 2022        self.select_larger_syntax_node_stack.clear();
 2023        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2024        self.snippet_stack
 2025            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2026        self.take_rename(false, window, cx);
 2027
 2028        let new_cursor_position = self.selections.newest_anchor().head();
 2029
 2030        self.push_to_nav_history(
 2031            *old_cursor_position,
 2032            Some(new_cursor_position.to_point(buffer)),
 2033            cx,
 2034        );
 2035
 2036        if local {
 2037            let new_cursor_position = self.selections.newest_anchor().head();
 2038            let mut context_menu = self.context_menu.borrow_mut();
 2039            let completion_menu = match context_menu.as_ref() {
 2040                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2041                _ => {
 2042                    *context_menu = None;
 2043                    None
 2044                }
 2045            };
 2046            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2047                if !self.registered_buffers.contains_key(&buffer_id) {
 2048                    if let Some(lsp_store) = self.lsp_store(cx) {
 2049                        lsp_store.update(cx, |lsp_store, cx| {
 2050                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2051                                return;
 2052                            };
 2053                            self.registered_buffers.insert(
 2054                                buffer_id,
 2055                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2056                            );
 2057                        })
 2058                    }
 2059                }
 2060            }
 2061
 2062            if let Some(completion_menu) = completion_menu {
 2063                let cursor_position = new_cursor_position.to_offset(buffer);
 2064                let (word_range, kind) =
 2065                    buffer.surrounding_word(completion_menu.initial_position, true);
 2066                if kind == Some(CharKind::Word)
 2067                    && word_range.to_inclusive().contains(&cursor_position)
 2068                {
 2069                    let mut completion_menu = completion_menu.clone();
 2070                    drop(context_menu);
 2071
 2072                    let query = Self::completion_query(buffer, cursor_position);
 2073                    cx.spawn(move |this, mut cx| async move {
 2074                        completion_menu
 2075                            .filter(query.as_deref(), cx.background_executor().clone())
 2076                            .await;
 2077
 2078                        this.update(&mut cx, |this, cx| {
 2079                            let mut context_menu = this.context_menu.borrow_mut();
 2080                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2081                            else {
 2082                                return;
 2083                            };
 2084
 2085                            if menu.id > completion_menu.id {
 2086                                return;
 2087                            }
 2088
 2089                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2090                            drop(context_menu);
 2091                            cx.notify();
 2092                        })
 2093                    })
 2094                    .detach();
 2095
 2096                    if show_completions {
 2097                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2098                    }
 2099                } else {
 2100                    drop(context_menu);
 2101                    self.hide_context_menu(window, cx);
 2102                }
 2103            } else {
 2104                drop(context_menu);
 2105            }
 2106
 2107            hide_hover(self, cx);
 2108
 2109            if old_cursor_position.to_display_point(&display_map).row()
 2110                != new_cursor_position.to_display_point(&display_map).row()
 2111            {
 2112                self.available_code_actions.take();
 2113            }
 2114            self.refresh_code_actions(window, cx);
 2115            self.refresh_document_highlights(cx);
 2116            refresh_matching_bracket_highlights(self, window, cx);
 2117            self.update_visible_inline_completion(window, cx);
 2118            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2119            if self.git_blame_inline_enabled {
 2120                self.start_inline_blame_timer(window, cx);
 2121            }
 2122        }
 2123
 2124        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2125        cx.emit(EditorEvent::SelectionsChanged { local });
 2126
 2127        if self.selections.disjoint_anchors().len() == 1 {
 2128            cx.emit(SearchEvent::ActiveMatchChanged)
 2129        }
 2130        cx.notify();
 2131    }
 2132
 2133    pub fn change_selections<R>(
 2134        &mut self,
 2135        autoscroll: Option<Autoscroll>,
 2136        window: &mut Window,
 2137        cx: &mut Context<Self>,
 2138        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2139    ) -> R {
 2140        self.change_selections_inner(autoscroll, true, window, cx, change)
 2141    }
 2142
 2143    pub fn change_selections_inner<R>(
 2144        &mut self,
 2145        autoscroll: Option<Autoscroll>,
 2146        request_completions: bool,
 2147        window: &mut Window,
 2148        cx: &mut Context<Self>,
 2149        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2150    ) -> R {
 2151        let old_cursor_position = self.selections.newest_anchor().head();
 2152        self.push_to_selection_history();
 2153
 2154        let (changed, result) = self.selections.change_with(cx, change);
 2155
 2156        if changed {
 2157            if let Some(autoscroll) = autoscroll {
 2158                self.request_autoscroll(autoscroll, cx);
 2159            }
 2160            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2161
 2162            if self.should_open_signature_help_automatically(
 2163                &old_cursor_position,
 2164                self.signature_help_state.backspace_pressed(),
 2165                cx,
 2166            ) {
 2167                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2168            }
 2169            self.signature_help_state.set_backspace_pressed(false);
 2170        }
 2171
 2172        result
 2173    }
 2174
 2175    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2176    where
 2177        I: IntoIterator<Item = (Range<S>, T)>,
 2178        S: ToOffset,
 2179        T: Into<Arc<str>>,
 2180    {
 2181        if self.read_only(cx) {
 2182            return;
 2183        }
 2184
 2185        self.buffer
 2186            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2187    }
 2188
 2189    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2190    where
 2191        I: IntoIterator<Item = (Range<S>, T)>,
 2192        S: ToOffset,
 2193        T: Into<Arc<str>>,
 2194    {
 2195        if self.read_only(cx) {
 2196            return;
 2197        }
 2198
 2199        self.buffer.update(cx, |buffer, cx| {
 2200            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2201        });
 2202    }
 2203
 2204    pub fn edit_with_block_indent<I, S, T>(
 2205        &mut self,
 2206        edits: I,
 2207        original_indent_columns: Vec<u32>,
 2208        cx: &mut Context<Self>,
 2209    ) where
 2210        I: IntoIterator<Item = (Range<S>, T)>,
 2211        S: ToOffset,
 2212        T: Into<Arc<str>>,
 2213    {
 2214        if self.read_only(cx) {
 2215            return;
 2216        }
 2217
 2218        self.buffer.update(cx, |buffer, cx| {
 2219            buffer.edit(
 2220                edits,
 2221                Some(AutoindentMode::Block {
 2222                    original_indent_columns,
 2223                }),
 2224                cx,
 2225            )
 2226        });
 2227    }
 2228
 2229    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2230        self.hide_context_menu(window, cx);
 2231
 2232        match phase {
 2233            SelectPhase::Begin {
 2234                position,
 2235                add,
 2236                click_count,
 2237            } => self.begin_selection(position, add, click_count, window, cx),
 2238            SelectPhase::BeginColumnar {
 2239                position,
 2240                goal_column,
 2241                reset,
 2242            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2243            SelectPhase::Extend {
 2244                position,
 2245                click_count,
 2246            } => self.extend_selection(position, click_count, window, cx),
 2247            SelectPhase::Update {
 2248                position,
 2249                goal_column,
 2250                scroll_delta,
 2251            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2252            SelectPhase::End => self.end_selection(window, cx),
 2253        }
 2254    }
 2255
 2256    fn extend_selection(
 2257        &mut self,
 2258        position: DisplayPoint,
 2259        click_count: usize,
 2260        window: &mut Window,
 2261        cx: &mut Context<Self>,
 2262    ) {
 2263        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2264        let tail = self.selections.newest::<usize>(cx).tail();
 2265        self.begin_selection(position, false, click_count, window, cx);
 2266
 2267        let position = position.to_offset(&display_map, Bias::Left);
 2268        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2269
 2270        let mut pending_selection = self
 2271            .selections
 2272            .pending_anchor()
 2273            .expect("extend_selection not called with pending selection");
 2274        if position >= tail {
 2275            pending_selection.start = tail_anchor;
 2276        } else {
 2277            pending_selection.end = tail_anchor;
 2278            pending_selection.reversed = true;
 2279        }
 2280
 2281        let mut pending_mode = self.selections.pending_mode().unwrap();
 2282        match &mut pending_mode {
 2283            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2284            _ => {}
 2285        }
 2286
 2287        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2288            s.set_pending(pending_selection, pending_mode)
 2289        });
 2290    }
 2291
 2292    fn begin_selection(
 2293        &mut self,
 2294        position: DisplayPoint,
 2295        add: bool,
 2296        click_count: usize,
 2297        window: &mut Window,
 2298        cx: &mut Context<Self>,
 2299    ) {
 2300        if !self.focus_handle.is_focused(window) {
 2301            self.last_focused_descendant = None;
 2302            window.focus(&self.focus_handle);
 2303        }
 2304
 2305        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2306        let buffer = &display_map.buffer_snapshot;
 2307        let newest_selection = self.selections.newest_anchor().clone();
 2308        let position = display_map.clip_point(position, Bias::Left);
 2309
 2310        let start;
 2311        let end;
 2312        let mode;
 2313        let mut auto_scroll;
 2314        match click_count {
 2315            1 => {
 2316                start = buffer.anchor_before(position.to_point(&display_map));
 2317                end = start;
 2318                mode = SelectMode::Character;
 2319                auto_scroll = true;
 2320            }
 2321            2 => {
 2322                let range = movement::surrounding_word(&display_map, position);
 2323                start = buffer.anchor_before(range.start.to_point(&display_map));
 2324                end = buffer.anchor_before(range.end.to_point(&display_map));
 2325                mode = SelectMode::Word(start..end);
 2326                auto_scroll = true;
 2327            }
 2328            3 => {
 2329                let position = display_map
 2330                    .clip_point(position, Bias::Left)
 2331                    .to_point(&display_map);
 2332                let line_start = display_map.prev_line_boundary(position).0;
 2333                let next_line_start = buffer.clip_point(
 2334                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2335                    Bias::Left,
 2336                );
 2337                start = buffer.anchor_before(line_start);
 2338                end = buffer.anchor_before(next_line_start);
 2339                mode = SelectMode::Line(start..end);
 2340                auto_scroll = true;
 2341            }
 2342            _ => {
 2343                start = buffer.anchor_before(0);
 2344                end = buffer.anchor_before(buffer.len());
 2345                mode = SelectMode::All;
 2346                auto_scroll = false;
 2347            }
 2348        }
 2349        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2350
 2351        let point_to_delete: Option<usize> = {
 2352            let selected_points: Vec<Selection<Point>> =
 2353                self.selections.disjoint_in_range(start..end, cx);
 2354
 2355            if !add || click_count > 1 {
 2356                None
 2357            } else if !selected_points.is_empty() {
 2358                Some(selected_points[0].id)
 2359            } else {
 2360                let clicked_point_already_selected =
 2361                    self.selections.disjoint.iter().find(|selection| {
 2362                        selection.start.to_point(buffer) == start.to_point(buffer)
 2363                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2364                    });
 2365
 2366                clicked_point_already_selected.map(|selection| selection.id)
 2367            }
 2368        };
 2369
 2370        let selections_count = self.selections.count();
 2371
 2372        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2373            if let Some(point_to_delete) = point_to_delete {
 2374                s.delete(point_to_delete);
 2375
 2376                if selections_count == 1 {
 2377                    s.set_pending_anchor_range(start..end, mode);
 2378                }
 2379            } else {
 2380                if !add {
 2381                    s.clear_disjoint();
 2382                } else if click_count > 1 {
 2383                    s.delete(newest_selection.id)
 2384                }
 2385
 2386                s.set_pending_anchor_range(start..end, mode);
 2387            }
 2388        });
 2389    }
 2390
 2391    fn begin_columnar_selection(
 2392        &mut self,
 2393        position: DisplayPoint,
 2394        goal_column: u32,
 2395        reset: bool,
 2396        window: &mut Window,
 2397        cx: &mut Context<Self>,
 2398    ) {
 2399        if !self.focus_handle.is_focused(window) {
 2400            self.last_focused_descendant = None;
 2401            window.focus(&self.focus_handle);
 2402        }
 2403
 2404        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2405
 2406        if reset {
 2407            let pointer_position = display_map
 2408                .buffer_snapshot
 2409                .anchor_before(position.to_point(&display_map));
 2410
 2411            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2412                s.clear_disjoint();
 2413                s.set_pending_anchor_range(
 2414                    pointer_position..pointer_position,
 2415                    SelectMode::Character,
 2416                );
 2417            });
 2418        }
 2419
 2420        let tail = self.selections.newest::<Point>(cx).tail();
 2421        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2422
 2423        if !reset {
 2424            self.select_columns(
 2425                tail.to_display_point(&display_map),
 2426                position,
 2427                goal_column,
 2428                &display_map,
 2429                window,
 2430                cx,
 2431            );
 2432        }
 2433    }
 2434
 2435    fn update_selection(
 2436        &mut self,
 2437        position: DisplayPoint,
 2438        goal_column: u32,
 2439        scroll_delta: gpui::Point<f32>,
 2440        window: &mut Window,
 2441        cx: &mut Context<Self>,
 2442    ) {
 2443        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2444
 2445        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2446            let tail = tail.to_display_point(&display_map);
 2447            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2448        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2449            let buffer = self.buffer.read(cx).snapshot(cx);
 2450            let head;
 2451            let tail;
 2452            let mode = self.selections.pending_mode().unwrap();
 2453            match &mode {
 2454                SelectMode::Character => {
 2455                    head = position.to_point(&display_map);
 2456                    tail = pending.tail().to_point(&buffer);
 2457                }
 2458                SelectMode::Word(original_range) => {
 2459                    let original_display_range = original_range.start.to_display_point(&display_map)
 2460                        ..original_range.end.to_display_point(&display_map);
 2461                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2462                        ..original_display_range.end.to_point(&display_map);
 2463                    if movement::is_inside_word(&display_map, position)
 2464                        || original_display_range.contains(&position)
 2465                    {
 2466                        let word_range = movement::surrounding_word(&display_map, position);
 2467                        if word_range.start < original_display_range.start {
 2468                            head = word_range.start.to_point(&display_map);
 2469                        } else {
 2470                            head = word_range.end.to_point(&display_map);
 2471                        }
 2472                    } else {
 2473                        head = position.to_point(&display_map);
 2474                    }
 2475
 2476                    if head <= original_buffer_range.start {
 2477                        tail = original_buffer_range.end;
 2478                    } else {
 2479                        tail = original_buffer_range.start;
 2480                    }
 2481                }
 2482                SelectMode::Line(original_range) => {
 2483                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2484
 2485                    let position = display_map
 2486                        .clip_point(position, Bias::Left)
 2487                        .to_point(&display_map);
 2488                    let line_start = display_map.prev_line_boundary(position).0;
 2489                    let next_line_start = buffer.clip_point(
 2490                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2491                        Bias::Left,
 2492                    );
 2493
 2494                    if line_start < original_range.start {
 2495                        head = line_start
 2496                    } else {
 2497                        head = next_line_start
 2498                    }
 2499
 2500                    if head <= original_range.start {
 2501                        tail = original_range.end;
 2502                    } else {
 2503                        tail = original_range.start;
 2504                    }
 2505                }
 2506                SelectMode::All => {
 2507                    return;
 2508                }
 2509            };
 2510
 2511            if head < tail {
 2512                pending.start = buffer.anchor_before(head);
 2513                pending.end = buffer.anchor_before(tail);
 2514                pending.reversed = true;
 2515            } else {
 2516                pending.start = buffer.anchor_before(tail);
 2517                pending.end = buffer.anchor_before(head);
 2518                pending.reversed = false;
 2519            }
 2520
 2521            self.change_selections(None, window, cx, |s| {
 2522                s.set_pending(pending, mode);
 2523            });
 2524        } else {
 2525            log::error!("update_selection dispatched with no pending selection");
 2526            return;
 2527        }
 2528
 2529        self.apply_scroll_delta(scroll_delta, window, cx);
 2530        cx.notify();
 2531    }
 2532
 2533    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2534        self.columnar_selection_tail.take();
 2535        if self.selections.pending_anchor().is_some() {
 2536            let selections = self.selections.all::<usize>(cx);
 2537            self.change_selections(None, window, cx, |s| {
 2538                s.select(selections);
 2539                s.clear_pending();
 2540            });
 2541        }
 2542    }
 2543
 2544    fn select_columns(
 2545        &mut self,
 2546        tail: DisplayPoint,
 2547        head: DisplayPoint,
 2548        goal_column: u32,
 2549        display_map: &DisplaySnapshot,
 2550        window: &mut Window,
 2551        cx: &mut Context<Self>,
 2552    ) {
 2553        let start_row = cmp::min(tail.row(), head.row());
 2554        let end_row = cmp::max(tail.row(), head.row());
 2555        let start_column = cmp::min(tail.column(), goal_column);
 2556        let end_column = cmp::max(tail.column(), goal_column);
 2557        let reversed = start_column < tail.column();
 2558
 2559        let selection_ranges = (start_row.0..=end_row.0)
 2560            .map(DisplayRow)
 2561            .filter_map(|row| {
 2562                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2563                    let start = display_map
 2564                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2565                        .to_point(display_map);
 2566                    let end = display_map
 2567                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2568                        .to_point(display_map);
 2569                    if reversed {
 2570                        Some(end..start)
 2571                    } else {
 2572                        Some(start..end)
 2573                    }
 2574                } else {
 2575                    None
 2576                }
 2577            })
 2578            .collect::<Vec<_>>();
 2579
 2580        self.change_selections(None, window, cx, |s| {
 2581            s.select_ranges(selection_ranges);
 2582        });
 2583        cx.notify();
 2584    }
 2585
 2586    pub fn has_pending_nonempty_selection(&self) -> bool {
 2587        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2588            Some(Selection { start, end, .. }) => start != end,
 2589            None => false,
 2590        };
 2591
 2592        pending_nonempty_selection
 2593            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2594    }
 2595
 2596    pub fn has_pending_selection(&self) -> bool {
 2597        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2598    }
 2599
 2600    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2601        self.selection_mark_mode = false;
 2602
 2603        if self.clear_expanded_diff_hunks(cx) {
 2604            cx.notify();
 2605            return;
 2606        }
 2607        if self.dismiss_menus_and_popups(true, window, cx) {
 2608            return;
 2609        }
 2610
 2611        if self.mode == EditorMode::Full
 2612            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2613        {
 2614            return;
 2615        }
 2616
 2617        cx.propagate();
 2618    }
 2619
 2620    pub fn dismiss_menus_and_popups(
 2621        &mut self,
 2622        is_user_requested: bool,
 2623        window: &mut Window,
 2624        cx: &mut Context<Self>,
 2625    ) -> bool {
 2626        if self.take_rename(false, window, cx).is_some() {
 2627            return true;
 2628        }
 2629
 2630        if hide_hover(self, cx) {
 2631            return true;
 2632        }
 2633
 2634        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2635            return true;
 2636        }
 2637
 2638        if self.hide_context_menu(window, cx).is_some() {
 2639            return true;
 2640        }
 2641
 2642        if self.mouse_context_menu.take().is_some() {
 2643            return true;
 2644        }
 2645
 2646        if is_user_requested && self.discard_inline_completion(true, cx) {
 2647            return true;
 2648        }
 2649
 2650        if self.snippet_stack.pop().is_some() {
 2651            return true;
 2652        }
 2653
 2654        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2655            self.dismiss_diagnostics(cx);
 2656            return true;
 2657        }
 2658
 2659        false
 2660    }
 2661
 2662    fn linked_editing_ranges_for(
 2663        &self,
 2664        selection: Range<text::Anchor>,
 2665        cx: &App,
 2666    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2667        if self.linked_edit_ranges.is_empty() {
 2668            return None;
 2669        }
 2670        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2671            selection.end.buffer_id.and_then(|end_buffer_id| {
 2672                if selection.start.buffer_id != Some(end_buffer_id) {
 2673                    return None;
 2674                }
 2675                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2676                let snapshot = buffer.read(cx).snapshot();
 2677                self.linked_edit_ranges
 2678                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2679                    .map(|ranges| (ranges, snapshot, buffer))
 2680            })?;
 2681        use text::ToOffset as TO;
 2682        // find offset from the start of current range to current cursor position
 2683        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2684
 2685        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2686        let start_difference = start_offset - start_byte_offset;
 2687        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2688        let end_difference = end_offset - start_byte_offset;
 2689        // Current range has associated linked ranges.
 2690        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2691        for range in linked_ranges.iter() {
 2692            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2693            let end_offset = start_offset + end_difference;
 2694            let start_offset = start_offset + start_difference;
 2695            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2696                continue;
 2697            }
 2698            if self.selections.disjoint_anchor_ranges().any(|s| {
 2699                if s.start.buffer_id != selection.start.buffer_id
 2700                    || s.end.buffer_id != selection.end.buffer_id
 2701                {
 2702                    return false;
 2703                }
 2704                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2705                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2706            }) {
 2707                continue;
 2708            }
 2709            let start = buffer_snapshot.anchor_after(start_offset);
 2710            let end = buffer_snapshot.anchor_after(end_offset);
 2711            linked_edits
 2712                .entry(buffer.clone())
 2713                .or_default()
 2714                .push(start..end);
 2715        }
 2716        Some(linked_edits)
 2717    }
 2718
 2719    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2720        let text: Arc<str> = text.into();
 2721
 2722        if self.read_only(cx) {
 2723            return;
 2724        }
 2725
 2726        let selections = self.selections.all_adjusted(cx);
 2727        let mut bracket_inserted = false;
 2728        let mut edits = Vec::new();
 2729        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2730        let mut new_selections = Vec::with_capacity(selections.len());
 2731        let mut new_autoclose_regions = Vec::new();
 2732        let snapshot = self.buffer.read(cx).read(cx);
 2733
 2734        for (selection, autoclose_region) in
 2735            self.selections_with_autoclose_regions(selections, &snapshot)
 2736        {
 2737            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2738                // Determine if the inserted text matches the opening or closing
 2739                // bracket of any of this language's bracket pairs.
 2740                let mut bracket_pair = None;
 2741                let mut is_bracket_pair_start = false;
 2742                let mut is_bracket_pair_end = false;
 2743                if !text.is_empty() {
 2744                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2745                    //  and they are removing the character that triggered IME popup.
 2746                    for (pair, enabled) in scope.brackets() {
 2747                        if !pair.close && !pair.surround {
 2748                            continue;
 2749                        }
 2750
 2751                        if enabled && pair.start.ends_with(text.as_ref()) {
 2752                            let prefix_len = pair.start.len() - text.len();
 2753                            let preceding_text_matches_prefix = prefix_len == 0
 2754                                || (selection.start.column >= (prefix_len as u32)
 2755                                    && snapshot.contains_str_at(
 2756                                        Point::new(
 2757                                            selection.start.row,
 2758                                            selection.start.column - (prefix_len as u32),
 2759                                        ),
 2760                                        &pair.start[..prefix_len],
 2761                                    ));
 2762                            if preceding_text_matches_prefix {
 2763                                bracket_pair = Some(pair.clone());
 2764                                is_bracket_pair_start = true;
 2765                                break;
 2766                            }
 2767                        }
 2768                        if pair.end.as_str() == text.as_ref() {
 2769                            bracket_pair = Some(pair.clone());
 2770                            is_bracket_pair_end = true;
 2771                            break;
 2772                        }
 2773                    }
 2774                }
 2775
 2776                if let Some(bracket_pair) = bracket_pair {
 2777                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2778                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2779                    let auto_surround =
 2780                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2781                    if selection.is_empty() {
 2782                        if is_bracket_pair_start {
 2783                            // If the inserted text is a suffix of an opening bracket and the
 2784                            // selection is preceded by the rest of the opening bracket, then
 2785                            // insert the closing bracket.
 2786                            let following_text_allows_autoclose = snapshot
 2787                                .chars_at(selection.start)
 2788                                .next()
 2789                                .map_or(true, |c| scope.should_autoclose_before(c));
 2790
 2791                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2792                                && bracket_pair.start.len() == 1
 2793                            {
 2794                                let target = bracket_pair.start.chars().next().unwrap();
 2795                                let current_line_count = snapshot
 2796                                    .reversed_chars_at(selection.start)
 2797                                    .take_while(|&c| c != '\n')
 2798                                    .filter(|&c| c == target)
 2799                                    .count();
 2800                                current_line_count % 2 == 1
 2801                            } else {
 2802                                false
 2803                            };
 2804
 2805                            if autoclose
 2806                                && bracket_pair.close
 2807                                && following_text_allows_autoclose
 2808                                && !is_closing_quote
 2809                            {
 2810                                let anchor = snapshot.anchor_before(selection.end);
 2811                                new_selections.push((selection.map(|_| anchor), text.len()));
 2812                                new_autoclose_regions.push((
 2813                                    anchor,
 2814                                    text.len(),
 2815                                    selection.id,
 2816                                    bracket_pair.clone(),
 2817                                ));
 2818                                edits.push((
 2819                                    selection.range(),
 2820                                    format!("{}{}", text, bracket_pair.end).into(),
 2821                                ));
 2822                                bracket_inserted = true;
 2823                                continue;
 2824                            }
 2825                        }
 2826
 2827                        if let Some(region) = autoclose_region {
 2828                            // If the selection is followed by an auto-inserted closing bracket,
 2829                            // then don't insert that closing bracket again; just move the selection
 2830                            // past the closing bracket.
 2831                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2832                                && text.as_ref() == region.pair.end.as_str();
 2833                            if should_skip {
 2834                                let anchor = snapshot.anchor_after(selection.end);
 2835                                new_selections
 2836                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2837                                continue;
 2838                            }
 2839                        }
 2840
 2841                        let always_treat_brackets_as_autoclosed = snapshot
 2842                            .settings_at(selection.start, cx)
 2843                            .always_treat_brackets_as_autoclosed;
 2844                        if always_treat_brackets_as_autoclosed
 2845                            && is_bracket_pair_end
 2846                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2847                        {
 2848                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2849                            // and the inserted text is a closing bracket and the selection is followed
 2850                            // by the closing bracket then move the selection past the closing bracket.
 2851                            let anchor = snapshot.anchor_after(selection.end);
 2852                            new_selections.push((selection.map(|_| anchor), text.len()));
 2853                            continue;
 2854                        }
 2855                    }
 2856                    // If an opening bracket is 1 character long and is typed while
 2857                    // text is selected, then surround that text with the bracket pair.
 2858                    else if auto_surround
 2859                        && bracket_pair.surround
 2860                        && is_bracket_pair_start
 2861                        && bracket_pair.start.chars().count() == 1
 2862                    {
 2863                        edits.push((selection.start..selection.start, text.clone()));
 2864                        edits.push((
 2865                            selection.end..selection.end,
 2866                            bracket_pair.end.as_str().into(),
 2867                        ));
 2868                        bracket_inserted = true;
 2869                        new_selections.push((
 2870                            Selection {
 2871                                id: selection.id,
 2872                                start: snapshot.anchor_after(selection.start),
 2873                                end: snapshot.anchor_before(selection.end),
 2874                                reversed: selection.reversed,
 2875                                goal: selection.goal,
 2876                            },
 2877                            0,
 2878                        ));
 2879                        continue;
 2880                    }
 2881                }
 2882            }
 2883
 2884            if self.auto_replace_emoji_shortcode
 2885                && selection.is_empty()
 2886                && text.as_ref().ends_with(':')
 2887            {
 2888                if let Some(possible_emoji_short_code) =
 2889                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2890                {
 2891                    if !possible_emoji_short_code.is_empty() {
 2892                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2893                            let emoji_shortcode_start = Point::new(
 2894                                selection.start.row,
 2895                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2896                            );
 2897
 2898                            // Remove shortcode from buffer
 2899                            edits.push((
 2900                                emoji_shortcode_start..selection.start,
 2901                                "".to_string().into(),
 2902                            ));
 2903                            new_selections.push((
 2904                                Selection {
 2905                                    id: selection.id,
 2906                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2907                                    end: snapshot.anchor_before(selection.start),
 2908                                    reversed: selection.reversed,
 2909                                    goal: selection.goal,
 2910                                },
 2911                                0,
 2912                            ));
 2913
 2914                            // Insert emoji
 2915                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2916                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2917                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2918
 2919                            continue;
 2920                        }
 2921                    }
 2922                }
 2923            }
 2924
 2925            // If not handling any auto-close operation, then just replace the selected
 2926            // text with the given input and move the selection to the end of the
 2927            // newly inserted text.
 2928            let anchor = snapshot.anchor_after(selection.end);
 2929            if !self.linked_edit_ranges.is_empty() {
 2930                let start_anchor = snapshot.anchor_before(selection.start);
 2931
 2932                let is_word_char = text.chars().next().map_or(true, |char| {
 2933                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2934                    classifier.is_word(char)
 2935                });
 2936
 2937                if is_word_char {
 2938                    if let Some(ranges) = self
 2939                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2940                    {
 2941                        for (buffer, edits) in ranges {
 2942                            linked_edits
 2943                                .entry(buffer.clone())
 2944                                .or_default()
 2945                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2946                        }
 2947                    }
 2948                }
 2949            }
 2950
 2951            new_selections.push((selection.map(|_| anchor), 0));
 2952            edits.push((selection.start..selection.end, text.clone()));
 2953        }
 2954
 2955        drop(snapshot);
 2956
 2957        self.transact(window, cx, |this, window, cx| {
 2958            this.buffer.update(cx, |buffer, cx| {
 2959                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2960            });
 2961            for (buffer, edits) in linked_edits {
 2962                buffer.update(cx, |buffer, cx| {
 2963                    let snapshot = buffer.snapshot();
 2964                    let edits = edits
 2965                        .into_iter()
 2966                        .map(|(range, text)| {
 2967                            use text::ToPoint as TP;
 2968                            let end_point = TP::to_point(&range.end, &snapshot);
 2969                            let start_point = TP::to_point(&range.start, &snapshot);
 2970                            (start_point..end_point, text)
 2971                        })
 2972                        .sorted_by_key(|(range, _)| range.start)
 2973                        .collect::<Vec<_>>();
 2974                    buffer.edit(edits, None, cx);
 2975                })
 2976            }
 2977            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2978            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2979            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2980            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2981                .zip(new_selection_deltas)
 2982                .map(|(selection, delta)| Selection {
 2983                    id: selection.id,
 2984                    start: selection.start + delta,
 2985                    end: selection.end + delta,
 2986                    reversed: selection.reversed,
 2987                    goal: SelectionGoal::None,
 2988                })
 2989                .collect::<Vec<_>>();
 2990
 2991            let mut i = 0;
 2992            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2993                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2994                let start = map.buffer_snapshot.anchor_before(position);
 2995                let end = map.buffer_snapshot.anchor_after(position);
 2996                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2997                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2998                        Ordering::Less => i += 1,
 2999                        Ordering::Greater => break,
 3000                        Ordering::Equal => {
 3001                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3002                                Ordering::Less => i += 1,
 3003                                Ordering::Equal => break,
 3004                                Ordering::Greater => break,
 3005                            }
 3006                        }
 3007                    }
 3008                }
 3009                this.autoclose_regions.insert(
 3010                    i,
 3011                    AutocloseRegion {
 3012                        selection_id,
 3013                        range: start..end,
 3014                        pair,
 3015                    },
 3016                );
 3017            }
 3018
 3019            let had_active_inline_completion = this.has_active_inline_completion();
 3020            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3021                s.select(new_selections)
 3022            });
 3023
 3024            if !bracket_inserted {
 3025                if let Some(on_type_format_task) =
 3026                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3027                {
 3028                    on_type_format_task.detach_and_log_err(cx);
 3029                }
 3030            }
 3031
 3032            let editor_settings = EditorSettings::get_global(cx);
 3033            if bracket_inserted
 3034                && (editor_settings.auto_signature_help
 3035                    || editor_settings.show_signature_help_after_edits)
 3036            {
 3037                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3038            }
 3039
 3040            let trigger_in_words =
 3041                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3042            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3043            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3044            this.refresh_inline_completion(true, false, window, cx);
 3045        });
 3046    }
 3047
 3048    fn find_possible_emoji_shortcode_at_position(
 3049        snapshot: &MultiBufferSnapshot,
 3050        position: Point,
 3051    ) -> Option<String> {
 3052        let mut chars = Vec::new();
 3053        let mut found_colon = false;
 3054        for char in snapshot.reversed_chars_at(position).take(100) {
 3055            // Found a possible emoji shortcode in the middle of the buffer
 3056            if found_colon {
 3057                if char.is_whitespace() {
 3058                    chars.reverse();
 3059                    return Some(chars.iter().collect());
 3060                }
 3061                // If the previous character is not a whitespace, we are in the middle of a word
 3062                // and we only want to complete the shortcode if the word is made up of other emojis
 3063                let mut containing_word = String::new();
 3064                for ch in snapshot
 3065                    .reversed_chars_at(position)
 3066                    .skip(chars.len() + 1)
 3067                    .take(100)
 3068                {
 3069                    if ch.is_whitespace() {
 3070                        break;
 3071                    }
 3072                    containing_word.push(ch);
 3073                }
 3074                let containing_word = containing_word.chars().rev().collect::<String>();
 3075                if util::word_consists_of_emojis(containing_word.as_str()) {
 3076                    chars.reverse();
 3077                    return Some(chars.iter().collect());
 3078                }
 3079            }
 3080
 3081            if char.is_whitespace() || !char.is_ascii() {
 3082                return None;
 3083            }
 3084            if char == ':' {
 3085                found_colon = true;
 3086            } else {
 3087                chars.push(char);
 3088            }
 3089        }
 3090        // Found a possible emoji shortcode at the beginning of the buffer
 3091        chars.reverse();
 3092        Some(chars.iter().collect())
 3093    }
 3094
 3095    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3096        self.transact(window, cx, |this, window, cx| {
 3097            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3098                let selections = this.selections.all::<usize>(cx);
 3099                let multi_buffer = this.buffer.read(cx);
 3100                let buffer = multi_buffer.snapshot(cx);
 3101                selections
 3102                    .iter()
 3103                    .map(|selection| {
 3104                        let start_point = selection.start.to_point(&buffer);
 3105                        let mut indent =
 3106                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3107                        indent.len = cmp::min(indent.len, start_point.column);
 3108                        let start = selection.start;
 3109                        let end = selection.end;
 3110                        let selection_is_empty = start == end;
 3111                        let language_scope = buffer.language_scope_at(start);
 3112                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3113                            &language_scope
 3114                        {
 3115                            let leading_whitespace_len = buffer
 3116                                .reversed_chars_at(start)
 3117                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3118                                .map(|c| c.len_utf8())
 3119                                .sum::<usize>();
 3120
 3121                            let trailing_whitespace_len = buffer
 3122                                .chars_at(end)
 3123                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3124                                .map(|c| c.len_utf8())
 3125                                .sum::<usize>();
 3126
 3127                            let insert_extra_newline =
 3128                                language.brackets().any(|(pair, enabled)| {
 3129                                    let pair_start = pair.start.trim_end();
 3130                                    let pair_end = pair.end.trim_start();
 3131
 3132                                    enabled
 3133                                        && pair.newline
 3134                                        && buffer.contains_str_at(
 3135                                            end + trailing_whitespace_len,
 3136                                            pair_end,
 3137                                        )
 3138                                        && buffer.contains_str_at(
 3139                                            (start - leading_whitespace_len)
 3140                                                .saturating_sub(pair_start.len()),
 3141                                            pair_start,
 3142                                        )
 3143                                });
 3144
 3145                            // Comment extension on newline is allowed only for cursor selections
 3146                            let comment_delimiter = maybe!({
 3147                                if !selection_is_empty {
 3148                                    return None;
 3149                                }
 3150
 3151                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3152                                    return None;
 3153                                }
 3154
 3155                                let delimiters = language.line_comment_prefixes();
 3156                                let max_len_of_delimiter =
 3157                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3158                                let (snapshot, range) =
 3159                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3160
 3161                                let mut index_of_first_non_whitespace = 0;
 3162                                let comment_candidate = snapshot
 3163                                    .chars_for_range(range)
 3164                                    .skip_while(|c| {
 3165                                        let should_skip = c.is_whitespace();
 3166                                        if should_skip {
 3167                                            index_of_first_non_whitespace += 1;
 3168                                        }
 3169                                        should_skip
 3170                                    })
 3171                                    .take(max_len_of_delimiter)
 3172                                    .collect::<String>();
 3173                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3174                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3175                                })?;
 3176                                let cursor_is_placed_after_comment_marker =
 3177                                    index_of_first_non_whitespace + comment_prefix.len()
 3178                                        <= start_point.column as usize;
 3179                                if cursor_is_placed_after_comment_marker {
 3180                                    Some(comment_prefix.clone())
 3181                                } else {
 3182                                    None
 3183                                }
 3184                            });
 3185                            (comment_delimiter, insert_extra_newline)
 3186                        } else {
 3187                            (None, false)
 3188                        };
 3189
 3190                        let capacity_for_delimiter = comment_delimiter
 3191                            .as_deref()
 3192                            .map(str::len)
 3193                            .unwrap_or_default();
 3194                        let mut new_text =
 3195                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3196                        new_text.push('\n');
 3197                        new_text.extend(indent.chars());
 3198                        if let Some(delimiter) = &comment_delimiter {
 3199                            new_text.push_str(delimiter);
 3200                        }
 3201                        if insert_extra_newline {
 3202                            new_text = new_text.repeat(2);
 3203                        }
 3204
 3205                        let anchor = buffer.anchor_after(end);
 3206                        let new_selection = selection.map(|_| anchor);
 3207                        (
 3208                            (start..end, new_text),
 3209                            (insert_extra_newline, new_selection),
 3210                        )
 3211                    })
 3212                    .unzip()
 3213            };
 3214
 3215            this.edit_with_autoindent(edits, cx);
 3216            let buffer = this.buffer.read(cx).snapshot(cx);
 3217            let new_selections = selection_fixup_info
 3218                .into_iter()
 3219                .map(|(extra_newline_inserted, new_selection)| {
 3220                    let mut cursor = new_selection.end.to_point(&buffer);
 3221                    if extra_newline_inserted {
 3222                        cursor.row -= 1;
 3223                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3224                    }
 3225                    new_selection.map(|_| cursor)
 3226                })
 3227                .collect();
 3228
 3229            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3230                s.select(new_selections)
 3231            });
 3232            this.refresh_inline_completion(true, false, window, cx);
 3233        });
 3234    }
 3235
 3236    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3237        let buffer = self.buffer.read(cx);
 3238        let snapshot = buffer.snapshot(cx);
 3239
 3240        let mut edits = Vec::new();
 3241        let mut rows = Vec::new();
 3242
 3243        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3244            let cursor = selection.head();
 3245            let row = cursor.row;
 3246
 3247            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3248
 3249            let newline = "\n".to_string();
 3250            edits.push((start_of_line..start_of_line, newline));
 3251
 3252            rows.push(row + rows_inserted as u32);
 3253        }
 3254
 3255        self.transact(window, cx, |editor, window, cx| {
 3256            editor.edit(edits, cx);
 3257
 3258            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3259                let mut index = 0;
 3260                s.move_cursors_with(|map, _, _| {
 3261                    let row = rows[index];
 3262                    index += 1;
 3263
 3264                    let point = Point::new(row, 0);
 3265                    let boundary = map.next_line_boundary(point).1;
 3266                    let clipped = map.clip_point(boundary, Bias::Left);
 3267
 3268                    (clipped, SelectionGoal::None)
 3269                });
 3270            });
 3271
 3272            let mut indent_edits = Vec::new();
 3273            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3274            for row in rows {
 3275                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3276                for (row, indent) in indents {
 3277                    if indent.len == 0 {
 3278                        continue;
 3279                    }
 3280
 3281                    let text = match indent.kind {
 3282                        IndentKind::Space => " ".repeat(indent.len as usize),
 3283                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3284                    };
 3285                    let point = Point::new(row.0, 0);
 3286                    indent_edits.push((point..point, text));
 3287                }
 3288            }
 3289            editor.edit(indent_edits, cx);
 3290        });
 3291    }
 3292
 3293    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3294        let buffer = self.buffer.read(cx);
 3295        let snapshot = buffer.snapshot(cx);
 3296
 3297        let mut edits = Vec::new();
 3298        let mut rows = Vec::new();
 3299        let mut rows_inserted = 0;
 3300
 3301        for selection in self.selections.all_adjusted(cx) {
 3302            let cursor = selection.head();
 3303            let row = cursor.row;
 3304
 3305            let point = Point::new(row + 1, 0);
 3306            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3307
 3308            let newline = "\n".to_string();
 3309            edits.push((start_of_line..start_of_line, newline));
 3310
 3311            rows_inserted += 1;
 3312            rows.push(row + rows_inserted);
 3313        }
 3314
 3315        self.transact(window, cx, |editor, window, cx| {
 3316            editor.edit(edits, cx);
 3317
 3318            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3319                let mut index = 0;
 3320                s.move_cursors_with(|map, _, _| {
 3321                    let row = rows[index];
 3322                    index += 1;
 3323
 3324                    let point = Point::new(row, 0);
 3325                    let boundary = map.next_line_boundary(point).1;
 3326                    let clipped = map.clip_point(boundary, Bias::Left);
 3327
 3328                    (clipped, SelectionGoal::None)
 3329                });
 3330            });
 3331
 3332            let mut indent_edits = Vec::new();
 3333            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3334            for row in rows {
 3335                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3336                for (row, indent) in indents {
 3337                    if indent.len == 0 {
 3338                        continue;
 3339                    }
 3340
 3341                    let text = match indent.kind {
 3342                        IndentKind::Space => " ".repeat(indent.len as usize),
 3343                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3344                    };
 3345                    let point = Point::new(row.0, 0);
 3346                    indent_edits.push((point..point, text));
 3347                }
 3348            }
 3349            editor.edit(indent_edits, cx);
 3350        });
 3351    }
 3352
 3353    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3354        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3355            original_indent_columns: Vec::new(),
 3356        });
 3357        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3358    }
 3359
 3360    fn insert_with_autoindent_mode(
 3361        &mut self,
 3362        text: &str,
 3363        autoindent_mode: Option<AutoindentMode>,
 3364        window: &mut Window,
 3365        cx: &mut Context<Self>,
 3366    ) {
 3367        if self.read_only(cx) {
 3368            return;
 3369        }
 3370
 3371        let text: Arc<str> = text.into();
 3372        self.transact(window, cx, |this, window, cx| {
 3373            let old_selections = this.selections.all_adjusted(cx);
 3374            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3375                let anchors = {
 3376                    let snapshot = buffer.read(cx);
 3377                    old_selections
 3378                        .iter()
 3379                        .map(|s| {
 3380                            let anchor = snapshot.anchor_after(s.head());
 3381                            s.map(|_| anchor)
 3382                        })
 3383                        .collect::<Vec<_>>()
 3384                };
 3385                buffer.edit(
 3386                    old_selections
 3387                        .iter()
 3388                        .map(|s| (s.start..s.end, text.clone())),
 3389                    autoindent_mode,
 3390                    cx,
 3391                );
 3392                anchors
 3393            });
 3394
 3395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3396                s.select_anchors(selection_anchors);
 3397            });
 3398
 3399            cx.notify();
 3400        });
 3401    }
 3402
 3403    fn trigger_completion_on_input(
 3404        &mut self,
 3405        text: &str,
 3406        trigger_in_words: bool,
 3407        window: &mut Window,
 3408        cx: &mut Context<Self>,
 3409    ) {
 3410        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3411            self.show_completions(
 3412                &ShowCompletions {
 3413                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3414                },
 3415                window,
 3416                cx,
 3417            );
 3418        } else {
 3419            self.hide_context_menu(window, cx);
 3420        }
 3421    }
 3422
 3423    fn is_completion_trigger(
 3424        &self,
 3425        text: &str,
 3426        trigger_in_words: bool,
 3427        cx: &mut Context<Self>,
 3428    ) -> bool {
 3429        let position = self.selections.newest_anchor().head();
 3430        let multibuffer = self.buffer.read(cx);
 3431        let Some(buffer) = position
 3432            .buffer_id
 3433            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3434        else {
 3435            return false;
 3436        };
 3437
 3438        if let Some(completion_provider) = &self.completion_provider {
 3439            completion_provider.is_completion_trigger(
 3440                &buffer,
 3441                position.text_anchor,
 3442                text,
 3443                trigger_in_words,
 3444                cx,
 3445            )
 3446        } else {
 3447            false
 3448        }
 3449    }
 3450
 3451    /// If any empty selections is touching the start of its innermost containing autoclose
 3452    /// region, expand it to select the brackets.
 3453    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3454        let selections = self.selections.all::<usize>(cx);
 3455        let buffer = self.buffer.read(cx).read(cx);
 3456        let new_selections = self
 3457            .selections_with_autoclose_regions(selections, &buffer)
 3458            .map(|(mut selection, region)| {
 3459                if !selection.is_empty() {
 3460                    return selection;
 3461                }
 3462
 3463                if let Some(region) = region {
 3464                    let mut range = region.range.to_offset(&buffer);
 3465                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3466                        range.start -= region.pair.start.len();
 3467                        if buffer.contains_str_at(range.start, &region.pair.start)
 3468                            && buffer.contains_str_at(range.end, &region.pair.end)
 3469                        {
 3470                            range.end += region.pair.end.len();
 3471                            selection.start = range.start;
 3472                            selection.end = range.end;
 3473
 3474                            return selection;
 3475                        }
 3476                    }
 3477                }
 3478
 3479                let always_treat_brackets_as_autoclosed = buffer
 3480                    .settings_at(selection.start, cx)
 3481                    .always_treat_brackets_as_autoclosed;
 3482
 3483                if !always_treat_brackets_as_autoclosed {
 3484                    return selection;
 3485                }
 3486
 3487                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3488                    for (pair, enabled) in scope.brackets() {
 3489                        if !enabled || !pair.close {
 3490                            continue;
 3491                        }
 3492
 3493                        if buffer.contains_str_at(selection.start, &pair.end) {
 3494                            let pair_start_len = pair.start.len();
 3495                            if buffer.contains_str_at(
 3496                                selection.start.saturating_sub(pair_start_len),
 3497                                &pair.start,
 3498                            ) {
 3499                                selection.start -= pair_start_len;
 3500                                selection.end += pair.end.len();
 3501
 3502                                return selection;
 3503                            }
 3504                        }
 3505                    }
 3506                }
 3507
 3508                selection
 3509            })
 3510            .collect();
 3511
 3512        drop(buffer);
 3513        self.change_selections(None, window, cx, |selections| {
 3514            selections.select(new_selections)
 3515        });
 3516    }
 3517
 3518    /// Iterate the given selections, and for each one, find the smallest surrounding
 3519    /// autoclose region. This uses the ordering of the selections and the autoclose
 3520    /// regions to avoid repeated comparisons.
 3521    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3522        &'a self,
 3523        selections: impl IntoIterator<Item = Selection<D>>,
 3524        buffer: &'a MultiBufferSnapshot,
 3525    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3526        let mut i = 0;
 3527        let mut regions = self.autoclose_regions.as_slice();
 3528        selections.into_iter().map(move |selection| {
 3529            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3530
 3531            let mut enclosing = None;
 3532            while let Some(pair_state) = regions.get(i) {
 3533                if pair_state.range.end.to_offset(buffer) < range.start {
 3534                    regions = &regions[i + 1..];
 3535                    i = 0;
 3536                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3537                    break;
 3538                } else {
 3539                    if pair_state.selection_id == selection.id {
 3540                        enclosing = Some(pair_state);
 3541                    }
 3542                    i += 1;
 3543                }
 3544            }
 3545
 3546            (selection, enclosing)
 3547        })
 3548    }
 3549
 3550    /// Remove any autoclose regions that no longer contain their selection.
 3551    fn invalidate_autoclose_regions(
 3552        &mut self,
 3553        mut selections: &[Selection<Anchor>],
 3554        buffer: &MultiBufferSnapshot,
 3555    ) {
 3556        self.autoclose_regions.retain(|state| {
 3557            let mut i = 0;
 3558            while let Some(selection) = selections.get(i) {
 3559                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3560                    selections = &selections[1..];
 3561                    continue;
 3562                }
 3563                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3564                    break;
 3565                }
 3566                if selection.id == state.selection_id {
 3567                    return true;
 3568                } else {
 3569                    i += 1;
 3570                }
 3571            }
 3572            false
 3573        });
 3574    }
 3575
 3576    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3577        let offset = position.to_offset(buffer);
 3578        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3579        if offset > word_range.start && kind == Some(CharKind::Word) {
 3580            Some(
 3581                buffer
 3582                    .text_for_range(word_range.start..offset)
 3583                    .collect::<String>(),
 3584            )
 3585        } else {
 3586            None
 3587        }
 3588    }
 3589
 3590    pub fn toggle_inlay_hints(
 3591        &mut self,
 3592        _: &ToggleInlayHints,
 3593        _: &mut Window,
 3594        cx: &mut Context<Self>,
 3595    ) {
 3596        self.refresh_inlay_hints(
 3597            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3598            cx,
 3599        );
 3600    }
 3601
 3602    pub fn inlay_hints_enabled(&self) -> bool {
 3603        self.inlay_hint_cache.enabled
 3604    }
 3605
 3606    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3607        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3608            return;
 3609        }
 3610
 3611        let reason_description = reason.description();
 3612        let ignore_debounce = matches!(
 3613            reason,
 3614            InlayHintRefreshReason::SettingsChange(_)
 3615                | InlayHintRefreshReason::Toggle(_)
 3616                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3617        );
 3618        let (invalidate_cache, required_languages) = match reason {
 3619            InlayHintRefreshReason::Toggle(enabled) => {
 3620                self.inlay_hint_cache.enabled = enabled;
 3621                if enabled {
 3622                    (InvalidationStrategy::RefreshRequested, None)
 3623                } else {
 3624                    self.inlay_hint_cache.clear();
 3625                    self.splice_inlays(
 3626                        &self
 3627                            .visible_inlay_hints(cx)
 3628                            .iter()
 3629                            .map(|inlay| inlay.id)
 3630                            .collect::<Vec<InlayId>>(),
 3631                        Vec::new(),
 3632                        cx,
 3633                    );
 3634                    return;
 3635                }
 3636            }
 3637            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3638                match self.inlay_hint_cache.update_settings(
 3639                    &self.buffer,
 3640                    new_settings,
 3641                    self.visible_inlay_hints(cx),
 3642                    cx,
 3643                ) {
 3644                    ControlFlow::Break(Some(InlaySplice {
 3645                        to_remove,
 3646                        to_insert,
 3647                    })) => {
 3648                        self.splice_inlays(&to_remove, to_insert, cx);
 3649                        return;
 3650                    }
 3651                    ControlFlow::Break(None) => return,
 3652                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3653                }
 3654            }
 3655            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3656                if let Some(InlaySplice {
 3657                    to_remove,
 3658                    to_insert,
 3659                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3660                {
 3661                    self.splice_inlays(&to_remove, to_insert, cx);
 3662                }
 3663                return;
 3664            }
 3665            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3666            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3667                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3668            }
 3669            InlayHintRefreshReason::RefreshRequested => {
 3670                (InvalidationStrategy::RefreshRequested, None)
 3671            }
 3672        };
 3673
 3674        if let Some(InlaySplice {
 3675            to_remove,
 3676            to_insert,
 3677        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3678            reason_description,
 3679            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3680            invalidate_cache,
 3681            ignore_debounce,
 3682            cx,
 3683        ) {
 3684            self.splice_inlays(&to_remove, to_insert, cx);
 3685        }
 3686    }
 3687
 3688    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3689        self.display_map
 3690            .read(cx)
 3691            .current_inlays()
 3692            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3693            .cloned()
 3694            .collect()
 3695    }
 3696
 3697    pub fn excerpts_for_inlay_hints_query(
 3698        &self,
 3699        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3700        cx: &mut Context<Editor>,
 3701    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3702        let Some(project) = self.project.as_ref() else {
 3703            return HashMap::default();
 3704        };
 3705        let project = project.read(cx);
 3706        let multi_buffer = self.buffer().read(cx);
 3707        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3708        let multi_buffer_visible_start = self
 3709            .scroll_manager
 3710            .anchor()
 3711            .anchor
 3712            .to_point(&multi_buffer_snapshot);
 3713        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3714            multi_buffer_visible_start
 3715                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3716            Bias::Left,
 3717        );
 3718        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3719        multi_buffer_snapshot
 3720            .range_to_buffer_ranges(multi_buffer_visible_range)
 3721            .into_iter()
 3722            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3723            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3724                let buffer_file = project::File::from_dyn(buffer.file())?;
 3725                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3726                let worktree_entry = buffer_worktree
 3727                    .read(cx)
 3728                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3729                if worktree_entry.is_ignored {
 3730                    return None;
 3731                }
 3732
 3733                let language = buffer.language()?;
 3734                if let Some(restrict_to_languages) = restrict_to_languages {
 3735                    if !restrict_to_languages.contains(language) {
 3736                        return None;
 3737                    }
 3738                }
 3739                Some((
 3740                    excerpt_id,
 3741                    (
 3742                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3743                        buffer.version().clone(),
 3744                        excerpt_visible_range,
 3745                    ),
 3746                ))
 3747            })
 3748            .collect()
 3749    }
 3750
 3751    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3752        TextLayoutDetails {
 3753            text_system: window.text_system().clone(),
 3754            editor_style: self.style.clone().unwrap(),
 3755            rem_size: window.rem_size(),
 3756            scroll_anchor: self.scroll_manager.anchor(),
 3757            visible_rows: self.visible_line_count(),
 3758            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3759        }
 3760    }
 3761
 3762    pub fn splice_inlays(
 3763        &self,
 3764        to_remove: &[InlayId],
 3765        to_insert: Vec<Inlay>,
 3766        cx: &mut Context<Self>,
 3767    ) {
 3768        self.display_map.update(cx, |display_map, cx| {
 3769            display_map.splice_inlays(to_remove, to_insert, cx)
 3770        });
 3771        cx.notify();
 3772    }
 3773
 3774    fn trigger_on_type_formatting(
 3775        &self,
 3776        input: String,
 3777        window: &mut Window,
 3778        cx: &mut Context<Self>,
 3779    ) -> Option<Task<Result<()>>> {
 3780        if input.len() != 1 {
 3781            return None;
 3782        }
 3783
 3784        let project = self.project.as_ref()?;
 3785        let position = self.selections.newest_anchor().head();
 3786        let (buffer, buffer_position) = self
 3787            .buffer
 3788            .read(cx)
 3789            .text_anchor_for_position(position, cx)?;
 3790
 3791        let settings = language_settings::language_settings(
 3792            buffer
 3793                .read(cx)
 3794                .language_at(buffer_position)
 3795                .map(|l| l.name()),
 3796            buffer.read(cx).file(),
 3797            cx,
 3798        );
 3799        if !settings.use_on_type_format {
 3800            return None;
 3801        }
 3802
 3803        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3804        // hence we do LSP request & edit on host side only — add formats to host's history.
 3805        let push_to_lsp_host_history = true;
 3806        // If this is not the host, append its history with new edits.
 3807        let push_to_client_history = project.read(cx).is_via_collab();
 3808
 3809        let on_type_formatting = project.update(cx, |project, cx| {
 3810            project.on_type_format(
 3811                buffer.clone(),
 3812                buffer_position,
 3813                input,
 3814                push_to_lsp_host_history,
 3815                cx,
 3816            )
 3817        });
 3818        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3819            if let Some(transaction) = on_type_formatting.await? {
 3820                if push_to_client_history {
 3821                    buffer
 3822                        .update(&mut cx, |buffer, _| {
 3823                            buffer.push_transaction(transaction, Instant::now());
 3824                        })
 3825                        .ok();
 3826                }
 3827                editor.update(&mut cx, |editor, cx| {
 3828                    editor.refresh_document_highlights(cx);
 3829                })?;
 3830            }
 3831            Ok(())
 3832        }))
 3833    }
 3834
 3835    pub fn show_completions(
 3836        &mut self,
 3837        options: &ShowCompletions,
 3838        window: &mut Window,
 3839        cx: &mut Context<Self>,
 3840    ) {
 3841        if self.pending_rename.is_some() {
 3842            return;
 3843        }
 3844
 3845        let Some(provider) = self.completion_provider.as_ref() else {
 3846            return;
 3847        };
 3848
 3849        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3850            return;
 3851        }
 3852
 3853        let position = self.selections.newest_anchor().head();
 3854        if position.diff_base_anchor.is_some() {
 3855            return;
 3856        }
 3857        let (buffer, buffer_position) =
 3858            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3859                output
 3860            } else {
 3861                return;
 3862            };
 3863        let show_completion_documentation = buffer
 3864            .read(cx)
 3865            .snapshot()
 3866            .settings_at(buffer_position, cx)
 3867            .show_completion_documentation;
 3868
 3869        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3870
 3871        let trigger_kind = match &options.trigger {
 3872            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3873                CompletionTriggerKind::TRIGGER_CHARACTER
 3874            }
 3875            _ => CompletionTriggerKind::INVOKED,
 3876        };
 3877        let completion_context = CompletionContext {
 3878            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3879                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3880                    Some(String::from(trigger))
 3881                } else {
 3882                    None
 3883                }
 3884            }),
 3885            trigger_kind,
 3886        };
 3887        let completions =
 3888            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3889        let sort_completions = provider.sort_completions();
 3890
 3891        let id = post_inc(&mut self.next_completion_id);
 3892        let task = cx.spawn_in(window, |editor, mut cx| {
 3893            async move {
 3894                editor.update(&mut cx, |this, _| {
 3895                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3896                })?;
 3897                let completions = completions.await.log_err();
 3898                let menu = if let Some(completions) = completions {
 3899                    let mut menu = CompletionsMenu::new(
 3900                        id,
 3901                        sort_completions,
 3902                        show_completion_documentation,
 3903                        position,
 3904                        buffer.clone(),
 3905                        completions.into(),
 3906                    );
 3907
 3908                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3909                        .await;
 3910
 3911                    menu.visible().then_some(menu)
 3912                } else {
 3913                    None
 3914                };
 3915
 3916                editor.update_in(&mut cx, |editor, window, cx| {
 3917                    match editor.context_menu.borrow().as_ref() {
 3918                        None => {}
 3919                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3920                            if prev_menu.id > id {
 3921                                return;
 3922                            }
 3923                        }
 3924                        _ => return,
 3925                    }
 3926
 3927                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3928                        let mut menu = menu.unwrap();
 3929                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3930
 3931                        *editor.context_menu.borrow_mut() =
 3932                            Some(CodeContextMenu::Completions(menu));
 3933
 3934                        if editor.show_edit_predictions_in_menu() {
 3935                            editor.update_visible_inline_completion(window, cx);
 3936                        } else {
 3937                            editor.discard_inline_completion(false, cx);
 3938                        }
 3939
 3940                        cx.notify();
 3941                    } else if editor.completion_tasks.len() <= 1 {
 3942                        // If there are no more completion tasks and the last menu was
 3943                        // empty, we should hide it.
 3944                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3945                        // If it was already hidden and we don't show inline
 3946                        // completions in the menu, we should also show the
 3947                        // inline-completion when available.
 3948                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3949                            editor.update_visible_inline_completion(window, cx);
 3950                        }
 3951                    }
 3952                })?;
 3953
 3954                Ok::<_, anyhow::Error>(())
 3955            }
 3956            .log_err()
 3957        });
 3958
 3959        self.completion_tasks.push((id, task));
 3960    }
 3961
 3962    pub fn confirm_completion(
 3963        &mut self,
 3964        action: &ConfirmCompletion,
 3965        window: &mut Window,
 3966        cx: &mut Context<Self>,
 3967    ) -> Option<Task<Result<()>>> {
 3968        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3969    }
 3970
 3971    pub fn compose_completion(
 3972        &mut self,
 3973        action: &ComposeCompletion,
 3974        window: &mut Window,
 3975        cx: &mut Context<Self>,
 3976    ) -> Option<Task<Result<()>>> {
 3977        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3978    }
 3979
 3980    fn do_completion(
 3981        &mut self,
 3982        item_ix: Option<usize>,
 3983        intent: CompletionIntent,
 3984        window: &mut Window,
 3985        cx: &mut Context<Editor>,
 3986    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3987        use language::ToOffset as _;
 3988
 3989        let completions_menu =
 3990            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3991                menu
 3992            } else {
 3993                return None;
 3994            };
 3995
 3996        let entries = completions_menu.entries.borrow();
 3997        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3998        if self.show_edit_predictions_in_menu() {
 3999            self.discard_inline_completion(true, cx);
 4000        }
 4001        let candidate_id = mat.candidate_id;
 4002        drop(entries);
 4003
 4004        let buffer_handle = completions_menu.buffer;
 4005        let completion = completions_menu
 4006            .completions
 4007            .borrow()
 4008            .get(candidate_id)?
 4009            .clone();
 4010        cx.stop_propagation();
 4011
 4012        let snippet;
 4013        let text;
 4014
 4015        if completion.is_snippet() {
 4016            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4017            text = snippet.as_ref().unwrap().text.clone();
 4018        } else {
 4019            snippet = None;
 4020            text = completion.new_text.clone();
 4021        };
 4022        let selections = self.selections.all::<usize>(cx);
 4023        let buffer = buffer_handle.read(cx);
 4024        let old_range = completion.old_range.to_offset(buffer);
 4025        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4026
 4027        let newest_selection = self.selections.newest_anchor();
 4028        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4029            return None;
 4030        }
 4031
 4032        let lookbehind = newest_selection
 4033            .start
 4034            .text_anchor
 4035            .to_offset(buffer)
 4036            .saturating_sub(old_range.start);
 4037        let lookahead = old_range
 4038            .end
 4039            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4040        let mut common_prefix_len = old_text
 4041            .bytes()
 4042            .zip(text.bytes())
 4043            .take_while(|(a, b)| a == b)
 4044            .count();
 4045
 4046        let snapshot = self.buffer.read(cx).snapshot(cx);
 4047        let mut range_to_replace: Option<Range<isize>> = None;
 4048        let mut ranges = Vec::new();
 4049        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4050        for selection in &selections {
 4051            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4052                let start = selection.start.saturating_sub(lookbehind);
 4053                let end = selection.end + lookahead;
 4054                if selection.id == newest_selection.id {
 4055                    range_to_replace = Some(
 4056                        ((start + common_prefix_len) as isize - selection.start as isize)
 4057                            ..(end as isize - selection.start as isize),
 4058                    );
 4059                }
 4060                ranges.push(start + common_prefix_len..end);
 4061            } else {
 4062                common_prefix_len = 0;
 4063                ranges.clear();
 4064                ranges.extend(selections.iter().map(|s| {
 4065                    if s.id == newest_selection.id {
 4066                        range_to_replace = Some(
 4067                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4068                                - selection.start as isize
 4069                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4070                                    - selection.start as isize,
 4071                        );
 4072                        old_range.clone()
 4073                    } else {
 4074                        s.start..s.end
 4075                    }
 4076                }));
 4077                break;
 4078            }
 4079            if !self.linked_edit_ranges.is_empty() {
 4080                let start_anchor = snapshot.anchor_before(selection.head());
 4081                let end_anchor = snapshot.anchor_after(selection.tail());
 4082                if let Some(ranges) = self
 4083                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4084                {
 4085                    for (buffer, edits) in ranges {
 4086                        linked_edits.entry(buffer.clone()).or_default().extend(
 4087                            edits
 4088                                .into_iter()
 4089                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4090                        );
 4091                    }
 4092                }
 4093            }
 4094        }
 4095        let text = &text[common_prefix_len..];
 4096
 4097        cx.emit(EditorEvent::InputHandled {
 4098            utf16_range_to_replace: range_to_replace,
 4099            text: text.into(),
 4100        });
 4101
 4102        self.transact(window, cx, |this, window, cx| {
 4103            if let Some(mut snippet) = snippet {
 4104                snippet.text = text.to_string();
 4105                for tabstop in snippet
 4106                    .tabstops
 4107                    .iter_mut()
 4108                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4109                {
 4110                    tabstop.start -= common_prefix_len as isize;
 4111                    tabstop.end -= common_prefix_len as isize;
 4112                }
 4113
 4114                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4115            } else {
 4116                this.buffer.update(cx, |buffer, cx| {
 4117                    buffer.edit(
 4118                        ranges.iter().map(|range| (range.clone(), text)),
 4119                        this.autoindent_mode.clone(),
 4120                        cx,
 4121                    );
 4122                });
 4123            }
 4124            for (buffer, edits) in linked_edits {
 4125                buffer.update(cx, |buffer, cx| {
 4126                    let snapshot = buffer.snapshot();
 4127                    let edits = edits
 4128                        .into_iter()
 4129                        .map(|(range, text)| {
 4130                            use text::ToPoint as TP;
 4131                            let end_point = TP::to_point(&range.end, &snapshot);
 4132                            let start_point = TP::to_point(&range.start, &snapshot);
 4133                            (start_point..end_point, text)
 4134                        })
 4135                        .sorted_by_key(|(range, _)| range.start)
 4136                        .collect::<Vec<_>>();
 4137                    buffer.edit(edits, None, cx);
 4138                })
 4139            }
 4140
 4141            this.refresh_inline_completion(true, false, window, cx);
 4142        });
 4143
 4144        let show_new_completions_on_confirm = completion
 4145            .confirm
 4146            .as_ref()
 4147            .map_or(false, |confirm| confirm(intent, window, cx));
 4148        if show_new_completions_on_confirm {
 4149            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4150        }
 4151
 4152        let provider = self.completion_provider.as_ref()?;
 4153        drop(completion);
 4154        let apply_edits = provider.apply_additional_edits_for_completion(
 4155            buffer_handle,
 4156            completions_menu.completions.clone(),
 4157            candidate_id,
 4158            true,
 4159            cx,
 4160        );
 4161
 4162        let editor_settings = EditorSettings::get_global(cx);
 4163        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4164            // After the code completion is finished, users often want to know what signatures are needed.
 4165            // so we should automatically call signature_help
 4166            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4167        }
 4168
 4169        Some(cx.foreground_executor().spawn(async move {
 4170            apply_edits.await?;
 4171            Ok(())
 4172        }))
 4173    }
 4174
 4175    pub fn toggle_code_actions(
 4176        &mut self,
 4177        action: &ToggleCodeActions,
 4178        window: &mut Window,
 4179        cx: &mut Context<Self>,
 4180    ) {
 4181        let mut context_menu = self.context_menu.borrow_mut();
 4182        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4183            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4184                // Toggle if we're selecting the same one
 4185                *context_menu = None;
 4186                cx.notify();
 4187                return;
 4188            } else {
 4189                // Otherwise, clear it and start a new one
 4190                *context_menu = None;
 4191                cx.notify();
 4192            }
 4193        }
 4194        drop(context_menu);
 4195        let snapshot = self.snapshot(window, cx);
 4196        let deployed_from_indicator = action.deployed_from_indicator;
 4197        let mut task = self.code_actions_task.take();
 4198        let action = action.clone();
 4199        cx.spawn_in(window, |editor, mut cx| async move {
 4200            while let Some(prev_task) = task {
 4201                prev_task.await.log_err();
 4202                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4203            }
 4204
 4205            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4206                if editor.focus_handle.is_focused(window) {
 4207                    let multibuffer_point = action
 4208                        .deployed_from_indicator
 4209                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4210                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4211                    let (buffer, buffer_row) = snapshot
 4212                        .buffer_snapshot
 4213                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4214                        .and_then(|(buffer_snapshot, range)| {
 4215                            editor
 4216                                .buffer
 4217                                .read(cx)
 4218                                .buffer(buffer_snapshot.remote_id())
 4219                                .map(|buffer| (buffer, range.start.row))
 4220                        })?;
 4221                    let (_, code_actions) = editor
 4222                        .available_code_actions
 4223                        .clone()
 4224                        .and_then(|(location, code_actions)| {
 4225                            let snapshot = location.buffer.read(cx).snapshot();
 4226                            let point_range = location.range.to_point(&snapshot);
 4227                            let point_range = point_range.start.row..=point_range.end.row;
 4228                            if point_range.contains(&buffer_row) {
 4229                                Some((location, code_actions))
 4230                            } else {
 4231                                None
 4232                            }
 4233                        })
 4234                        .unzip();
 4235                    let buffer_id = buffer.read(cx).remote_id();
 4236                    let tasks = editor
 4237                        .tasks
 4238                        .get(&(buffer_id, buffer_row))
 4239                        .map(|t| Arc::new(t.to_owned()));
 4240                    if tasks.is_none() && code_actions.is_none() {
 4241                        return None;
 4242                    }
 4243
 4244                    editor.completion_tasks.clear();
 4245                    editor.discard_inline_completion(false, cx);
 4246                    let task_context =
 4247                        tasks
 4248                            .as_ref()
 4249                            .zip(editor.project.clone())
 4250                            .map(|(tasks, project)| {
 4251                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4252                            });
 4253
 4254                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4255                        let task_context = match task_context {
 4256                            Some(task_context) => task_context.await,
 4257                            None => None,
 4258                        };
 4259                        let resolved_tasks =
 4260                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4261                                Rc::new(ResolvedTasks {
 4262                                    templates: tasks.resolve(&task_context).collect(),
 4263                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4264                                        multibuffer_point.row,
 4265                                        tasks.column,
 4266                                    )),
 4267                                })
 4268                            });
 4269                        let spawn_straight_away = resolved_tasks
 4270                            .as_ref()
 4271                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4272                            && code_actions
 4273                                .as_ref()
 4274                                .map_or(true, |actions| actions.is_empty());
 4275                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4276                            *editor.context_menu.borrow_mut() =
 4277                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4278                                    buffer,
 4279                                    actions: CodeActionContents {
 4280                                        tasks: resolved_tasks,
 4281                                        actions: code_actions,
 4282                                    },
 4283                                    selected_item: Default::default(),
 4284                                    scroll_handle: UniformListScrollHandle::default(),
 4285                                    deployed_from_indicator,
 4286                                }));
 4287                            if spawn_straight_away {
 4288                                if let Some(task) = editor.confirm_code_action(
 4289                                    &ConfirmCodeAction { item_ix: Some(0) },
 4290                                    window,
 4291                                    cx,
 4292                                ) {
 4293                                    cx.notify();
 4294                                    return task;
 4295                                }
 4296                            }
 4297                            cx.notify();
 4298                            Task::ready(Ok(()))
 4299                        }) {
 4300                            task.await
 4301                        } else {
 4302                            Ok(())
 4303                        }
 4304                    }))
 4305                } else {
 4306                    Some(Task::ready(Ok(())))
 4307                }
 4308            })?;
 4309            if let Some(task) = spawned_test_task {
 4310                task.await?;
 4311            }
 4312
 4313            Ok::<_, anyhow::Error>(())
 4314        })
 4315        .detach_and_log_err(cx);
 4316    }
 4317
 4318    pub fn confirm_code_action(
 4319        &mut self,
 4320        action: &ConfirmCodeAction,
 4321        window: &mut Window,
 4322        cx: &mut Context<Self>,
 4323    ) -> Option<Task<Result<()>>> {
 4324        let actions_menu =
 4325            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4326                menu
 4327            } else {
 4328                return None;
 4329            };
 4330        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4331        let action = actions_menu.actions.get(action_ix)?;
 4332        let title = action.label();
 4333        let buffer = actions_menu.buffer;
 4334        let workspace = self.workspace()?;
 4335
 4336        match action {
 4337            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4338                workspace.update(cx, |workspace, cx| {
 4339                    workspace::tasks::schedule_resolved_task(
 4340                        workspace,
 4341                        task_source_kind,
 4342                        resolved_task,
 4343                        false,
 4344                        cx,
 4345                    );
 4346
 4347                    Some(Task::ready(Ok(())))
 4348                })
 4349            }
 4350            CodeActionsItem::CodeAction {
 4351                excerpt_id,
 4352                action,
 4353                provider,
 4354            } => {
 4355                let apply_code_action =
 4356                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4357                let workspace = workspace.downgrade();
 4358                Some(cx.spawn_in(window, |editor, cx| async move {
 4359                    let project_transaction = apply_code_action.await?;
 4360                    Self::open_project_transaction(
 4361                        &editor,
 4362                        workspace,
 4363                        project_transaction,
 4364                        title,
 4365                        cx,
 4366                    )
 4367                    .await
 4368                }))
 4369            }
 4370        }
 4371    }
 4372
 4373    pub async fn open_project_transaction(
 4374        this: &WeakEntity<Editor>,
 4375        workspace: WeakEntity<Workspace>,
 4376        transaction: ProjectTransaction,
 4377        title: String,
 4378        mut cx: AsyncWindowContext,
 4379    ) -> Result<()> {
 4380        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4381        cx.update(|_, cx| {
 4382            entries.sort_unstable_by_key(|(buffer, _)| {
 4383                buffer.read(cx).file().map(|f| f.path().clone())
 4384            });
 4385        })?;
 4386
 4387        // If the project transaction's edits are all contained within this editor, then
 4388        // avoid opening a new editor to display them.
 4389
 4390        if let Some((buffer, transaction)) = entries.first() {
 4391            if entries.len() == 1 {
 4392                let excerpt = this.update(&mut cx, |editor, cx| {
 4393                    editor
 4394                        .buffer()
 4395                        .read(cx)
 4396                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4397                })?;
 4398                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4399                    if excerpted_buffer == *buffer {
 4400                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4401                            let excerpt_range = excerpt_range.to_offset(buffer);
 4402                            buffer
 4403                                .edited_ranges_for_transaction::<usize>(transaction)
 4404                                .all(|range| {
 4405                                    excerpt_range.start <= range.start
 4406                                        && excerpt_range.end >= range.end
 4407                                })
 4408                        })?;
 4409
 4410                        if all_edits_within_excerpt {
 4411                            return Ok(());
 4412                        }
 4413                    }
 4414                }
 4415            }
 4416        } else {
 4417            return Ok(());
 4418        }
 4419
 4420        let mut ranges_to_highlight = Vec::new();
 4421        let excerpt_buffer = cx.new(|cx| {
 4422            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4423            for (buffer_handle, transaction) in &entries {
 4424                let buffer = buffer_handle.read(cx);
 4425                ranges_to_highlight.extend(
 4426                    multibuffer.push_excerpts_with_context_lines(
 4427                        buffer_handle.clone(),
 4428                        buffer
 4429                            .edited_ranges_for_transaction::<usize>(transaction)
 4430                            .collect(),
 4431                        DEFAULT_MULTIBUFFER_CONTEXT,
 4432                        cx,
 4433                    ),
 4434                );
 4435            }
 4436            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4437            multibuffer
 4438        })?;
 4439
 4440        workspace.update_in(&mut cx, |workspace, window, cx| {
 4441            let project = workspace.project().clone();
 4442            let editor = cx
 4443                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4444            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4445            editor.update(cx, |editor, cx| {
 4446                editor.highlight_background::<Self>(
 4447                    &ranges_to_highlight,
 4448                    |theme| theme.editor_highlighted_line_background,
 4449                    cx,
 4450                );
 4451            });
 4452        })?;
 4453
 4454        Ok(())
 4455    }
 4456
 4457    pub fn clear_code_action_providers(&mut self) {
 4458        self.code_action_providers.clear();
 4459        self.available_code_actions.take();
 4460    }
 4461
 4462    pub fn add_code_action_provider(
 4463        &mut self,
 4464        provider: Rc<dyn CodeActionProvider>,
 4465        window: &mut Window,
 4466        cx: &mut Context<Self>,
 4467    ) {
 4468        if self
 4469            .code_action_providers
 4470            .iter()
 4471            .any(|existing_provider| existing_provider.id() == provider.id())
 4472        {
 4473            return;
 4474        }
 4475
 4476        self.code_action_providers.push(provider);
 4477        self.refresh_code_actions(window, cx);
 4478    }
 4479
 4480    pub fn remove_code_action_provider(
 4481        &mut self,
 4482        id: Arc<str>,
 4483        window: &mut Window,
 4484        cx: &mut Context<Self>,
 4485    ) {
 4486        self.code_action_providers
 4487            .retain(|provider| provider.id() != id);
 4488        self.refresh_code_actions(window, cx);
 4489    }
 4490
 4491    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4492        let buffer = self.buffer.read(cx);
 4493        let newest_selection = self.selections.newest_anchor().clone();
 4494        if newest_selection.head().diff_base_anchor.is_some() {
 4495            return None;
 4496        }
 4497        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4498        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4499        if start_buffer != end_buffer {
 4500            return None;
 4501        }
 4502
 4503        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4504            cx.background_executor()
 4505                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4506                .await;
 4507
 4508            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4509                let providers = this.code_action_providers.clone();
 4510                let tasks = this
 4511                    .code_action_providers
 4512                    .iter()
 4513                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4514                    .collect::<Vec<_>>();
 4515                (providers, tasks)
 4516            })?;
 4517
 4518            let mut actions = Vec::new();
 4519            for (provider, provider_actions) in
 4520                providers.into_iter().zip(future::join_all(tasks).await)
 4521            {
 4522                if let Some(provider_actions) = provider_actions.log_err() {
 4523                    actions.extend(provider_actions.into_iter().map(|action| {
 4524                        AvailableCodeAction {
 4525                            excerpt_id: newest_selection.start.excerpt_id,
 4526                            action,
 4527                            provider: provider.clone(),
 4528                        }
 4529                    }));
 4530                }
 4531            }
 4532
 4533            this.update(&mut cx, |this, cx| {
 4534                this.available_code_actions = if actions.is_empty() {
 4535                    None
 4536                } else {
 4537                    Some((
 4538                        Location {
 4539                            buffer: start_buffer,
 4540                            range: start..end,
 4541                        },
 4542                        actions.into(),
 4543                    ))
 4544                };
 4545                cx.notify();
 4546            })
 4547        }));
 4548        None
 4549    }
 4550
 4551    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4552        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4553            self.show_git_blame_inline = false;
 4554
 4555            self.show_git_blame_inline_delay_task =
 4556                Some(cx.spawn_in(window, |this, mut cx| async move {
 4557                    cx.background_executor().timer(delay).await;
 4558
 4559                    this.update(&mut cx, |this, cx| {
 4560                        this.show_git_blame_inline = true;
 4561                        cx.notify();
 4562                    })
 4563                    .log_err();
 4564                }));
 4565        }
 4566    }
 4567
 4568    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4569        if self.pending_rename.is_some() {
 4570            return None;
 4571        }
 4572
 4573        let provider = self.semantics_provider.clone()?;
 4574        let buffer = self.buffer.read(cx);
 4575        let newest_selection = self.selections.newest_anchor().clone();
 4576        let cursor_position = newest_selection.head();
 4577        let (cursor_buffer, cursor_buffer_position) =
 4578            buffer.text_anchor_for_position(cursor_position, cx)?;
 4579        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4580        if cursor_buffer != tail_buffer {
 4581            return None;
 4582        }
 4583        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4584        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4585            cx.background_executor()
 4586                .timer(Duration::from_millis(debounce))
 4587                .await;
 4588
 4589            let highlights = if let Some(highlights) = cx
 4590                .update(|cx| {
 4591                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4592                })
 4593                .ok()
 4594                .flatten()
 4595            {
 4596                highlights.await.log_err()
 4597            } else {
 4598                None
 4599            };
 4600
 4601            if let Some(highlights) = highlights {
 4602                this.update(&mut cx, |this, cx| {
 4603                    if this.pending_rename.is_some() {
 4604                        return;
 4605                    }
 4606
 4607                    let buffer_id = cursor_position.buffer_id;
 4608                    let buffer = this.buffer.read(cx);
 4609                    if !buffer
 4610                        .text_anchor_for_position(cursor_position, cx)
 4611                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4612                    {
 4613                        return;
 4614                    }
 4615
 4616                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4617                    let mut write_ranges = Vec::new();
 4618                    let mut read_ranges = Vec::new();
 4619                    for highlight in highlights {
 4620                        for (excerpt_id, excerpt_range) in
 4621                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4622                        {
 4623                            let start = highlight
 4624                                .range
 4625                                .start
 4626                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4627                            let end = highlight
 4628                                .range
 4629                                .end
 4630                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4631                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4632                                continue;
 4633                            }
 4634
 4635                            let range = Anchor {
 4636                                buffer_id,
 4637                                excerpt_id,
 4638                                text_anchor: start,
 4639                                diff_base_anchor: None,
 4640                            }..Anchor {
 4641                                buffer_id,
 4642                                excerpt_id,
 4643                                text_anchor: end,
 4644                                diff_base_anchor: None,
 4645                            };
 4646                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4647                                write_ranges.push(range);
 4648                            } else {
 4649                                read_ranges.push(range);
 4650                            }
 4651                        }
 4652                    }
 4653
 4654                    this.highlight_background::<DocumentHighlightRead>(
 4655                        &read_ranges,
 4656                        |theme| theme.editor_document_highlight_read_background,
 4657                        cx,
 4658                    );
 4659                    this.highlight_background::<DocumentHighlightWrite>(
 4660                        &write_ranges,
 4661                        |theme| theme.editor_document_highlight_write_background,
 4662                        cx,
 4663                    );
 4664                    cx.notify();
 4665                })
 4666                .log_err();
 4667            }
 4668        }));
 4669        None
 4670    }
 4671
 4672    pub fn refresh_inline_completion(
 4673        &mut self,
 4674        debounce: bool,
 4675        user_requested: bool,
 4676        window: &mut Window,
 4677        cx: &mut Context<Self>,
 4678    ) -> Option<()> {
 4679        let provider = self.edit_prediction_provider()?;
 4680        let cursor = self.selections.newest_anchor().head();
 4681        let (buffer, cursor_buffer_position) =
 4682            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4683
 4684        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4685            self.discard_inline_completion(false, cx);
 4686            return None;
 4687        }
 4688
 4689        if !user_requested
 4690            && (!self.should_show_edit_predictions()
 4691                || !self.is_focused(window)
 4692                || buffer.read(cx).is_empty())
 4693        {
 4694            self.discard_inline_completion(false, cx);
 4695            return None;
 4696        }
 4697
 4698        self.update_visible_inline_completion(window, cx);
 4699        provider.refresh(
 4700            self.project.clone(),
 4701            buffer,
 4702            cursor_buffer_position,
 4703            debounce,
 4704            cx,
 4705        );
 4706        Some(())
 4707    }
 4708
 4709    fn show_edit_predictions_in_menu(&self) -> bool {
 4710        match self.edit_prediction_settings {
 4711            EditPredictionSettings::Disabled => false,
 4712            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4713        }
 4714    }
 4715
 4716    pub fn edit_predictions_enabled(&self) -> bool {
 4717        match self.edit_prediction_settings {
 4718            EditPredictionSettings::Disabled => false,
 4719            EditPredictionSettings::Enabled { .. } => true,
 4720        }
 4721    }
 4722
 4723    fn edit_prediction_requires_modifier(&self) -> bool {
 4724        match self.edit_prediction_settings {
 4725            EditPredictionSettings::Disabled => false,
 4726            EditPredictionSettings::Enabled {
 4727                preview_requires_modifier,
 4728                ..
 4729            } => preview_requires_modifier,
 4730        }
 4731    }
 4732
 4733    fn edit_prediction_settings_at_position(
 4734        &self,
 4735        buffer: &Entity<Buffer>,
 4736        buffer_position: language::Anchor,
 4737        cx: &App,
 4738    ) -> EditPredictionSettings {
 4739        if self.mode != EditorMode::Full
 4740            || !self.show_inline_completions_override.unwrap_or(true)
 4741            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4742        {
 4743            return EditPredictionSettings::Disabled;
 4744        }
 4745
 4746        let buffer = buffer.read(cx);
 4747
 4748        let file = buffer.file();
 4749
 4750        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4751            return EditPredictionSettings::Disabled;
 4752        };
 4753
 4754        let by_provider = matches!(
 4755            self.menu_inline_completions_policy,
 4756            MenuInlineCompletionsPolicy::ByProvider
 4757        );
 4758
 4759        let show_in_menu = by_provider
 4760            && EditorSettings::get_global(cx).show_edit_predictions_in_menu
 4761            && self
 4762                .edit_prediction_provider
 4763                .as_ref()
 4764                .map_or(false, |provider| {
 4765                    provider.provider.show_completions_in_menu()
 4766                });
 4767
 4768        let preview_requires_modifier = all_language_settings(file, cx)
 4769            .inline_completions_preview_mode()
 4770            == InlineCompletionPreviewMode::WhenHoldingModifier;
 4771
 4772        EditPredictionSettings::Enabled {
 4773            show_in_menu,
 4774            preview_requires_modifier,
 4775        }
 4776    }
 4777
 4778    fn should_show_edit_predictions(&self) -> bool {
 4779        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4780    }
 4781
 4782    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4783        let cursor = self.selections.newest_anchor().head();
 4784        if let Some((buffer, cursor_position)) =
 4785            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4786        {
 4787            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4788        } else {
 4789            false
 4790        }
 4791    }
 4792
 4793    fn inline_completions_enabled_in_buffer(
 4794        &self,
 4795        buffer: &Entity<Buffer>,
 4796        buffer_position: language::Anchor,
 4797        cx: &App,
 4798    ) -> bool {
 4799        maybe!({
 4800            let provider = self.edit_prediction_provider()?;
 4801            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4802                return Some(false);
 4803            }
 4804            let buffer = buffer.read(cx);
 4805            let Some(file) = buffer.file() else {
 4806                return Some(true);
 4807            };
 4808            let settings = all_language_settings(Some(file), cx);
 4809            Some(settings.inline_completions_enabled_for_path(file.path()))
 4810        })
 4811        .unwrap_or(false)
 4812    }
 4813
 4814    fn cycle_inline_completion(
 4815        &mut self,
 4816        direction: Direction,
 4817        window: &mut Window,
 4818        cx: &mut Context<Self>,
 4819    ) -> Option<()> {
 4820        let provider = self.edit_prediction_provider()?;
 4821        let cursor = self.selections.newest_anchor().head();
 4822        let (buffer, cursor_buffer_position) =
 4823            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4824        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4825            return None;
 4826        }
 4827
 4828        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4829        self.update_visible_inline_completion(window, cx);
 4830
 4831        Some(())
 4832    }
 4833
 4834    pub fn show_inline_completion(
 4835        &mut self,
 4836        _: &ShowEditPrediction,
 4837        window: &mut Window,
 4838        cx: &mut Context<Self>,
 4839    ) {
 4840        if !self.has_active_inline_completion() {
 4841            self.refresh_inline_completion(false, true, window, cx);
 4842            return;
 4843        }
 4844
 4845        self.update_visible_inline_completion(window, cx);
 4846    }
 4847
 4848    pub fn display_cursor_names(
 4849        &mut self,
 4850        _: &DisplayCursorNames,
 4851        window: &mut Window,
 4852        cx: &mut Context<Self>,
 4853    ) {
 4854        self.show_cursor_names(window, cx);
 4855    }
 4856
 4857    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4858        self.show_cursor_names = true;
 4859        cx.notify();
 4860        cx.spawn_in(window, |this, mut cx| async move {
 4861            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4862            this.update(&mut cx, |this, cx| {
 4863                this.show_cursor_names = false;
 4864                cx.notify()
 4865            })
 4866            .ok()
 4867        })
 4868        .detach();
 4869    }
 4870
 4871    pub fn next_edit_prediction(
 4872        &mut self,
 4873        _: &NextEditPrediction,
 4874        window: &mut Window,
 4875        cx: &mut Context<Self>,
 4876    ) {
 4877        if self.has_active_inline_completion() {
 4878            self.cycle_inline_completion(Direction::Next, window, cx);
 4879        } else {
 4880            let is_copilot_disabled = self
 4881                .refresh_inline_completion(false, true, window, cx)
 4882                .is_none();
 4883            if is_copilot_disabled {
 4884                cx.propagate();
 4885            }
 4886        }
 4887    }
 4888
 4889    pub fn previous_edit_prediction(
 4890        &mut self,
 4891        _: &PreviousEditPrediction,
 4892        window: &mut Window,
 4893        cx: &mut Context<Self>,
 4894    ) {
 4895        if self.has_active_inline_completion() {
 4896            self.cycle_inline_completion(Direction::Prev, window, cx);
 4897        } else {
 4898            let is_copilot_disabled = self
 4899                .refresh_inline_completion(false, true, window, cx)
 4900                .is_none();
 4901            if is_copilot_disabled {
 4902                cx.propagate();
 4903            }
 4904        }
 4905    }
 4906
 4907    pub fn accept_edit_prediction(
 4908        &mut self,
 4909        _: &AcceptEditPrediction,
 4910        window: &mut Window,
 4911        cx: &mut Context<Self>,
 4912    ) {
 4913        let buffer = self.buffer.read(cx);
 4914        let snapshot = buffer.snapshot(cx);
 4915        let selection = self.selections.newest_adjusted(cx);
 4916        let cursor = selection.head();
 4917        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4918        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4919        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4920        {
 4921            if cursor.column < suggested_indent.len
 4922                && cursor.column <= current_indent.len
 4923                && current_indent.len <= suggested_indent.len
 4924            {
 4925                self.tab(&Default::default(), window, cx);
 4926                return;
 4927            }
 4928        }
 4929
 4930        if self.show_edit_predictions_in_menu() {
 4931            self.hide_context_menu(window, cx);
 4932        }
 4933
 4934        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4935            return;
 4936        };
 4937
 4938        self.report_inline_completion_event(
 4939            active_inline_completion.completion_id.clone(),
 4940            true,
 4941            cx,
 4942        );
 4943
 4944        match &active_inline_completion.completion {
 4945            InlineCompletion::Move { target, .. } => {
 4946                let target = *target;
 4947                // Note that this is also done in vim's handler of the Tab action.
 4948                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4949                    selections.select_anchor_ranges([target..target]);
 4950                });
 4951            }
 4952            InlineCompletion::Edit { edits, .. } => {
 4953                if let Some(provider) = self.edit_prediction_provider() {
 4954                    provider.accept(cx);
 4955                }
 4956
 4957                let snapshot = self.buffer.read(cx).snapshot(cx);
 4958                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4959
 4960                self.buffer.update(cx, |buffer, cx| {
 4961                    buffer.edit(edits.iter().cloned(), None, cx)
 4962                });
 4963
 4964                self.change_selections(None, window, cx, |s| {
 4965                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4966                });
 4967
 4968                self.update_visible_inline_completion(window, cx);
 4969                if self.active_inline_completion.is_none() {
 4970                    self.refresh_inline_completion(true, true, window, cx);
 4971                }
 4972
 4973                cx.notify();
 4974            }
 4975        }
 4976    }
 4977
 4978    pub fn accept_partial_inline_completion(
 4979        &mut self,
 4980        _: &AcceptPartialEditPrediction,
 4981        window: &mut Window,
 4982        cx: &mut Context<Self>,
 4983    ) {
 4984        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4985            return;
 4986        };
 4987        if self.selections.count() != 1 {
 4988            return;
 4989        }
 4990
 4991        self.report_inline_completion_event(
 4992            active_inline_completion.completion_id.clone(),
 4993            true,
 4994            cx,
 4995        );
 4996
 4997        match &active_inline_completion.completion {
 4998            InlineCompletion::Move { target, .. } => {
 4999                let target = *target;
 5000                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5001                    selections.select_anchor_ranges([target..target]);
 5002                });
 5003            }
 5004            InlineCompletion::Edit { edits, .. } => {
 5005                // Find an insertion that starts at the cursor position.
 5006                let snapshot = self.buffer.read(cx).snapshot(cx);
 5007                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5008                let insertion = edits.iter().find_map(|(range, text)| {
 5009                    let range = range.to_offset(&snapshot);
 5010                    if range.is_empty() && range.start == cursor_offset {
 5011                        Some(text)
 5012                    } else {
 5013                        None
 5014                    }
 5015                });
 5016
 5017                if let Some(text) = insertion {
 5018                    let mut partial_completion = text
 5019                        .chars()
 5020                        .by_ref()
 5021                        .take_while(|c| c.is_alphabetic())
 5022                        .collect::<String>();
 5023                    if partial_completion.is_empty() {
 5024                        partial_completion = text
 5025                            .chars()
 5026                            .by_ref()
 5027                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5028                            .collect::<String>();
 5029                    }
 5030
 5031                    cx.emit(EditorEvent::InputHandled {
 5032                        utf16_range_to_replace: None,
 5033                        text: partial_completion.clone().into(),
 5034                    });
 5035
 5036                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5037
 5038                    self.refresh_inline_completion(true, true, window, cx);
 5039                    cx.notify();
 5040                } else {
 5041                    self.accept_edit_prediction(&Default::default(), window, cx);
 5042                }
 5043            }
 5044        }
 5045    }
 5046
 5047    fn discard_inline_completion(
 5048        &mut self,
 5049        should_report_inline_completion_event: bool,
 5050        cx: &mut Context<Self>,
 5051    ) -> bool {
 5052        if should_report_inline_completion_event {
 5053            let completion_id = self
 5054                .active_inline_completion
 5055                .as_ref()
 5056                .and_then(|active_completion| active_completion.completion_id.clone());
 5057
 5058            self.report_inline_completion_event(completion_id, false, cx);
 5059        }
 5060
 5061        if let Some(provider) = self.edit_prediction_provider() {
 5062            provider.discard(cx);
 5063        }
 5064
 5065        self.take_active_inline_completion(cx)
 5066    }
 5067
 5068    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5069        let Some(provider) = self.edit_prediction_provider() else {
 5070            return;
 5071        };
 5072
 5073        let Some((_, buffer, _)) = self
 5074            .buffer
 5075            .read(cx)
 5076            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5077        else {
 5078            return;
 5079        };
 5080
 5081        let extension = buffer
 5082            .read(cx)
 5083            .file()
 5084            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5085
 5086        let event_type = match accepted {
 5087            true => "Edit Prediction Accepted",
 5088            false => "Edit Prediction Discarded",
 5089        };
 5090        telemetry::event!(
 5091            event_type,
 5092            provider = provider.name(),
 5093            prediction_id = id,
 5094            suggestion_accepted = accepted,
 5095            file_extension = extension,
 5096        );
 5097    }
 5098
 5099    pub fn has_active_inline_completion(&self) -> bool {
 5100        self.active_inline_completion.is_some()
 5101    }
 5102
 5103    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5104        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5105            return false;
 5106        };
 5107
 5108        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5109        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5110        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5111        true
 5112    }
 5113
 5114    /// Returns true when we're displaying the inline completion popover below the cursor
 5115    /// like we are not previewing and the LSP autocomplete menu is visible
 5116    /// or we are in `when_holding_modifier` mode.
 5117    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5118        if self.previewing_inline_completion
 5119            || !self.show_edit_predictions_in_menu()
 5120            || !self.edit_predictions_enabled()
 5121        {
 5122            return false;
 5123        }
 5124
 5125        if self.has_visible_completions_menu() {
 5126            return true;
 5127        }
 5128
 5129        has_completion && self.edit_prediction_requires_modifier()
 5130    }
 5131
 5132    fn handle_modifiers_changed(
 5133        &mut self,
 5134        modifiers: Modifiers,
 5135        position_map: &PositionMap,
 5136        window: &mut Window,
 5137        cx: &mut Context<Self>,
 5138    ) {
 5139        if self.show_edit_predictions_in_menu() {
 5140            let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5141            if let Some(accept_keystroke) = accept_binding.keystroke() {
 5142                let was_previewing_inline_completion = self.previewing_inline_completion;
 5143                self.previewing_inline_completion = modifiers == accept_keystroke.modifiers
 5144                    && accept_keystroke.modifiers.modified();
 5145                if self.previewing_inline_completion != was_previewing_inline_completion {
 5146                    self.update_visible_inline_completion(window, cx);
 5147                }
 5148            }
 5149        }
 5150
 5151        let mouse_position = window.mouse_position();
 5152        if !position_map.text_hitbox.is_hovered(window) {
 5153            return;
 5154        }
 5155
 5156        self.update_hovered_link(
 5157            position_map.point_for_position(mouse_position),
 5158            &position_map.snapshot,
 5159            modifiers,
 5160            window,
 5161            cx,
 5162        )
 5163    }
 5164
 5165    fn update_visible_inline_completion(
 5166        &mut self,
 5167        _window: &mut Window,
 5168        cx: &mut Context<Self>,
 5169    ) -> Option<()> {
 5170        let selection = self.selections.newest_anchor();
 5171        let cursor = selection.head();
 5172        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5173        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5174        let excerpt_id = cursor.excerpt_id;
 5175
 5176        let show_in_menu = self.show_edit_predictions_in_menu();
 5177        let completions_menu_has_precedence = !show_in_menu
 5178            && (self.context_menu.borrow().is_some()
 5179                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5180
 5181        if completions_menu_has_precedence
 5182            || !offset_selection.is_empty()
 5183            || self
 5184                .active_inline_completion
 5185                .as_ref()
 5186                .map_or(false, |completion| {
 5187                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5188                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5189                    !invalidation_range.contains(&offset_selection.head())
 5190                })
 5191        {
 5192            self.discard_inline_completion(false, cx);
 5193            return None;
 5194        }
 5195
 5196        self.take_active_inline_completion(cx);
 5197        let Some(provider) = self.edit_prediction_provider() else {
 5198            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5199            return None;
 5200        };
 5201
 5202        let (buffer, cursor_buffer_position) =
 5203            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5204
 5205        self.edit_prediction_settings =
 5206            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5207
 5208        if !self.edit_prediction_settings.is_enabled() {
 5209            self.discard_inline_completion(false, cx);
 5210            return None;
 5211        }
 5212
 5213        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5214        let edits = inline_completion
 5215            .edits
 5216            .into_iter()
 5217            .flat_map(|(range, new_text)| {
 5218                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5219                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5220                Some((start..end, new_text))
 5221            })
 5222            .collect::<Vec<_>>();
 5223        if edits.is_empty() {
 5224            return None;
 5225        }
 5226
 5227        let first_edit_start = edits.first().unwrap().0.start;
 5228        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5229        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5230
 5231        let last_edit_end = edits.last().unwrap().0.end;
 5232        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5233        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5234
 5235        let cursor_row = cursor.to_point(&multibuffer).row;
 5236
 5237        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5238
 5239        let mut inlay_ids = Vec::new();
 5240        let invalidation_row_range;
 5241        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5242            Some(cursor_row..edit_end_row)
 5243        } else if cursor_row > edit_end_row {
 5244            Some(edit_start_row..cursor_row)
 5245        } else {
 5246            None
 5247        };
 5248        let is_move =
 5249            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5250        let completion = if is_move {
 5251            invalidation_row_range =
 5252                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5253            let target = first_edit_start;
 5254            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5255            // TODO: Base this off of TreeSitter or word boundaries?
 5256            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5257                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5258                Bias::Left,
 5259            ));
 5260            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5261                Point::new(target_point.row, target_point.column + 20),
 5262                Bias::Right,
 5263            ));
 5264            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5265            InlineCompletion::Move {
 5266                target,
 5267                range_around_target,
 5268                snapshot,
 5269            }
 5270        } else {
 5271            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5272                && !self.inline_completions_hidden_for_vim_mode;
 5273            if show_completions_in_buffer {
 5274                if edits
 5275                    .iter()
 5276                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5277                {
 5278                    let mut inlays = Vec::new();
 5279                    for (range, new_text) in &edits {
 5280                        let inlay = Inlay::inline_completion(
 5281                            post_inc(&mut self.next_inlay_id),
 5282                            range.start,
 5283                            new_text.as_str(),
 5284                        );
 5285                        inlay_ids.push(inlay.id);
 5286                        inlays.push(inlay);
 5287                    }
 5288
 5289                    self.splice_inlays(&[], inlays, cx);
 5290                } else {
 5291                    let background_color = cx.theme().status().deleted_background;
 5292                    self.highlight_text::<InlineCompletionHighlight>(
 5293                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5294                        HighlightStyle {
 5295                            background_color: Some(background_color),
 5296                            ..Default::default()
 5297                        },
 5298                        cx,
 5299                    );
 5300                }
 5301            }
 5302
 5303            invalidation_row_range = edit_start_row..edit_end_row;
 5304
 5305            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5306                if provider.show_tab_accept_marker() {
 5307                    EditDisplayMode::TabAccept
 5308                } else {
 5309                    EditDisplayMode::Inline
 5310                }
 5311            } else {
 5312                EditDisplayMode::DiffPopover
 5313            };
 5314
 5315            InlineCompletion::Edit {
 5316                edits,
 5317                edit_preview: inline_completion.edit_preview,
 5318                display_mode,
 5319                snapshot,
 5320            }
 5321        };
 5322
 5323        let invalidation_range = multibuffer
 5324            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5325            ..multibuffer.anchor_after(Point::new(
 5326                invalidation_row_range.end,
 5327                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5328            ));
 5329
 5330        self.stale_inline_completion_in_menu = None;
 5331        self.active_inline_completion = Some(InlineCompletionState {
 5332            inlay_ids,
 5333            completion,
 5334            completion_id: inline_completion.id,
 5335            invalidation_range,
 5336        });
 5337
 5338        cx.notify();
 5339
 5340        Some(())
 5341    }
 5342
 5343    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5344        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5345    }
 5346
 5347    fn render_code_actions_indicator(
 5348        &self,
 5349        _style: &EditorStyle,
 5350        row: DisplayRow,
 5351        is_active: bool,
 5352        cx: &mut Context<Self>,
 5353    ) -> Option<IconButton> {
 5354        if self.available_code_actions.is_some() {
 5355            Some(
 5356                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5357                    .shape(ui::IconButtonShape::Square)
 5358                    .icon_size(IconSize::XSmall)
 5359                    .icon_color(Color::Muted)
 5360                    .toggle_state(is_active)
 5361                    .tooltip({
 5362                        let focus_handle = self.focus_handle.clone();
 5363                        move |window, cx| {
 5364                            Tooltip::for_action_in(
 5365                                "Toggle Code Actions",
 5366                                &ToggleCodeActions {
 5367                                    deployed_from_indicator: None,
 5368                                },
 5369                                &focus_handle,
 5370                                window,
 5371                                cx,
 5372                            )
 5373                        }
 5374                    })
 5375                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5376                        window.focus(&editor.focus_handle(cx));
 5377                        editor.toggle_code_actions(
 5378                            &ToggleCodeActions {
 5379                                deployed_from_indicator: Some(row),
 5380                            },
 5381                            window,
 5382                            cx,
 5383                        );
 5384                    })),
 5385            )
 5386        } else {
 5387            None
 5388        }
 5389    }
 5390
 5391    fn clear_tasks(&mut self) {
 5392        self.tasks.clear()
 5393    }
 5394
 5395    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5396        if self.tasks.insert(key, value).is_some() {
 5397            // This case should hopefully be rare, but just in case...
 5398            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5399        }
 5400    }
 5401
 5402    fn build_tasks_context(
 5403        project: &Entity<Project>,
 5404        buffer: &Entity<Buffer>,
 5405        buffer_row: u32,
 5406        tasks: &Arc<RunnableTasks>,
 5407        cx: &mut Context<Self>,
 5408    ) -> Task<Option<task::TaskContext>> {
 5409        let position = Point::new(buffer_row, tasks.column);
 5410        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5411        let location = Location {
 5412            buffer: buffer.clone(),
 5413            range: range_start..range_start,
 5414        };
 5415        // Fill in the environmental variables from the tree-sitter captures
 5416        let mut captured_task_variables = TaskVariables::default();
 5417        for (capture_name, value) in tasks.extra_variables.clone() {
 5418            captured_task_variables.insert(
 5419                task::VariableName::Custom(capture_name.into()),
 5420                value.clone(),
 5421            );
 5422        }
 5423        project.update(cx, |project, cx| {
 5424            project.task_store().update(cx, |task_store, cx| {
 5425                task_store.task_context_for_location(captured_task_variables, location, cx)
 5426            })
 5427        })
 5428    }
 5429
 5430    pub fn spawn_nearest_task(
 5431        &mut self,
 5432        action: &SpawnNearestTask,
 5433        window: &mut Window,
 5434        cx: &mut Context<Self>,
 5435    ) {
 5436        let Some((workspace, _)) = self.workspace.clone() else {
 5437            return;
 5438        };
 5439        let Some(project) = self.project.clone() else {
 5440            return;
 5441        };
 5442
 5443        // Try to find a closest, enclosing node using tree-sitter that has a
 5444        // task
 5445        let Some((buffer, buffer_row, tasks)) = self
 5446            .find_enclosing_node_task(cx)
 5447            // Or find the task that's closest in row-distance.
 5448            .or_else(|| self.find_closest_task(cx))
 5449        else {
 5450            return;
 5451        };
 5452
 5453        let reveal_strategy = action.reveal;
 5454        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5455        cx.spawn_in(window, |_, mut cx| async move {
 5456            let context = task_context.await?;
 5457            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5458
 5459            let resolved = resolved_task.resolved.as_mut()?;
 5460            resolved.reveal = reveal_strategy;
 5461
 5462            workspace
 5463                .update(&mut cx, |workspace, cx| {
 5464                    workspace::tasks::schedule_resolved_task(
 5465                        workspace,
 5466                        task_source_kind,
 5467                        resolved_task,
 5468                        false,
 5469                        cx,
 5470                    );
 5471                })
 5472                .ok()
 5473        })
 5474        .detach();
 5475    }
 5476
 5477    fn find_closest_task(
 5478        &mut self,
 5479        cx: &mut Context<Self>,
 5480    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5481        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5482
 5483        let ((buffer_id, row), tasks) = self
 5484            .tasks
 5485            .iter()
 5486            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5487
 5488        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5489        let tasks = Arc::new(tasks.to_owned());
 5490        Some((buffer, *row, tasks))
 5491    }
 5492
 5493    fn find_enclosing_node_task(
 5494        &mut self,
 5495        cx: &mut Context<Self>,
 5496    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5497        let snapshot = self.buffer.read(cx).snapshot(cx);
 5498        let offset = self.selections.newest::<usize>(cx).head();
 5499        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5500        let buffer_id = excerpt.buffer().remote_id();
 5501
 5502        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5503        let mut cursor = layer.node().walk();
 5504
 5505        while cursor.goto_first_child_for_byte(offset).is_some() {
 5506            if cursor.node().end_byte() == offset {
 5507                cursor.goto_next_sibling();
 5508            }
 5509        }
 5510
 5511        // Ascend to the smallest ancestor that contains the range and has a task.
 5512        loop {
 5513            let node = cursor.node();
 5514            let node_range = node.byte_range();
 5515            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5516
 5517            // Check if this node contains our offset
 5518            if node_range.start <= offset && node_range.end >= offset {
 5519                // If it contains offset, check for task
 5520                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5521                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5522                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5523                }
 5524            }
 5525
 5526            if !cursor.goto_parent() {
 5527                break;
 5528            }
 5529        }
 5530        None
 5531    }
 5532
 5533    fn render_run_indicator(
 5534        &self,
 5535        _style: &EditorStyle,
 5536        is_active: bool,
 5537        row: DisplayRow,
 5538        cx: &mut Context<Self>,
 5539    ) -> IconButton {
 5540        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5541            .shape(ui::IconButtonShape::Square)
 5542            .icon_size(IconSize::XSmall)
 5543            .icon_color(Color::Muted)
 5544            .toggle_state(is_active)
 5545            .on_click(cx.listener(move |editor, _e, window, cx| {
 5546                window.focus(&editor.focus_handle(cx));
 5547                editor.toggle_code_actions(
 5548                    &ToggleCodeActions {
 5549                        deployed_from_indicator: Some(row),
 5550                    },
 5551                    window,
 5552                    cx,
 5553                );
 5554            }))
 5555    }
 5556
 5557    pub fn context_menu_visible(&self) -> bool {
 5558        !self.previewing_inline_completion
 5559            && self
 5560                .context_menu
 5561                .borrow()
 5562                .as_ref()
 5563                .map_or(false, |menu| menu.visible())
 5564    }
 5565
 5566    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5567        self.context_menu
 5568            .borrow()
 5569            .as_ref()
 5570            .map(|menu| menu.origin())
 5571    }
 5572
 5573    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5574        px(30.)
 5575    }
 5576
 5577    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5578        if self.read_only(cx) {
 5579            cx.theme().players().read_only()
 5580        } else {
 5581            self.style.as_ref().unwrap().local_player
 5582        }
 5583    }
 5584
 5585    #[allow(clippy::too_many_arguments)]
 5586    fn render_edit_prediction_cursor_popover(
 5587        &self,
 5588        min_width: Pixels,
 5589        max_width: Pixels,
 5590        cursor_point: Point,
 5591        style: &EditorStyle,
 5592        accept_keystroke: &gpui::Keystroke,
 5593        window: &Window,
 5594        cx: &mut Context<Editor>,
 5595    ) -> Option<AnyElement> {
 5596        let provider = self.edit_prediction_provider.as_ref()?;
 5597
 5598        if provider.provider.needs_terms_acceptance(cx) {
 5599            return Some(
 5600                h_flex()
 5601                    .min_w(min_width)
 5602                    .flex_1()
 5603                    .px_2()
 5604                    .py_1()
 5605                    .gap_3()
 5606                    .elevation_2(cx)
 5607                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5608                    .id("accept-terms")
 5609                    .cursor_pointer()
 5610                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5611                    .on_click(cx.listener(|this, _event, window, cx| {
 5612                        cx.stop_propagation();
 5613                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5614                        window.dispatch_action(
 5615                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5616                            cx,
 5617                        );
 5618                    }))
 5619                    .child(
 5620                        h_flex()
 5621                            .flex_1()
 5622                            .gap_2()
 5623                            .child(Icon::new(IconName::ZedPredict))
 5624                            .child(Label::new("Accept Terms of Service"))
 5625                            .child(div().w_full())
 5626                            .child(
 5627                                Icon::new(IconName::ArrowUpRight)
 5628                                    .color(Color::Muted)
 5629                                    .size(IconSize::Small),
 5630                            )
 5631                            .into_any_element(),
 5632                    )
 5633                    .into_any(),
 5634            );
 5635        }
 5636
 5637        let is_refreshing = provider.provider.is_refreshing(cx);
 5638
 5639        fn pending_completion_container() -> Div {
 5640            h_flex()
 5641                .h_full()
 5642                .flex_1()
 5643                .gap_2()
 5644                .child(Icon::new(IconName::ZedPredict))
 5645        }
 5646
 5647        let completion = match &self.active_inline_completion {
 5648            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5649                completion,
 5650                cursor_point,
 5651                style,
 5652                window,
 5653                cx,
 5654            )?,
 5655
 5656            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5657                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5658                    stale_completion,
 5659                    cursor_point,
 5660                    style,
 5661                    window,
 5662                    cx,
 5663                )?,
 5664
 5665                None => {
 5666                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5667                }
 5668            },
 5669
 5670            None => pending_completion_container().child(Label::new("No Prediction")),
 5671        };
 5672
 5673        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5674        let completion = completion.font(buffer_font.clone());
 5675
 5676        let completion = if is_refreshing {
 5677            completion
 5678                .with_animation(
 5679                    "loading-completion",
 5680                    Animation::new(Duration::from_secs(2))
 5681                        .repeat()
 5682                        .with_easing(pulsating_between(0.4, 0.8)),
 5683                    |label, delta| label.opacity(delta),
 5684                )
 5685                .into_any_element()
 5686        } else {
 5687            completion.into_any_element()
 5688        };
 5689
 5690        let has_completion = self.active_inline_completion.is_some();
 5691
 5692        Some(
 5693            h_flex()
 5694                .min_w(min_width)
 5695                .max_w(max_width)
 5696                .flex_1()
 5697                .px_2()
 5698                .py_1()
 5699                .elevation_2(cx)
 5700                .child(completion)
 5701                .child(ui::Divider::vertical())
 5702                .child(
 5703                    h_flex()
 5704                        .h_full()
 5705                        .gap_1()
 5706                        .pl_2()
 5707                        .child(h_flex().font(buffer_font.clone()).gap_1().children(
 5708                            ui::render_modifiers(
 5709                                &accept_keystroke.modifiers,
 5710                                PlatformStyle::platform(),
 5711                                Some(if !has_completion {
 5712                                    Color::Muted
 5713                                } else {
 5714                                    Color::Default
 5715                                }),
 5716                                None,
 5717                                true,
 5718                            ),
 5719                        ))
 5720                        .child(Label::new("Preview").into_any_element())
 5721                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5722                )
 5723                .into_any(),
 5724        )
 5725    }
 5726
 5727    fn render_edit_prediction_cursor_popover_preview(
 5728        &self,
 5729        completion: &InlineCompletionState,
 5730        cursor_point: Point,
 5731        style: &EditorStyle,
 5732        window: &Window,
 5733        cx: &mut Context<Editor>,
 5734    ) -> Option<Div> {
 5735        use text::ToPoint as _;
 5736
 5737        fn render_relative_row_jump(
 5738            prefix: impl Into<String>,
 5739            current_row: u32,
 5740            target_row: u32,
 5741        ) -> Div {
 5742            let (row_diff, arrow) = if target_row < current_row {
 5743                (current_row - target_row, IconName::ArrowUp)
 5744            } else {
 5745                (target_row - current_row, IconName::ArrowDown)
 5746            };
 5747
 5748            h_flex()
 5749                .child(
 5750                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5751                        .color(Color::Muted)
 5752                        .size(LabelSize::Small),
 5753                )
 5754                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5755        }
 5756
 5757        match &completion.completion {
 5758            InlineCompletion::Edit {
 5759                edits,
 5760                edit_preview,
 5761                snapshot,
 5762                display_mode: _,
 5763            } => {
 5764                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5765
 5766                let highlighted_edits = crate::inline_completion_edit_text(
 5767                    &snapshot,
 5768                    &edits,
 5769                    edit_preview.as_ref()?,
 5770                    true,
 5771                    cx,
 5772                );
 5773
 5774                let len_total = highlighted_edits.text.len();
 5775                let first_line = &highlighted_edits.text
 5776                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5777                let first_line_len = first_line.len();
 5778
 5779                let first_highlight_start = highlighted_edits
 5780                    .highlights
 5781                    .first()
 5782                    .map_or(0, |(range, _)| range.start);
 5783                let drop_prefix_len = first_line
 5784                    .char_indices()
 5785                    .find(|(_, c)| !c.is_whitespace())
 5786                    .map_or(first_highlight_start, |(ix, _)| {
 5787                        ix.min(first_highlight_start)
 5788                    });
 5789
 5790                let preview_text = &first_line[drop_prefix_len..];
 5791                let preview_len = preview_text.len();
 5792                let highlights = highlighted_edits
 5793                    .highlights
 5794                    .into_iter()
 5795                    .take_until(|(range, _)| range.start > first_line_len)
 5796                    .map(|(range, style)| {
 5797                        (
 5798                            range.start - drop_prefix_len
 5799                                ..(range.end - drop_prefix_len).min(preview_len),
 5800                            style,
 5801                        )
 5802                    });
 5803
 5804                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5805                    .with_highlights(&style.text, highlights);
 5806
 5807                let preview = h_flex()
 5808                    .gap_1()
 5809                    .min_w_16()
 5810                    .child(styled_text)
 5811                    .when(len_total > first_line_len, |parent| parent.child(""));
 5812
 5813                let left = if first_edit_row != cursor_point.row {
 5814                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5815                        .into_any_element()
 5816                } else {
 5817                    Icon::new(IconName::ZedPredict).into_any_element()
 5818                };
 5819
 5820                Some(
 5821                    h_flex()
 5822                        .h_full()
 5823                        .flex_1()
 5824                        .gap_2()
 5825                        .pr_1()
 5826                        .overflow_x_hidden()
 5827                        .child(left)
 5828                        .child(preview),
 5829                )
 5830            }
 5831
 5832            InlineCompletion::Move {
 5833                target,
 5834                range_around_target,
 5835                snapshot,
 5836            } => {
 5837                let highlighted_text = snapshot.highlighted_text_for_range(
 5838                    range_around_target.clone(),
 5839                    None,
 5840                    &style.syntax,
 5841                );
 5842                let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
 5843                    "Jump ",
 5844                    cursor_point.row,
 5845                    target.text_anchor.to_point(&snapshot).row,
 5846                ));
 5847
 5848                if highlighted_text.text.is_empty() {
 5849                    return Some(base);
 5850                }
 5851
 5852                let cursor_color = self.current_user_player_color(cx).cursor;
 5853
 5854                let start_point = range_around_target.start.to_point(&snapshot);
 5855                let end_point = range_around_target.end.to_point(&snapshot);
 5856                let target_point = target.text_anchor.to_point(&snapshot);
 5857
 5858                let styled_text = highlighted_text.to_styled_text(&style.text);
 5859                let text_len = highlighted_text.text.len();
 5860
 5861                let cursor_relative_position = window
 5862                    .text_system()
 5863                    .layout_line(
 5864                        highlighted_text.text,
 5865                        style.text.font_size.to_pixels(window.rem_size()),
 5866                        // We don't need to include highlights
 5867                        // because we are only using this for the cursor position
 5868                        &[TextRun {
 5869                            len: text_len,
 5870                            font: style.text.font(),
 5871                            color: style.text.color,
 5872                            background_color: None,
 5873                            underline: None,
 5874                            strikethrough: None,
 5875                        }],
 5876                    )
 5877                    .log_err()
 5878                    .map(|line| {
 5879                        line.x_for_index(
 5880                            target_point.column.saturating_sub(start_point.column) as usize
 5881                        )
 5882                    });
 5883
 5884                let fade_before = start_point.column > 0;
 5885                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5886
 5887                let background = cx.theme().colors().elevated_surface_background;
 5888
 5889                let preview = h_flex()
 5890                    .relative()
 5891                    .child(styled_text)
 5892                    .when(fade_before, |parent| {
 5893                        parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
 5894                            linear_gradient(
 5895                                90.,
 5896                                linear_color_stop(background, 0.),
 5897                                linear_color_stop(background.opacity(0.), 1.),
 5898                            ),
 5899                        ))
 5900                    })
 5901                    .when(fade_after, |parent| {
 5902                        parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
 5903                            linear_gradient(
 5904                                -90.,
 5905                                linear_color_stop(background, 0.),
 5906                                linear_color_stop(background.opacity(0.), 1.),
 5907                            ),
 5908                        ))
 5909                    })
 5910                    .when_some(cursor_relative_position, |parent, position| {
 5911                        parent.child(
 5912                            div()
 5913                                .w(px(2.))
 5914                                .h_full()
 5915                                .bg(cursor_color)
 5916                                .absolute()
 5917                                .top_0()
 5918                                .left(position),
 5919                        )
 5920                    });
 5921
 5922                Some(base.child(preview))
 5923            }
 5924        }
 5925    }
 5926
 5927    fn render_context_menu(
 5928        &self,
 5929        style: &EditorStyle,
 5930        max_height_in_lines: u32,
 5931        y_flipped: bool,
 5932        window: &mut Window,
 5933        cx: &mut Context<Editor>,
 5934    ) -> Option<AnyElement> {
 5935        let menu = self.context_menu.borrow();
 5936        let menu = menu.as_ref()?;
 5937        if !menu.visible() {
 5938            return None;
 5939        };
 5940        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5941    }
 5942
 5943    fn render_context_menu_aside(
 5944        &self,
 5945        style: &EditorStyle,
 5946        max_size: Size<Pixels>,
 5947        cx: &mut Context<Editor>,
 5948    ) -> Option<AnyElement> {
 5949        self.context_menu.borrow().as_ref().and_then(|menu| {
 5950            if menu.visible() {
 5951                menu.render_aside(
 5952                    style,
 5953                    max_size,
 5954                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5955                    cx,
 5956                )
 5957            } else {
 5958                None
 5959            }
 5960        })
 5961    }
 5962
 5963    fn hide_context_menu(
 5964        &mut self,
 5965        window: &mut Window,
 5966        cx: &mut Context<Self>,
 5967    ) -> Option<CodeContextMenu> {
 5968        cx.notify();
 5969        self.completion_tasks.clear();
 5970        let context_menu = self.context_menu.borrow_mut().take();
 5971        self.stale_inline_completion_in_menu.take();
 5972        self.update_visible_inline_completion(window, cx);
 5973        context_menu
 5974    }
 5975
 5976    fn show_snippet_choices(
 5977        &mut self,
 5978        choices: &Vec<String>,
 5979        selection: Range<Anchor>,
 5980        cx: &mut Context<Self>,
 5981    ) {
 5982        if selection.start.buffer_id.is_none() {
 5983            return;
 5984        }
 5985        let buffer_id = selection.start.buffer_id.unwrap();
 5986        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5987        let id = post_inc(&mut self.next_completion_id);
 5988
 5989        if let Some(buffer) = buffer {
 5990            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5991                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5992            ));
 5993        }
 5994    }
 5995
 5996    pub fn insert_snippet(
 5997        &mut self,
 5998        insertion_ranges: &[Range<usize>],
 5999        snippet: Snippet,
 6000        window: &mut Window,
 6001        cx: &mut Context<Self>,
 6002    ) -> Result<()> {
 6003        struct Tabstop<T> {
 6004            is_end_tabstop: bool,
 6005            ranges: Vec<Range<T>>,
 6006            choices: Option<Vec<String>>,
 6007        }
 6008
 6009        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6010            let snippet_text: Arc<str> = snippet.text.clone().into();
 6011            buffer.edit(
 6012                insertion_ranges
 6013                    .iter()
 6014                    .cloned()
 6015                    .map(|range| (range, snippet_text.clone())),
 6016                Some(AutoindentMode::EachLine),
 6017                cx,
 6018            );
 6019
 6020            let snapshot = &*buffer.read(cx);
 6021            let snippet = &snippet;
 6022            snippet
 6023                .tabstops
 6024                .iter()
 6025                .map(|tabstop| {
 6026                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6027                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6028                    });
 6029                    let mut tabstop_ranges = tabstop
 6030                        .ranges
 6031                        .iter()
 6032                        .flat_map(|tabstop_range| {
 6033                            let mut delta = 0_isize;
 6034                            insertion_ranges.iter().map(move |insertion_range| {
 6035                                let insertion_start = insertion_range.start as isize + delta;
 6036                                delta +=
 6037                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6038
 6039                                let start = ((insertion_start + tabstop_range.start) as usize)
 6040                                    .min(snapshot.len());
 6041                                let end = ((insertion_start + tabstop_range.end) as usize)
 6042                                    .min(snapshot.len());
 6043                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6044                            })
 6045                        })
 6046                        .collect::<Vec<_>>();
 6047                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6048
 6049                    Tabstop {
 6050                        is_end_tabstop,
 6051                        ranges: tabstop_ranges,
 6052                        choices: tabstop.choices.clone(),
 6053                    }
 6054                })
 6055                .collect::<Vec<_>>()
 6056        });
 6057        if let Some(tabstop) = tabstops.first() {
 6058            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6059                s.select_ranges(tabstop.ranges.iter().cloned());
 6060            });
 6061
 6062            if let Some(choices) = &tabstop.choices {
 6063                if let Some(selection) = tabstop.ranges.first() {
 6064                    self.show_snippet_choices(choices, selection.clone(), cx)
 6065                }
 6066            }
 6067
 6068            // If we're already at the last tabstop and it's at the end of the snippet,
 6069            // we're done, we don't need to keep the state around.
 6070            if !tabstop.is_end_tabstop {
 6071                let choices = tabstops
 6072                    .iter()
 6073                    .map(|tabstop| tabstop.choices.clone())
 6074                    .collect();
 6075
 6076                let ranges = tabstops
 6077                    .into_iter()
 6078                    .map(|tabstop| tabstop.ranges)
 6079                    .collect::<Vec<_>>();
 6080
 6081                self.snippet_stack.push(SnippetState {
 6082                    active_index: 0,
 6083                    ranges,
 6084                    choices,
 6085                });
 6086            }
 6087
 6088            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6089            if self.autoclose_regions.is_empty() {
 6090                let snapshot = self.buffer.read(cx).snapshot(cx);
 6091                for selection in &mut self.selections.all::<Point>(cx) {
 6092                    let selection_head = selection.head();
 6093                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6094                        continue;
 6095                    };
 6096
 6097                    let mut bracket_pair = None;
 6098                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6099                    let prev_chars = snapshot
 6100                        .reversed_chars_at(selection_head)
 6101                        .collect::<String>();
 6102                    for (pair, enabled) in scope.brackets() {
 6103                        if enabled
 6104                            && pair.close
 6105                            && prev_chars.starts_with(pair.start.as_str())
 6106                            && next_chars.starts_with(pair.end.as_str())
 6107                        {
 6108                            bracket_pair = Some(pair.clone());
 6109                            break;
 6110                        }
 6111                    }
 6112                    if let Some(pair) = bracket_pair {
 6113                        let start = snapshot.anchor_after(selection_head);
 6114                        let end = snapshot.anchor_after(selection_head);
 6115                        self.autoclose_regions.push(AutocloseRegion {
 6116                            selection_id: selection.id,
 6117                            range: start..end,
 6118                            pair,
 6119                        });
 6120                    }
 6121                }
 6122            }
 6123        }
 6124        Ok(())
 6125    }
 6126
 6127    pub fn move_to_next_snippet_tabstop(
 6128        &mut self,
 6129        window: &mut Window,
 6130        cx: &mut Context<Self>,
 6131    ) -> bool {
 6132        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6133    }
 6134
 6135    pub fn move_to_prev_snippet_tabstop(
 6136        &mut self,
 6137        window: &mut Window,
 6138        cx: &mut Context<Self>,
 6139    ) -> bool {
 6140        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6141    }
 6142
 6143    pub fn move_to_snippet_tabstop(
 6144        &mut self,
 6145        bias: Bias,
 6146        window: &mut Window,
 6147        cx: &mut Context<Self>,
 6148    ) -> bool {
 6149        if let Some(mut snippet) = self.snippet_stack.pop() {
 6150            match bias {
 6151                Bias::Left => {
 6152                    if snippet.active_index > 0 {
 6153                        snippet.active_index -= 1;
 6154                    } else {
 6155                        self.snippet_stack.push(snippet);
 6156                        return false;
 6157                    }
 6158                }
 6159                Bias::Right => {
 6160                    if snippet.active_index + 1 < snippet.ranges.len() {
 6161                        snippet.active_index += 1;
 6162                    } else {
 6163                        self.snippet_stack.push(snippet);
 6164                        return false;
 6165                    }
 6166                }
 6167            }
 6168            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6169                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6170                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6171                });
 6172
 6173                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6174                    if let Some(selection) = current_ranges.first() {
 6175                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6176                    }
 6177                }
 6178
 6179                // If snippet state is not at the last tabstop, push it back on the stack
 6180                if snippet.active_index + 1 < snippet.ranges.len() {
 6181                    self.snippet_stack.push(snippet);
 6182                }
 6183                return true;
 6184            }
 6185        }
 6186
 6187        false
 6188    }
 6189
 6190    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6191        self.transact(window, cx, |this, window, cx| {
 6192            this.select_all(&SelectAll, window, cx);
 6193            this.insert("", window, cx);
 6194        });
 6195    }
 6196
 6197    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6198        self.transact(window, cx, |this, window, cx| {
 6199            this.select_autoclose_pair(window, cx);
 6200            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6201            if !this.linked_edit_ranges.is_empty() {
 6202                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6203                let snapshot = this.buffer.read(cx).snapshot(cx);
 6204
 6205                for selection in selections.iter() {
 6206                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6207                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6208                    if selection_start.buffer_id != selection_end.buffer_id {
 6209                        continue;
 6210                    }
 6211                    if let Some(ranges) =
 6212                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6213                    {
 6214                        for (buffer, entries) in ranges {
 6215                            linked_ranges.entry(buffer).or_default().extend(entries);
 6216                        }
 6217                    }
 6218                }
 6219            }
 6220
 6221            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6222            if !this.selections.line_mode {
 6223                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6224                for selection in &mut selections {
 6225                    if selection.is_empty() {
 6226                        let old_head = selection.head();
 6227                        let mut new_head =
 6228                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6229                                .to_point(&display_map);
 6230                        if let Some((buffer, line_buffer_range)) = display_map
 6231                            .buffer_snapshot
 6232                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6233                        {
 6234                            let indent_size =
 6235                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6236                            let indent_len = match indent_size.kind {
 6237                                IndentKind::Space => {
 6238                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6239                                }
 6240                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6241                            };
 6242                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6243                                let indent_len = indent_len.get();
 6244                                new_head = cmp::min(
 6245                                    new_head,
 6246                                    MultiBufferPoint::new(
 6247                                        old_head.row,
 6248                                        ((old_head.column - 1) / indent_len) * indent_len,
 6249                                    ),
 6250                                );
 6251                            }
 6252                        }
 6253
 6254                        selection.set_head(new_head, SelectionGoal::None);
 6255                    }
 6256                }
 6257            }
 6258
 6259            this.signature_help_state.set_backspace_pressed(true);
 6260            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6261                s.select(selections)
 6262            });
 6263            this.insert("", window, cx);
 6264            let empty_str: Arc<str> = Arc::from("");
 6265            for (buffer, edits) in linked_ranges {
 6266                let snapshot = buffer.read(cx).snapshot();
 6267                use text::ToPoint as TP;
 6268
 6269                let edits = edits
 6270                    .into_iter()
 6271                    .map(|range| {
 6272                        let end_point = TP::to_point(&range.end, &snapshot);
 6273                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6274
 6275                        if end_point == start_point {
 6276                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6277                                .saturating_sub(1);
 6278                            start_point =
 6279                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6280                        };
 6281
 6282                        (start_point..end_point, empty_str.clone())
 6283                    })
 6284                    .sorted_by_key(|(range, _)| range.start)
 6285                    .collect::<Vec<_>>();
 6286                buffer.update(cx, |this, cx| {
 6287                    this.edit(edits, None, cx);
 6288                })
 6289            }
 6290            this.refresh_inline_completion(true, false, window, cx);
 6291            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6292        });
 6293    }
 6294
 6295    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6296        self.transact(window, cx, |this, window, cx| {
 6297            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6298                let line_mode = s.line_mode;
 6299                s.move_with(|map, selection| {
 6300                    if selection.is_empty() && !line_mode {
 6301                        let cursor = movement::right(map, selection.head());
 6302                        selection.end = cursor;
 6303                        selection.reversed = true;
 6304                        selection.goal = SelectionGoal::None;
 6305                    }
 6306                })
 6307            });
 6308            this.insert("", window, cx);
 6309            this.refresh_inline_completion(true, false, window, cx);
 6310        });
 6311    }
 6312
 6313    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6314        if self.move_to_prev_snippet_tabstop(window, cx) {
 6315            return;
 6316        }
 6317
 6318        self.outdent(&Outdent, window, cx);
 6319    }
 6320
 6321    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6322        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6323            return;
 6324        }
 6325
 6326        let mut selections = self.selections.all_adjusted(cx);
 6327        let buffer = self.buffer.read(cx);
 6328        let snapshot = buffer.snapshot(cx);
 6329        let rows_iter = selections.iter().map(|s| s.head().row);
 6330        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6331
 6332        let mut edits = Vec::new();
 6333        let mut prev_edited_row = 0;
 6334        let mut row_delta = 0;
 6335        for selection in &mut selections {
 6336            if selection.start.row != prev_edited_row {
 6337                row_delta = 0;
 6338            }
 6339            prev_edited_row = selection.end.row;
 6340
 6341            // If the selection is non-empty, then increase the indentation of the selected lines.
 6342            if !selection.is_empty() {
 6343                row_delta =
 6344                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6345                continue;
 6346            }
 6347
 6348            // If the selection is empty and the cursor is in the leading whitespace before the
 6349            // suggested indentation, then auto-indent the line.
 6350            let cursor = selection.head();
 6351            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6352            if let Some(suggested_indent) =
 6353                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6354            {
 6355                if cursor.column < suggested_indent.len
 6356                    && cursor.column <= current_indent.len
 6357                    && current_indent.len <= suggested_indent.len
 6358                {
 6359                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6360                    selection.end = selection.start;
 6361                    if row_delta == 0 {
 6362                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6363                            cursor.row,
 6364                            current_indent,
 6365                            suggested_indent,
 6366                        ));
 6367                        row_delta = suggested_indent.len - current_indent.len;
 6368                    }
 6369                    continue;
 6370                }
 6371            }
 6372
 6373            // Otherwise, insert a hard or soft tab.
 6374            let settings = buffer.settings_at(cursor, cx);
 6375            let tab_size = if settings.hard_tabs {
 6376                IndentSize::tab()
 6377            } else {
 6378                let tab_size = settings.tab_size.get();
 6379                let char_column = snapshot
 6380                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6381                    .flat_map(str::chars)
 6382                    .count()
 6383                    + row_delta as usize;
 6384                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6385                IndentSize::spaces(chars_to_next_tab_stop)
 6386            };
 6387            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6388            selection.end = selection.start;
 6389            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6390            row_delta += tab_size.len;
 6391        }
 6392
 6393        self.transact(window, cx, |this, window, cx| {
 6394            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6396                s.select(selections)
 6397            });
 6398            this.refresh_inline_completion(true, false, window, cx);
 6399        });
 6400    }
 6401
 6402    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6403        if self.read_only(cx) {
 6404            return;
 6405        }
 6406        let mut selections = self.selections.all::<Point>(cx);
 6407        let mut prev_edited_row = 0;
 6408        let mut row_delta = 0;
 6409        let mut edits = Vec::new();
 6410        let buffer = self.buffer.read(cx);
 6411        let snapshot = buffer.snapshot(cx);
 6412        for selection in &mut selections {
 6413            if selection.start.row != prev_edited_row {
 6414                row_delta = 0;
 6415            }
 6416            prev_edited_row = selection.end.row;
 6417
 6418            row_delta =
 6419                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6420        }
 6421
 6422        self.transact(window, cx, |this, window, cx| {
 6423            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6424            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6425                s.select(selections)
 6426            });
 6427        });
 6428    }
 6429
 6430    fn indent_selection(
 6431        buffer: &MultiBuffer,
 6432        snapshot: &MultiBufferSnapshot,
 6433        selection: &mut Selection<Point>,
 6434        edits: &mut Vec<(Range<Point>, String)>,
 6435        delta_for_start_row: u32,
 6436        cx: &App,
 6437    ) -> u32 {
 6438        let settings = buffer.settings_at(selection.start, cx);
 6439        let tab_size = settings.tab_size.get();
 6440        let indent_kind = if settings.hard_tabs {
 6441            IndentKind::Tab
 6442        } else {
 6443            IndentKind::Space
 6444        };
 6445        let mut start_row = selection.start.row;
 6446        let mut end_row = selection.end.row + 1;
 6447
 6448        // If a selection ends at the beginning of a line, don't indent
 6449        // that last line.
 6450        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6451            end_row -= 1;
 6452        }
 6453
 6454        // Avoid re-indenting a row that has already been indented by a
 6455        // previous selection, but still update this selection's column
 6456        // to reflect that indentation.
 6457        if delta_for_start_row > 0 {
 6458            start_row += 1;
 6459            selection.start.column += delta_for_start_row;
 6460            if selection.end.row == selection.start.row {
 6461                selection.end.column += delta_for_start_row;
 6462            }
 6463        }
 6464
 6465        let mut delta_for_end_row = 0;
 6466        let has_multiple_rows = start_row + 1 != end_row;
 6467        for row in start_row..end_row {
 6468            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6469            let indent_delta = match (current_indent.kind, indent_kind) {
 6470                (IndentKind::Space, IndentKind::Space) => {
 6471                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6472                    IndentSize::spaces(columns_to_next_tab_stop)
 6473                }
 6474                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6475                (_, IndentKind::Tab) => IndentSize::tab(),
 6476            };
 6477
 6478            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6479                0
 6480            } else {
 6481                selection.start.column
 6482            };
 6483            let row_start = Point::new(row, start);
 6484            edits.push((
 6485                row_start..row_start,
 6486                indent_delta.chars().collect::<String>(),
 6487            ));
 6488
 6489            // Update this selection's endpoints to reflect the indentation.
 6490            if row == selection.start.row {
 6491                selection.start.column += indent_delta.len;
 6492            }
 6493            if row == selection.end.row {
 6494                selection.end.column += indent_delta.len;
 6495                delta_for_end_row = indent_delta.len;
 6496            }
 6497        }
 6498
 6499        if selection.start.row == selection.end.row {
 6500            delta_for_start_row + delta_for_end_row
 6501        } else {
 6502            delta_for_end_row
 6503        }
 6504    }
 6505
 6506    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6507        if self.read_only(cx) {
 6508            return;
 6509        }
 6510        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6511        let selections = self.selections.all::<Point>(cx);
 6512        let mut deletion_ranges = Vec::new();
 6513        let mut last_outdent = None;
 6514        {
 6515            let buffer = self.buffer.read(cx);
 6516            let snapshot = buffer.snapshot(cx);
 6517            for selection in &selections {
 6518                let settings = buffer.settings_at(selection.start, cx);
 6519                let tab_size = settings.tab_size.get();
 6520                let mut rows = selection.spanned_rows(false, &display_map);
 6521
 6522                // Avoid re-outdenting a row that has already been outdented by a
 6523                // previous selection.
 6524                if let Some(last_row) = last_outdent {
 6525                    if last_row == rows.start {
 6526                        rows.start = rows.start.next_row();
 6527                    }
 6528                }
 6529                let has_multiple_rows = rows.len() > 1;
 6530                for row in rows.iter_rows() {
 6531                    let indent_size = snapshot.indent_size_for_line(row);
 6532                    if indent_size.len > 0 {
 6533                        let deletion_len = match indent_size.kind {
 6534                            IndentKind::Space => {
 6535                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6536                                if columns_to_prev_tab_stop == 0 {
 6537                                    tab_size
 6538                                } else {
 6539                                    columns_to_prev_tab_stop
 6540                                }
 6541                            }
 6542                            IndentKind::Tab => 1,
 6543                        };
 6544                        let start = if has_multiple_rows
 6545                            || deletion_len > selection.start.column
 6546                            || indent_size.len < selection.start.column
 6547                        {
 6548                            0
 6549                        } else {
 6550                            selection.start.column - deletion_len
 6551                        };
 6552                        deletion_ranges.push(
 6553                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6554                        );
 6555                        last_outdent = Some(row);
 6556                    }
 6557                }
 6558            }
 6559        }
 6560
 6561        self.transact(window, cx, |this, window, cx| {
 6562            this.buffer.update(cx, |buffer, cx| {
 6563                let empty_str: Arc<str> = Arc::default();
 6564                buffer.edit(
 6565                    deletion_ranges
 6566                        .into_iter()
 6567                        .map(|range| (range, empty_str.clone())),
 6568                    None,
 6569                    cx,
 6570                );
 6571            });
 6572            let selections = this.selections.all::<usize>(cx);
 6573            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6574                s.select(selections)
 6575            });
 6576        });
 6577    }
 6578
 6579    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6580        if self.read_only(cx) {
 6581            return;
 6582        }
 6583        let selections = self
 6584            .selections
 6585            .all::<usize>(cx)
 6586            .into_iter()
 6587            .map(|s| s.range());
 6588
 6589        self.transact(window, cx, |this, window, cx| {
 6590            this.buffer.update(cx, |buffer, cx| {
 6591                buffer.autoindent_ranges(selections, cx);
 6592            });
 6593            let selections = this.selections.all::<usize>(cx);
 6594            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6595                s.select(selections)
 6596            });
 6597        });
 6598    }
 6599
 6600    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6601        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6602        let selections = self.selections.all::<Point>(cx);
 6603
 6604        let mut new_cursors = Vec::new();
 6605        let mut edit_ranges = Vec::new();
 6606        let mut selections = selections.iter().peekable();
 6607        while let Some(selection) = selections.next() {
 6608            let mut rows = selection.spanned_rows(false, &display_map);
 6609            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6610
 6611            // Accumulate contiguous regions of rows that we want to delete.
 6612            while let Some(next_selection) = selections.peek() {
 6613                let next_rows = next_selection.spanned_rows(false, &display_map);
 6614                if next_rows.start <= rows.end {
 6615                    rows.end = next_rows.end;
 6616                    selections.next().unwrap();
 6617                } else {
 6618                    break;
 6619                }
 6620            }
 6621
 6622            let buffer = &display_map.buffer_snapshot;
 6623            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6624            let edit_end;
 6625            let cursor_buffer_row;
 6626            if buffer.max_point().row >= rows.end.0 {
 6627                // If there's a line after the range, delete the \n from the end of the row range
 6628                // and position the cursor on the next line.
 6629                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6630                cursor_buffer_row = rows.end;
 6631            } else {
 6632                // If there isn't a line after the range, delete the \n from the line before the
 6633                // start of the row range and position the cursor there.
 6634                edit_start = edit_start.saturating_sub(1);
 6635                edit_end = buffer.len();
 6636                cursor_buffer_row = rows.start.previous_row();
 6637            }
 6638
 6639            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6640            *cursor.column_mut() =
 6641                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6642
 6643            new_cursors.push((
 6644                selection.id,
 6645                buffer.anchor_after(cursor.to_point(&display_map)),
 6646            ));
 6647            edit_ranges.push(edit_start..edit_end);
 6648        }
 6649
 6650        self.transact(window, cx, |this, window, cx| {
 6651            let buffer = this.buffer.update(cx, |buffer, cx| {
 6652                let empty_str: Arc<str> = Arc::default();
 6653                buffer.edit(
 6654                    edit_ranges
 6655                        .into_iter()
 6656                        .map(|range| (range, empty_str.clone())),
 6657                    None,
 6658                    cx,
 6659                );
 6660                buffer.snapshot(cx)
 6661            });
 6662            let new_selections = new_cursors
 6663                .into_iter()
 6664                .map(|(id, cursor)| {
 6665                    let cursor = cursor.to_point(&buffer);
 6666                    Selection {
 6667                        id,
 6668                        start: cursor,
 6669                        end: cursor,
 6670                        reversed: false,
 6671                        goal: SelectionGoal::None,
 6672                    }
 6673                })
 6674                .collect();
 6675
 6676            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6677                s.select(new_selections);
 6678            });
 6679        });
 6680    }
 6681
 6682    pub fn join_lines_impl(
 6683        &mut self,
 6684        insert_whitespace: bool,
 6685        window: &mut Window,
 6686        cx: &mut Context<Self>,
 6687    ) {
 6688        if self.read_only(cx) {
 6689            return;
 6690        }
 6691        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6692        for selection in self.selections.all::<Point>(cx) {
 6693            let start = MultiBufferRow(selection.start.row);
 6694            // Treat single line selections as if they include the next line. Otherwise this action
 6695            // would do nothing for single line selections individual cursors.
 6696            let end = if selection.start.row == selection.end.row {
 6697                MultiBufferRow(selection.start.row + 1)
 6698            } else {
 6699                MultiBufferRow(selection.end.row)
 6700            };
 6701
 6702            if let Some(last_row_range) = row_ranges.last_mut() {
 6703                if start <= last_row_range.end {
 6704                    last_row_range.end = end;
 6705                    continue;
 6706                }
 6707            }
 6708            row_ranges.push(start..end);
 6709        }
 6710
 6711        let snapshot = self.buffer.read(cx).snapshot(cx);
 6712        let mut cursor_positions = Vec::new();
 6713        for row_range in &row_ranges {
 6714            let anchor = snapshot.anchor_before(Point::new(
 6715                row_range.end.previous_row().0,
 6716                snapshot.line_len(row_range.end.previous_row()),
 6717            ));
 6718            cursor_positions.push(anchor..anchor);
 6719        }
 6720
 6721        self.transact(window, cx, |this, window, cx| {
 6722            for row_range in row_ranges.into_iter().rev() {
 6723                for row in row_range.iter_rows().rev() {
 6724                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6725                    let next_line_row = row.next_row();
 6726                    let indent = snapshot.indent_size_for_line(next_line_row);
 6727                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6728
 6729                    let replace =
 6730                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6731                            " "
 6732                        } else {
 6733                            ""
 6734                        };
 6735
 6736                    this.buffer.update(cx, |buffer, cx| {
 6737                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6738                    });
 6739                }
 6740            }
 6741
 6742            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6743                s.select_anchor_ranges(cursor_positions)
 6744            });
 6745        });
 6746    }
 6747
 6748    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6749        self.join_lines_impl(true, window, cx);
 6750    }
 6751
 6752    pub fn sort_lines_case_sensitive(
 6753        &mut self,
 6754        _: &SortLinesCaseSensitive,
 6755        window: &mut Window,
 6756        cx: &mut Context<Self>,
 6757    ) {
 6758        self.manipulate_lines(window, cx, |lines| lines.sort())
 6759    }
 6760
 6761    pub fn sort_lines_case_insensitive(
 6762        &mut self,
 6763        _: &SortLinesCaseInsensitive,
 6764        window: &mut Window,
 6765        cx: &mut Context<Self>,
 6766    ) {
 6767        self.manipulate_lines(window, cx, |lines| {
 6768            lines.sort_by_key(|line| line.to_lowercase())
 6769        })
 6770    }
 6771
 6772    pub fn unique_lines_case_insensitive(
 6773        &mut self,
 6774        _: &UniqueLinesCaseInsensitive,
 6775        window: &mut Window,
 6776        cx: &mut Context<Self>,
 6777    ) {
 6778        self.manipulate_lines(window, cx, |lines| {
 6779            let mut seen = HashSet::default();
 6780            lines.retain(|line| seen.insert(line.to_lowercase()));
 6781        })
 6782    }
 6783
 6784    pub fn unique_lines_case_sensitive(
 6785        &mut self,
 6786        _: &UniqueLinesCaseSensitive,
 6787        window: &mut Window,
 6788        cx: &mut Context<Self>,
 6789    ) {
 6790        self.manipulate_lines(window, cx, |lines| {
 6791            let mut seen = HashSet::default();
 6792            lines.retain(|line| seen.insert(*line));
 6793        })
 6794    }
 6795
 6796    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6797        let mut revert_changes = HashMap::default();
 6798        let snapshot = self.snapshot(window, cx);
 6799        for hunk in snapshot
 6800            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6801        {
 6802            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6803        }
 6804        if !revert_changes.is_empty() {
 6805            self.transact(window, cx, |editor, window, cx| {
 6806                editor.revert(revert_changes, window, cx);
 6807            });
 6808        }
 6809    }
 6810
 6811    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6812        let Some(project) = self.project.clone() else {
 6813            return;
 6814        };
 6815        self.reload(project, window, cx)
 6816            .detach_and_notify_err(window, cx);
 6817    }
 6818
 6819    pub fn revert_selected_hunks(
 6820        &mut self,
 6821        _: &RevertSelectedHunks,
 6822        window: &mut Window,
 6823        cx: &mut Context<Self>,
 6824    ) {
 6825        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6826        self.revert_hunks_in_ranges(selections, window, cx);
 6827    }
 6828
 6829    fn revert_hunks_in_ranges(
 6830        &mut self,
 6831        ranges: impl Iterator<Item = Range<Point>>,
 6832        window: &mut Window,
 6833        cx: &mut Context<Editor>,
 6834    ) {
 6835        let mut revert_changes = HashMap::default();
 6836        let snapshot = self.snapshot(window, cx);
 6837        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6838            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6839        }
 6840        if !revert_changes.is_empty() {
 6841            self.transact(window, cx, |editor, window, cx| {
 6842                editor.revert(revert_changes, window, cx);
 6843            });
 6844        }
 6845    }
 6846
 6847    pub fn open_active_item_in_terminal(
 6848        &mut self,
 6849        _: &OpenInTerminal,
 6850        window: &mut Window,
 6851        cx: &mut Context<Self>,
 6852    ) {
 6853        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6854            let project_path = buffer.read(cx).project_path(cx)?;
 6855            let project = self.project.as_ref()?.read(cx);
 6856            let entry = project.entry_for_path(&project_path, cx)?;
 6857            let parent = match &entry.canonical_path {
 6858                Some(canonical_path) => canonical_path.to_path_buf(),
 6859                None => project.absolute_path(&project_path, cx)?,
 6860            }
 6861            .parent()?
 6862            .to_path_buf();
 6863            Some(parent)
 6864        }) {
 6865            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6866        }
 6867    }
 6868
 6869    pub fn prepare_revert_change(
 6870        &self,
 6871        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6872        hunk: &MultiBufferDiffHunk,
 6873        cx: &mut App,
 6874    ) -> Option<()> {
 6875        let buffer = self.buffer.read(cx);
 6876        let diff = buffer.diff_for(hunk.buffer_id)?;
 6877        let buffer = buffer.buffer(hunk.buffer_id)?;
 6878        let buffer = buffer.read(cx);
 6879        let original_text = diff
 6880            .read(cx)
 6881            .snapshot
 6882            .base_text
 6883            .as_ref()?
 6884            .as_rope()
 6885            .slice(hunk.diff_base_byte_range.clone());
 6886        let buffer_snapshot = buffer.snapshot();
 6887        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6888        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6889            probe
 6890                .0
 6891                .start
 6892                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6893                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6894        }) {
 6895            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6896            Some(())
 6897        } else {
 6898            None
 6899        }
 6900    }
 6901
 6902    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6903        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6904    }
 6905
 6906    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6907        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6908    }
 6909
 6910    fn manipulate_lines<Fn>(
 6911        &mut self,
 6912        window: &mut Window,
 6913        cx: &mut Context<Self>,
 6914        mut callback: Fn,
 6915    ) where
 6916        Fn: FnMut(&mut Vec<&str>),
 6917    {
 6918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6919        let buffer = self.buffer.read(cx).snapshot(cx);
 6920
 6921        let mut edits = Vec::new();
 6922
 6923        let selections = self.selections.all::<Point>(cx);
 6924        let mut selections = selections.iter().peekable();
 6925        let mut contiguous_row_selections = Vec::new();
 6926        let mut new_selections = Vec::new();
 6927        let mut added_lines = 0;
 6928        let mut removed_lines = 0;
 6929
 6930        while let Some(selection) = selections.next() {
 6931            let (start_row, end_row) = consume_contiguous_rows(
 6932                &mut contiguous_row_selections,
 6933                selection,
 6934                &display_map,
 6935                &mut selections,
 6936            );
 6937
 6938            let start_point = Point::new(start_row.0, 0);
 6939            let end_point = Point::new(
 6940                end_row.previous_row().0,
 6941                buffer.line_len(end_row.previous_row()),
 6942            );
 6943            let text = buffer
 6944                .text_for_range(start_point..end_point)
 6945                .collect::<String>();
 6946
 6947            let mut lines = text.split('\n').collect_vec();
 6948
 6949            let lines_before = lines.len();
 6950            callback(&mut lines);
 6951            let lines_after = lines.len();
 6952
 6953            edits.push((start_point..end_point, lines.join("\n")));
 6954
 6955            // Selections must change based on added and removed line count
 6956            let start_row =
 6957                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6958            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6959            new_selections.push(Selection {
 6960                id: selection.id,
 6961                start: start_row,
 6962                end: end_row,
 6963                goal: SelectionGoal::None,
 6964                reversed: selection.reversed,
 6965            });
 6966
 6967            if lines_after > lines_before {
 6968                added_lines += lines_after - lines_before;
 6969            } else if lines_before > lines_after {
 6970                removed_lines += lines_before - lines_after;
 6971            }
 6972        }
 6973
 6974        self.transact(window, cx, |this, window, cx| {
 6975            let buffer = this.buffer.update(cx, |buffer, cx| {
 6976                buffer.edit(edits, None, cx);
 6977                buffer.snapshot(cx)
 6978            });
 6979
 6980            // Recalculate offsets on newly edited buffer
 6981            let new_selections = new_selections
 6982                .iter()
 6983                .map(|s| {
 6984                    let start_point = Point::new(s.start.0, 0);
 6985                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6986                    Selection {
 6987                        id: s.id,
 6988                        start: buffer.point_to_offset(start_point),
 6989                        end: buffer.point_to_offset(end_point),
 6990                        goal: s.goal,
 6991                        reversed: s.reversed,
 6992                    }
 6993                })
 6994                .collect();
 6995
 6996            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6997                s.select(new_selections);
 6998            });
 6999
 7000            this.request_autoscroll(Autoscroll::fit(), cx);
 7001        });
 7002    }
 7003
 7004    pub fn convert_to_upper_case(
 7005        &mut self,
 7006        _: &ConvertToUpperCase,
 7007        window: &mut Window,
 7008        cx: &mut Context<Self>,
 7009    ) {
 7010        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7011    }
 7012
 7013    pub fn convert_to_lower_case(
 7014        &mut self,
 7015        _: &ConvertToLowerCase,
 7016        window: &mut Window,
 7017        cx: &mut Context<Self>,
 7018    ) {
 7019        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7020    }
 7021
 7022    pub fn convert_to_title_case(
 7023        &mut self,
 7024        _: &ConvertToTitleCase,
 7025        window: &mut Window,
 7026        cx: &mut Context<Self>,
 7027    ) {
 7028        self.manipulate_text(window, cx, |text| {
 7029            text.split('\n')
 7030                .map(|line| line.to_case(Case::Title))
 7031                .join("\n")
 7032        })
 7033    }
 7034
 7035    pub fn convert_to_snake_case(
 7036        &mut self,
 7037        _: &ConvertToSnakeCase,
 7038        window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7042    }
 7043
 7044    pub fn convert_to_kebab_case(
 7045        &mut self,
 7046        _: &ConvertToKebabCase,
 7047        window: &mut Window,
 7048        cx: &mut Context<Self>,
 7049    ) {
 7050        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7051    }
 7052
 7053    pub fn convert_to_upper_camel_case(
 7054        &mut self,
 7055        _: &ConvertToUpperCamelCase,
 7056        window: &mut Window,
 7057        cx: &mut Context<Self>,
 7058    ) {
 7059        self.manipulate_text(window, cx, |text| {
 7060            text.split('\n')
 7061                .map(|line| line.to_case(Case::UpperCamel))
 7062                .join("\n")
 7063        })
 7064    }
 7065
 7066    pub fn convert_to_lower_camel_case(
 7067        &mut self,
 7068        _: &ConvertToLowerCamelCase,
 7069        window: &mut Window,
 7070        cx: &mut Context<Self>,
 7071    ) {
 7072        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7073    }
 7074
 7075    pub fn convert_to_opposite_case(
 7076        &mut self,
 7077        _: &ConvertToOppositeCase,
 7078        window: &mut Window,
 7079        cx: &mut Context<Self>,
 7080    ) {
 7081        self.manipulate_text(window, cx, |text| {
 7082            text.chars()
 7083                .fold(String::with_capacity(text.len()), |mut t, c| {
 7084                    if c.is_uppercase() {
 7085                        t.extend(c.to_lowercase());
 7086                    } else {
 7087                        t.extend(c.to_uppercase());
 7088                    }
 7089                    t
 7090                })
 7091        })
 7092    }
 7093
 7094    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7095    where
 7096        Fn: FnMut(&str) -> String,
 7097    {
 7098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7099        let buffer = self.buffer.read(cx).snapshot(cx);
 7100
 7101        let mut new_selections = Vec::new();
 7102        let mut edits = Vec::new();
 7103        let mut selection_adjustment = 0i32;
 7104
 7105        for selection in self.selections.all::<usize>(cx) {
 7106            let selection_is_empty = selection.is_empty();
 7107
 7108            let (start, end) = if selection_is_empty {
 7109                let word_range = movement::surrounding_word(
 7110                    &display_map,
 7111                    selection.start.to_display_point(&display_map),
 7112                );
 7113                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7114                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7115                (start, end)
 7116            } else {
 7117                (selection.start, selection.end)
 7118            };
 7119
 7120            let text = buffer.text_for_range(start..end).collect::<String>();
 7121            let old_length = text.len() as i32;
 7122            let text = callback(&text);
 7123
 7124            new_selections.push(Selection {
 7125                start: (start as i32 - selection_adjustment) as usize,
 7126                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7127                goal: SelectionGoal::None,
 7128                ..selection
 7129            });
 7130
 7131            selection_adjustment += old_length - text.len() as i32;
 7132
 7133            edits.push((start..end, text));
 7134        }
 7135
 7136        self.transact(window, cx, |this, window, cx| {
 7137            this.buffer.update(cx, |buffer, cx| {
 7138                buffer.edit(edits, None, cx);
 7139            });
 7140
 7141            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7142                s.select(new_selections);
 7143            });
 7144
 7145            this.request_autoscroll(Autoscroll::fit(), cx);
 7146        });
 7147    }
 7148
 7149    pub fn duplicate(
 7150        &mut self,
 7151        upwards: bool,
 7152        whole_lines: bool,
 7153        window: &mut Window,
 7154        cx: &mut Context<Self>,
 7155    ) {
 7156        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7157        let buffer = &display_map.buffer_snapshot;
 7158        let selections = self.selections.all::<Point>(cx);
 7159
 7160        let mut edits = Vec::new();
 7161        let mut selections_iter = selections.iter().peekable();
 7162        while let Some(selection) = selections_iter.next() {
 7163            let mut rows = selection.spanned_rows(false, &display_map);
 7164            // duplicate line-wise
 7165            if whole_lines || selection.start == selection.end {
 7166                // Avoid duplicating the same lines twice.
 7167                while let Some(next_selection) = selections_iter.peek() {
 7168                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7169                    if next_rows.start < rows.end {
 7170                        rows.end = next_rows.end;
 7171                        selections_iter.next().unwrap();
 7172                    } else {
 7173                        break;
 7174                    }
 7175                }
 7176
 7177                // Copy the text from the selected row region and splice it either at the start
 7178                // or end of the region.
 7179                let start = Point::new(rows.start.0, 0);
 7180                let end = Point::new(
 7181                    rows.end.previous_row().0,
 7182                    buffer.line_len(rows.end.previous_row()),
 7183                );
 7184                let text = buffer
 7185                    .text_for_range(start..end)
 7186                    .chain(Some("\n"))
 7187                    .collect::<String>();
 7188                let insert_location = if upwards {
 7189                    Point::new(rows.end.0, 0)
 7190                } else {
 7191                    start
 7192                };
 7193                edits.push((insert_location..insert_location, text));
 7194            } else {
 7195                // duplicate character-wise
 7196                let start = selection.start;
 7197                let end = selection.end;
 7198                let text = buffer.text_for_range(start..end).collect::<String>();
 7199                edits.push((selection.end..selection.end, text));
 7200            }
 7201        }
 7202
 7203        self.transact(window, cx, |this, _, cx| {
 7204            this.buffer.update(cx, |buffer, cx| {
 7205                buffer.edit(edits, None, cx);
 7206            });
 7207
 7208            this.request_autoscroll(Autoscroll::fit(), cx);
 7209        });
 7210    }
 7211
 7212    pub fn duplicate_line_up(
 7213        &mut self,
 7214        _: &DuplicateLineUp,
 7215        window: &mut Window,
 7216        cx: &mut Context<Self>,
 7217    ) {
 7218        self.duplicate(true, true, window, cx);
 7219    }
 7220
 7221    pub fn duplicate_line_down(
 7222        &mut self,
 7223        _: &DuplicateLineDown,
 7224        window: &mut Window,
 7225        cx: &mut Context<Self>,
 7226    ) {
 7227        self.duplicate(false, true, window, cx);
 7228    }
 7229
 7230    pub fn duplicate_selection(
 7231        &mut self,
 7232        _: &DuplicateSelection,
 7233        window: &mut Window,
 7234        cx: &mut Context<Self>,
 7235    ) {
 7236        self.duplicate(false, false, window, cx);
 7237    }
 7238
 7239    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7241        let buffer = self.buffer.read(cx).snapshot(cx);
 7242
 7243        let mut edits = Vec::new();
 7244        let mut unfold_ranges = Vec::new();
 7245        let mut refold_creases = Vec::new();
 7246
 7247        let selections = self.selections.all::<Point>(cx);
 7248        let mut selections = selections.iter().peekable();
 7249        let mut contiguous_row_selections = Vec::new();
 7250        let mut new_selections = Vec::new();
 7251
 7252        while let Some(selection) = selections.next() {
 7253            // Find all the selections that span a contiguous row range
 7254            let (start_row, end_row) = consume_contiguous_rows(
 7255                &mut contiguous_row_selections,
 7256                selection,
 7257                &display_map,
 7258                &mut selections,
 7259            );
 7260
 7261            // Move the text spanned by the row range to be before the line preceding the row range
 7262            if start_row.0 > 0 {
 7263                let range_to_move = Point::new(
 7264                    start_row.previous_row().0,
 7265                    buffer.line_len(start_row.previous_row()),
 7266                )
 7267                    ..Point::new(
 7268                        end_row.previous_row().0,
 7269                        buffer.line_len(end_row.previous_row()),
 7270                    );
 7271                let insertion_point = display_map
 7272                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7273                    .0;
 7274
 7275                // Don't move lines across excerpts
 7276                if buffer
 7277                    .excerpt_containing(insertion_point..range_to_move.end)
 7278                    .is_some()
 7279                {
 7280                    let text = buffer
 7281                        .text_for_range(range_to_move.clone())
 7282                        .flat_map(|s| s.chars())
 7283                        .skip(1)
 7284                        .chain(['\n'])
 7285                        .collect::<String>();
 7286
 7287                    edits.push((
 7288                        buffer.anchor_after(range_to_move.start)
 7289                            ..buffer.anchor_before(range_to_move.end),
 7290                        String::new(),
 7291                    ));
 7292                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7293                    edits.push((insertion_anchor..insertion_anchor, text));
 7294
 7295                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7296
 7297                    // Move selections up
 7298                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7299                        |mut selection| {
 7300                            selection.start.row -= row_delta;
 7301                            selection.end.row -= row_delta;
 7302                            selection
 7303                        },
 7304                    ));
 7305
 7306                    // Move folds up
 7307                    unfold_ranges.push(range_to_move.clone());
 7308                    for fold in display_map.folds_in_range(
 7309                        buffer.anchor_before(range_to_move.start)
 7310                            ..buffer.anchor_after(range_to_move.end),
 7311                    ) {
 7312                        let mut start = fold.range.start.to_point(&buffer);
 7313                        let mut end = fold.range.end.to_point(&buffer);
 7314                        start.row -= row_delta;
 7315                        end.row -= row_delta;
 7316                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7317                    }
 7318                }
 7319            }
 7320
 7321            // If we didn't move line(s), preserve the existing selections
 7322            new_selections.append(&mut contiguous_row_selections);
 7323        }
 7324
 7325        self.transact(window, cx, |this, window, cx| {
 7326            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7327            this.buffer.update(cx, |buffer, cx| {
 7328                for (range, text) in edits {
 7329                    buffer.edit([(range, text)], None, cx);
 7330                }
 7331            });
 7332            this.fold_creases(refold_creases, true, window, cx);
 7333            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7334                s.select(new_selections);
 7335            })
 7336        });
 7337    }
 7338
 7339    pub fn move_line_down(
 7340        &mut self,
 7341        _: &MoveLineDown,
 7342        window: &mut Window,
 7343        cx: &mut Context<Self>,
 7344    ) {
 7345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7346        let buffer = self.buffer.read(cx).snapshot(cx);
 7347
 7348        let mut edits = Vec::new();
 7349        let mut unfold_ranges = Vec::new();
 7350        let mut refold_creases = Vec::new();
 7351
 7352        let selections = self.selections.all::<Point>(cx);
 7353        let mut selections = selections.iter().peekable();
 7354        let mut contiguous_row_selections = Vec::new();
 7355        let mut new_selections = Vec::new();
 7356
 7357        while let Some(selection) = selections.next() {
 7358            // Find all the selections that span a contiguous row range
 7359            let (start_row, end_row) = consume_contiguous_rows(
 7360                &mut contiguous_row_selections,
 7361                selection,
 7362                &display_map,
 7363                &mut selections,
 7364            );
 7365
 7366            // Move the text spanned by the row range to be after the last line of the row range
 7367            if end_row.0 <= buffer.max_point().row {
 7368                let range_to_move =
 7369                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7370                let insertion_point = display_map
 7371                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7372                    .0;
 7373
 7374                // Don't move lines across excerpt boundaries
 7375                if buffer
 7376                    .excerpt_containing(range_to_move.start..insertion_point)
 7377                    .is_some()
 7378                {
 7379                    let mut text = String::from("\n");
 7380                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7381                    text.pop(); // Drop trailing newline
 7382                    edits.push((
 7383                        buffer.anchor_after(range_to_move.start)
 7384                            ..buffer.anchor_before(range_to_move.end),
 7385                        String::new(),
 7386                    ));
 7387                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7388                    edits.push((insertion_anchor..insertion_anchor, text));
 7389
 7390                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7391
 7392                    // Move selections down
 7393                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7394                        |mut selection| {
 7395                            selection.start.row += row_delta;
 7396                            selection.end.row += row_delta;
 7397                            selection
 7398                        },
 7399                    ));
 7400
 7401                    // Move folds down
 7402                    unfold_ranges.push(range_to_move.clone());
 7403                    for fold in display_map.folds_in_range(
 7404                        buffer.anchor_before(range_to_move.start)
 7405                            ..buffer.anchor_after(range_to_move.end),
 7406                    ) {
 7407                        let mut start = fold.range.start.to_point(&buffer);
 7408                        let mut end = fold.range.end.to_point(&buffer);
 7409                        start.row += row_delta;
 7410                        end.row += row_delta;
 7411                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7412                    }
 7413                }
 7414            }
 7415
 7416            // If we didn't move line(s), preserve the existing selections
 7417            new_selections.append(&mut contiguous_row_selections);
 7418        }
 7419
 7420        self.transact(window, cx, |this, window, cx| {
 7421            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7422            this.buffer.update(cx, |buffer, cx| {
 7423                for (range, text) in edits {
 7424                    buffer.edit([(range, text)], None, cx);
 7425                }
 7426            });
 7427            this.fold_creases(refold_creases, true, window, cx);
 7428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7429                s.select(new_selections)
 7430            });
 7431        });
 7432    }
 7433
 7434    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7435        let text_layout_details = &self.text_layout_details(window);
 7436        self.transact(window, cx, |this, window, cx| {
 7437            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7438                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7439                let line_mode = s.line_mode;
 7440                s.move_with(|display_map, selection| {
 7441                    if !selection.is_empty() || line_mode {
 7442                        return;
 7443                    }
 7444
 7445                    let mut head = selection.head();
 7446                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7447                    if head.column() == display_map.line_len(head.row()) {
 7448                        transpose_offset = display_map
 7449                            .buffer_snapshot
 7450                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7451                    }
 7452
 7453                    if transpose_offset == 0 {
 7454                        return;
 7455                    }
 7456
 7457                    *head.column_mut() += 1;
 7458                    head = display_map.clip_point(head, Bias::Right);
 7459                    let goal = SelectionGoal::HorizontalPosition(
 7460                        display_map
 7461                            .x_for_display_point(head, text_layout_details)
 7462                            .into(),
 7463                    );
 7464                    selection.collapse_to(head, goal);
 7465
 7466                    let transpose_start = display_map
 7467                        .buffer_snapshot
 7468                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7469                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7470                        let transpose_end = display_map
 7471                            .buffer_snapshot
 7472                            .clip_offset(transpose_offset + 1, Bias::Right);
 7473                        if let Some(ch) =
 7474                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7475                        {
 7476                            edits.push((transpose_start..transpose_offset, String::new()));
 7477                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7478                        }
 7479                    }
 7480                });
 7481                edits
 7482            });
 7483            this.buffer
 7484                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7485            let selections = this.selections.all::<usize>(cx);
 7486            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7487                s.select(selections);
 7488            });
 7489        });
 7490    }
 7491
 7492    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7493        self.rewrap_impl(IsVimMode::No, cx)
 7494    }
 7495
 7496    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7497        let buffer = self.buffer.read(cx).snapshot(cx);
 7498        let selections = self.selections.all::<Point>(cx);
 7499        let mut selections = selections.iter().peekable();
 7500
 7501        let mut edits = Vec::new();
 7502        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7503
 7504        while let Some(selection) = selections.next() {
 7505            let mut start_row = selection.start.row;
 7506            let mut end_row = selection.end.row;
 7507
 7508            // Skip selections that overlap with a range that has already been rewrapped.
 7509            let selection_range = start_row..end_row;
 7510            if rewrapped_row_ranges
 7511                .iter()
 7512                .any(|range| range.overlaps(&selection_range))
 7513            {
 7514                continue;
 7515            }
 7516
 7517            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7518
 7519            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7520                match language_scope.language_name().as_ref() {
 7521                    "Markdown" | "Plain Text" => {
 7522                        should_rewrap = true;
 7523                    }
 7524                    _ => {}
 7525                }
 7526            }
 7527
 7528            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7529
 7530            // Since not all lines in the selection may be at the same indent
 7531            // level, choose the indent size that is the most common between all
 7532            // of the lines.
 7533            //
 7534            // If there is a tie, we use the deepest indent.
 7535            let (indent_size, indent_end) = {
 7536                let mut indent_size_occurrences = HashMap::default();
 7537                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7538
 7539                for row in start_row..=end_row {
 7540                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7541                    rows_by_indent_size.entry(indent).or_default().push(row);
 7542                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7543                }
 7544
 7545                let indent_size = indent_size_occurrences
 7546                    .into_iter()
 7547                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7548                    .map(|(indent, _)| indent)
 7549                    .unwrap_or_default();
 7550                let row = rows_by_indent_size[&indent_size][0];
 7551                let indent_end = Point::new(row, indent_size.len);
 7552
 7553                (indent_size, indent_end)
 7554            };
 7555
 7556            let mut line_prefix = indent_size.chars().collect::<String>();
 7557
 7558            if let Some(comment_prefix) =
 7559                buffer
 7560                    .language_scope_at(selection.head())
 7561                    .and_then(|language| {
 7562                        language
 7563                            .line_comment_prefixes()
 7564                            .iter()
 7565                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7566                            .cloned()
 7567                    })
 7568            {
 7569                line_prefix.push_str(&comment_prefix);
 7570                should_rewrap = true;
 7571            }
 7572
 7573            if !should_rewrap {
 7574                continue;
 7575            }
 7576
 7577            if selection.is_empty() {
 7578                'expand_upwards: while start_row > 0 {
 7579                    let prev_row = start_row - 1;
 7580                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7581                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7582                    {
 7583                        start_row = prev_row;
 7584                    } else {
 7585                        break 'expand_upwards;
 7586                    }
 7587                }
 7588
 7589                'expand_downwards: while end_row < buffer.max_point().row {
 7590                    let next_row = end_row + 1;
 7591                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7592                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7593                    {
 7594                        end_row = next_row;
 7595                    } else {
 7596                        break 'expand_downwards;
 7597                    }
 7598                }
 7599            }
 7600
 7601            let start = Point::new(start_row, 0);
 7602            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7603            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7604            let Some(lines_without_prefixes) = selection_text
 7605                .lines()
 7606                .map(|line| {
 7607                    line.strip_prefix(&line_prefix)
 7608                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7609                        .ok_or_else(|| {
 7610                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7611                        })
 7612                })
 7613                .collect::<Result<Vec<_>, _>>()
 7614                .log_err()
 7615            else {
 7616                continue;
 7617            };
 7618
 7619            let wrap_column = buffer
 7620                .settings_at(Point::new(start_row, 0), cx)
 7621                .preferred_line_length as usize;
 7622            let wrapped_text = wrap_with_prefix(
 7623                line_prefix,
 7624                lines_without_prefixes.join(" "),
 7625                wrap_column,
 7626                tab_size,
 7627            );
 7628
 7629            // TODO: should always use char-based diff while still supporting cursor behavior that
 7630            // matches vim.
 7631            let diff = match is_vim_mode {
 7632                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7633                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7634            };
 7635            let mut offset = start.to_offset(&buffer);
 7636            let mut moved_since_edit = true;
 7637
 7638            for change in diff.iter_all_changes() {
 7639                let value = change.value();
 7640                match change.tag() {
 7641                    ChangeTag::Equal => {
 7642                        offset += value.len();
 7643                        moved_since_edit = true;
 7644                    }
 7645                    ChangeTag::Delete => {
 7646                        let start = buffer.anchor_after(offset);
 7647                        let end = buffer.anchor_before(offset + value.len());
 7648
 7649                        if moved_since_edit {
 7650                            edits.push((start..end, String::new()));
 7651                        } else {
 7652                            edits.last_mut().unwrap().0.end = end;
 7653                        }
 7654
 7655                        offset += value.len();
 7656                        moved_since_edit = false;
 7657                    }
 7658                    ChangeTag::Insert => {
 7659                        if moved_since_edit {
 7660                            let anchor = buffer.anchor_after(offset);
 7661                            edits.push((anchor..anchor, value.to_string()));
 7662                        } else {
 7663                            edits.last_mut().unwrap().1.push_str(value);
 7664                        }
 7665
 7666                        moved_since_edit = false;
 7667                    }
 7668                }
 7669            }
 7670
 7671            rewrapped_row_ranges.push(start_row..=end_row);
 7672        }
 7673
 7674        self.buffer
 7675            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7676    }
 7677
 7678    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7679        let mut text = String::new();
 7680        let buffer = self.buffer.read(cx).snapshot(cx);
 7681        let mut selections = self.selections.all::<Point>(cx);
 7682        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7683        {
 7684            let max_point = buffer.max_point();
 7685            let mut is_first = true;
 7686            for selection in &mut selections {
 7687                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7688                if is_entire_line {
 7689                    selection.start = Point::new(selection.start.row, 0);
 7690                    if !selection.is_empty() && selection.end.column == 0 {
 7691                        selection.end = cmp::min(max_point, selection.end);
 7692                    } else {
 7693                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7694                    }
 7695                    selection.goal = SelectionGoal::None;
 7696                }
 7697                if is_first {
 7698                    is_first = false;
 7699                } else {
 7700                    text += "\n";
 7701                }
 7702                let mut len = 0;
 7703                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7704                    text.push_str(chunk);
 7705                    len += chunk.len();
 7706                }
 7707                clipboard_selections.push(ClipboardSelection {
 7708                    len,
 7709                    is_entire_line,
 7710                    first_line_indent: buffer
 7711                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7712                        .len,
 7713                });
 7714            }
 7715        }
 7716
 7717        self.transact(window, cx, |this, window, cx| {
 7718            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7719                s.select(selections);
 7720            });
 7721            this.insert("", window, cx);
 7722        });
 7723        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7724    }
 7725
 7726    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7727        let item = self.cut_common(window, cx);
 7728        cx.write_to_clipboard(item);
 7729    }
 7730
 7731    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7732        self.change_selections(None, window, cx, |s| {
 7733            s.move_with(|snapshot, sel| {
 7734                if sel.is_empty() {
 7735                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7736                }
 7737            });
 7738        });
 7739        let item = self.cut_common(window, cx);
 7740        cx.set_global(KillRing(item))
 7741    }
 7742
 7743    pub fn kill_ring_yank(
 7744        &mut self,
 7745        _: &KillRingYank,
 7746        window: &mut Window,
 7747        cx: &mut Context<Self>,
 7748    ) {
 7749        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7750            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7751                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7752            } else {
 7753                return;
 7754            }
 7755        } else {
 7756            return;
 7757        };
 7758        self.do_paste(&text, metadata, false, window, cx);
 7759    }
 7760
 7761    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7762        let selections = self.selections.all::<Point>(cx);
 7763        let buffer = self.buffer.read(cx).read(cx);
 7764        let mut text = String::new();
 7765
 7766        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7767        {
 7768            let max_point = buffer.max_point();
 7769            let mut is_first = true;
 7770            for selection in selections.iter() {
 7771                let mut start = selection.start;
 7772                let mut end = selection.end;
 7773                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7774                if is_entire_line {
 7775                    start = Point::new(start.row, 0);
 7776                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7777                }
 7778                if is_first {
 7779                    is_first = false;
 7780                } else {
 7781                    text += "\n";
 7782                }
 7783                let mut len = 0;
 7784                for chunk in buffer.text_for_range(start..end) {
 7785                    text.push_str(chunk);
 7786                    len += chunk.len();
 7787                }
 7788                clipboard_selections.push(ClipboardSelection {
 7789                    len,
 7790                    is_entire_line,
 7791                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7792                });
 7793            }
 7794        }
 7795
 7796        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7797            text,
 7798            clipboard_selections,
 7799        ));
 7800    }
 7801
 7802    pub fn do_paste(
 7803        &mut self,
 7804        text: &String,
 7805        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7806        handle_entire_lines: bool,
 7807        window: &mut Window,
 7808        cx: &mut Context<Self>,
 7809    ) {
 7810        if self.read_only(cx) {
 7811            return;
 7812        }
 7813
 7814        let clipboard_text = Cow::Borrowed(text);
 7815
 7816        self.transact(window, cx, |this, window, cx| {
 7817            if let Some(mut clipboard_selections) = clipboard_selections {
 7818                let old_selections = this.selections.all::<usize>(cx);
 7819                let all_selections_were_entire_line =
 7820                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7821                let first_selection_indent_column =
 7822                    clipboard_selections.first().map(|s| s.first_line_indent);
 7823                if clipboard_selections.len() != old_selections.len() {
 7824                    clipboard_selections.drain(..);
 7825                }
 7826                let cursor_offset = this.selections.last::<usize>(cx).head();
 7827                let mut auto_indent_on_paste = true;
 7828
 7829                this.buffer.update(cx, |buffer, cx| {
 7830                    let snapshot = buffer.read(cx);
 7831                    auto_indent_on_paste =
 7832                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7833
 7834                    let mut start_offset = 0;
 7835                    let mut edits = Vec::new();
 7836                    let mut original_indent_columns = Vec::new();
 7837                    for (ix, selection) in old_selections.iter().enumerate() {
 7838                        let to_insert;
 7839                        let entire_line;
 7840                        let original_indent_column;
 7841                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7842                            let end_offset = start_offset + clipboard_selection.len;
 7843                            to_insert = &clipboard_text[start_offset..end_offset];
 7844                            entire_line = clipboard_selection.is_entire_line;
 7845                            start_offset = end_offset + 1;
 7846                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7847                        } else {
 7848                            to_insert = clipboard_text.as_str();
 7849                            entire_line = all_selections_were_entire_line;
 7850                            original_indent_column = first_selection_indent_column
 7851                        }
 7852
 7853                        // If the corresponding selection was empty when this slice of the
 7854                        // clipboard text was written, then the entire line containing the
 7855                        // selection was copied. If this selection is also currently empty,
 7856                        // then paste the line before the current line of the buffer.
 7857                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7858                            let column = selection.start.to_point(&snapshot).column as usize;
 7859                            let line_start = selection.start - column;
 7860                            line_start..line_start
 7861                        } else {
 7862                            selection.range()
 7863                        };
 7864
 7865                        edits.push((range, to_insert));
 7866                        original_indent_columns.extend(original_indent_column);
 7867                    }
 7868                    drop(snapshot);
 7869
 7870                    buffer.edit(
 7871                        edits,
 7872                        if auto_indent_on_paste {
 7873                            Some(AutoindentMode::Block {
 7874                                original_indent_columns,
 7875                            })
 7876                        } else {
 7877                            None
 7878                        },
 7879                        cx,
 7880                    );
 7881                });
 7882
 7883                let selections = this.selections.all::<usize>(cx);
 7884                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7885                    s.select(selections)
 7886                });
 7887            } else {
 7888                this.insert(&clipboard_text, window, cx);
 7889            }
 7890        });
 7891    }
 7892
 7893    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7894        if let Some(item) = cx.read_from_clipboard() {
 7895            let entries = item.entries();
 7896
 7897            match entries.first() {
 7898                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7899                // of all the pasted entries.
 7900                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7901                    .do_paste(
 7902                        clipboard_string.text(),
 7903                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7904                        true,
 7905                        window,
 7906                        cx,
 7907                    ),
 7908                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7909            }
 7910        }
 7911    }
 7912
 7913    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7914        if self.read_only(cx) {
 7915            return;
 7916        }
 7917
 7918        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7919            if let Some((selections, _)) =
 7920                self.selection_history.transaction(transaction_id).cloned()
 7921            {
 7922                self.change_selections(None, window, cx, |s| {
 7923                    s.select_anchors(selections.to_vec());
 7924                });
 7925            }
 7926            self.request_autoscroll(Autoscroll::fit(), cx);
 7927            self.unmark_text(window, cx);
 7928            self.refresh_inline_completion(true, false, window, cx);
 7929            cx.emit(EditorEvent::Edited { transaction_id });
 7930            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7931        }
 7932    }
 7933
 7934    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7935        if self.read_only(cx) {
 7936            return;
 7937        }
 7938
 7939        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7940            if let Some((_, Some(selections))) =
 7941                self.selection_history.transaction(transaction_id).cloned()
 7942            {
 7943                self.change_selections(None, window, cx, |s| {
 7944                    s.select_anchors(selections.to_vec());
 7945                });
 7946            }
 7947            self.request_autoscroll(Autoscroll::fit(), cx);
 7948            self.unmark_text(window, cx);
 7949            self.refresh_inline_completion(true, false, window, cx);
 7950            cx.emit(EditorEvent::Edited { transaction_id });
 7951        }
 7952    }
 7953
 7954    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7955        self.buffer
 7956            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7957    }
 7958
 7959    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7960        self.buffer
 7961            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7962    }
 7963
 7964    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7966            let line_mode = s.line_mode;
 7967            s.move_with(|map, selection| {
 7968                let cursor = if selection.is_empty() && !line_mode {
 7969                    movement::left(map, selection.start)
 7970                } else {
 7971                    selection.start
 7972                };
 7973                selection.collapse_to(cursor, SelectionGoal::None);
 7974            });
 7975        })
 7976    }
 7977
 7978    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7980            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7981        })
 7982    }
 7983
 7984    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7985        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7986            let line_mode = s.line_mode;
 7987            s.move_with(|map, selection| {
 7988                let cursor = if selection.is_empty() && !line_mode {
 7989                    movement::right(map, selection.end)
 7990                } else {
 7991                    selection.end
 7992                };
 7993                selection.collapse_to(cursor, SelectionGoal::None)
 7994            });
 7995        })
 7996    }
 7997
 7998    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7999        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8000            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8001        })
 8002    }
 8003
 8004    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8005        if self.take_rename(true, window, cx).is_some() {
 8006            return;
 8007        }
 8008
 8009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8010            cx.propagate();
 8011            return;
 8012        }
 8013
 8014        let text_layout_details = &self.text_layout_details(window);
 8015        let selection_count = self.selections.count();
 8016        let first_selection = self.selections.first_anchor();
 8017
 8018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8019            let line_mode = s.line_mode;
 8020            s.move_with(|map, selection| {
 8021                if !selection.is_empty() && !line_mode {
 8022                    selection.goal = SelectionGoal::None;
 8023                }
 8024                let (cursor, goal) = movement::up(
 8025                    map,
 8026                    selection.start,
 8027                    selection.goal,
 8028                    false,
 8029                    text_layout_details,
 8030                );
 8031                selection.collapse_to(cursor, goal);
 8032            });
 8033        });
 8034
 8035        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8036        {
 8037            cx.propagate();
 8038        }
 8039    }
 8040
 8041    pub fn move_up_by_lines(
 8042        &mut self,
 8043        action: &MoveUpByLines,
 8044        window: &mut Window,
 8045        cx: &mut Context<Self>,
 8046    ) {
 8047        if self.take_rename(true, window, cx).is_some() {
 8048            return;
 8049        }
 8050
 8051        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8052            cx.propagate();
 8053            return;
 8054        }
 8055
 8056        let text_layout_details = &self.text_layout_details(window);
 8057
 8058        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8059            let line_mode = s.line_mode;
 8060            s.move_with(|map, selection| {
 8061                if !selection.is_empty() && !line_mode {
 8062                    selection.goal = SelectionGoal::None;
 8063                }
 8064                let (cursor, goal) = movement::up_by_rows(
 8065                    map,
 8066                    selection.start,
 8067                    action.lines,
 8068                    selection.goal,
 8069                    false,
 8070                    text_layout_details,
 8071                );
 8072                selection.collapse_to(cursor, goal);
 8073            });
 8074        })
 8075    }
 8076
 8077    pub fn move_down_by_lines(
 8078        &mut self,
 8079        action: &MoveDownByLines,
 8080        window: &mut Window,
 8081        cx: &mut Context<Self>,
 8082    ) {
 8083        if self.take_rename(true, window, cx).is_some() {
 8084            return;
 8085        }
 8086
 8087        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8088            cx.propagate();
 8089            return;
 8090        }
 8091
 8092        let text_layout_details = &self.text_layout_details(window);
 8093
 8094        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8095            let line_mode = s.line_mode;
 8096            s.move_with(|map, selection| {
 8097                if !selection.is_empty() && !line_mode {
 8098                    selection.goal = SelectionGoal::None;
 8099                }
 8100                let (cursor, goal) = movement::down_by_rows(
 8101                    map,
 8102                    selection.start,
 8103                    action.lines,
 8104                    selection.goal,
 8105                    false,
 8106                    text_layout_details,
 8107                );
 8108                selection.collapse_to(cursor, goal);
 8109            });
 8110        })
 8111    }
 8112
 8113    pub fn select_down_by_lines(
 8114        &mut self,
 8115        action: &SelectDownByLines,
 8116        window: &mut Window,
 8117        cx: &mut Context<Self>,
 8118    ) {
 8119        let text_layout_details = &self.text_layout_details(window);
 8120        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8121            s.move_heads_with(|map, head, goal| {
 8122                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8123            })
 8124        })
 8125    }
 8126
 8127    pub fn select_up_by_lines(
 8128        &mut self,
 8129        action: &SelectUpByLines,
 8130        window: &mut Window,
 8131        cx: &mut Context<Self>,
 8132    ) {
 8133        let text_layout_details = &self.text_layout_details(window);
 8134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8135            s.move_heads_with(|map, head, goal| {
 8136                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8137            })
 8138        })
 8139    }
 8140
 8141    pub fn select_page_up(
 8142        &mut self,
 8143        _: &SelectPageUp,
 8144        window: &mut Window,
 8145        cx: &mut Context<Self>,
 8146    ) {
 8147        let Some(row_count) = self.visible_row_count() else {
 8148            return;
 8149        };
 8150
 8151        let text_layout_details = &self.text_layout_details(window);
 8152
 8153        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8154            s.move_heads_with(|map, head, goal| {
 8155                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8156            })
 8157        })
 8158    }
 8159
 8160    pub fn move_page_up(
 8161        &mut self,
 8162        action: &MovePageUp,
 8163        window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) {
 8166        if self.take_rename(true, window, cx).is_some() {
 8167            return;
 8168        }
 8169
 8170        if self
 8171            .context_menu
 8172            .borrow_mut()
 8173            .as_mut()
 8174            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8175            .unwrap_or(false)
 8176        {
 8177            return;
 8178        }
 8179
 8180        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8181            cx.propagate();
 8182            return;
 8183        }
 8184
 8185        let Some(row_count) = self.visible_row_count() else {
 8186            return;
 8187        };
 8188
 8189        let autoscroll = if action.center_cursor {
 8190            Autoscroll::center()
 8191        } else {
 8192            Autoscroll::fit()
 8193        };
 8194
 8195        let text_layout_details = &self.text_layout_details(window);
 8196
 8197        self.change_selections(Some(autoscroll), window, cx, |s| {
 8198            let line_mode = s.line_mode;
 8199            s.move_with(|map, selection| {
 8200                if !selection.is_empty() && !line_mode {
 8201                    selection.goal = SelectionGoal::None;
 8202                }
 8203                let (cursor, goal) = movement::up_by_rows(
 8204                    map,
 8205                    selection.end,
 8206                    row_count,
 8207                    selection.goal,
 8208                    false,
 8209                    text_layout_details,
 8210                );
 8211                selection.collapse_to(cursor, goal);
 8212            });
 8213        });
 8214    }
 8215
 8216    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8217        let text_layout_details = &self.text_layout_details(window);
 8218        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8219            s.move_heads_with(|map, head, goal| {
 8220                movement::up(map, head, goal, false, text_layout_details)
 8221            })
 8222        })
 8223    }
 8224
 8225    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8226        self.take_rename(true, window, cx);
 8227
 8228        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8229            cx.propagate();
 8230            return;
 8231        }
 8232
 8233        let text_layout_details = &self.text_layout_details(window);
 8234        let selection_count = self.selections.count();
 8235        let first_selection = self.selections.first_anchor();
 8236
 8237        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8238            let line_mode = s.line_mode;
 8239            s.move_with(|map, selection| {
 8240                if !selection.is_empty() && !line_mode {
 8241                    selection.goal = SelectionGoal::None;
 8242                }
 8243                let (cursor, goal) = movement::down(
 8244                    map,
 8245                    selection.end,
 8246                    selection.goal,
 8247                    false,
 8248                    text_layout_details,
 8249                );
 8250                selection.collapse_to(cursor, goal);
 8251            });
 8252        });
 8253
 8254        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8255        {
 8256            cx.propagate();
 8257        }
 8258    }
 8259
 8260    pub fn select_page_down(
 8261        &mut self,
 8262        _: &SelectPageDown,
 8263        window: &mut Window,
 8264        cx: &mut Context<Self>,
 8265    ) {
 8266        let Some(row_count) = self.visible_row_count() else {
 8267            return;
 8268        };
 8269
 8270        let text_layout_details = &self.text_layout_details(window);
 8271
 8272        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8273            s.move_heads_with(|map, head, goal| {
 8274                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8275            })
 8276        })
 8277    }
 8278
 8279    pub fn move_page_down(
 8280        &mut self,
 8281        action: &MovePageDown,
 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 self
 8290            .context_menu
 8291            .borrow_mut()
 8292            .as_mut()
 8293            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8294            .unwrap_or(false)
 8295        {
 8296            return;
 8297        }
 8298
 8299        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8300            cx.propagate();
 8301            return;
 8302        }
 8303
 8304        let Some(row_count) = self.visible_row_count() else {
 8305            return;
 8306        };
 8307
 8308        let autoscroll = if action.center_cursor {
 8309            Autoscroll::center()
 8310        } else {
 8311            Autoscroll::fit()
 8312        };
 8313
 8314        let text_layout_details = &self.text_layout_details(window);
 8315        self.change_selections(Some(autoscroll), window, cx, |s| {
 8316            let line_mode = s.line_mode;
 8317            s.move_with(|map, selection| {
 8318                if !selection.is_empty() && !line_mode {
 8319                    selection.goal = SelectionGoal::None;
 8320                }
 8321                let (cursor, goal) = movement::down_by_rows(
 8322                    map,
 8323                    selection.end,
 8324                    row_count,
 8325                    selection.goal,
 8326                    false,
 8327                    text_layout_details,
 8328                );
 8329                selection.collapse_to(cursor, goal);
 8330            });
 8331        });
 8332    }
 8333
 8334    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 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::down(map, head, goal, false, text_layout_details)
 8339            })
 8340        });
 8341    }
 8342
 8343    pub fn context_menu_first(
 8344        &mut self,
 8345        _: &ContextMenuFirst,
 8346        _window: &mut Window,
 8347        cx: &mut Context<Self>,
 8348    ) {
 8349        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8350            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8351        }
 8352    }
 8353
 8354    pub fn context_menu_prev(
 8355        &mut self,
 8356        _: &ContextMenuPrev,
 8357        _window: &mut Window,
 8358        cx: &mut Context<Self>,
 8359    ) {
 8360        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8361            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8362        }
 8363    }
 8364
 8365    pub fn context_menu_next(
 8366        &mut self,
 8367        _: &ContextMenuNext,
 8368        _window: &mut Window,
 8369        cx: &mut Context<Self>,
 8370    ) {
 8371        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8372            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8373        }
 8374    }
 8375
 8376    pub fn context_menu_last(
 8377        &mut self,
 8378        _: &ContextMenuLast,
 8379        _window: &mut Window,
 8380        cx: &mut Context<Self>,
 8381    ) {
 8382        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8383            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8384        }
 8385    }
 8386
 8387    pub fn move_to_previous_word_start(
 8388        &mut self,
 8389        _: &MoveToPreviousWordStart,
 8390        window: &mut Window,
 8391        cx: &mut Context<Self>,
 8392    ) {
 8393        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8394            s.move_cursors_with(|map, head, _| {
 8395                (
 8396                    movement::previous_word_start(map, head),
 8397                    SelectionGoal::None,
 8398                )
 8399            });
 8400        })
 8401    }
 8402
 8403    pub fn move_to_previous_subword_start(
 8404        &mut self,
 8405        _: &MoveToPreviousSubwordStart,
 8406        window: &mut Window,
 8407        cx: &mut Context<Self>,
 8408    ) {
 8409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8410            s.move_cursors_with(|map, head, _| {
 8411                (
 8412                    movement::previous_subword_start(map, head),
 8413                    SelectionGoal::None,
 8414                )
 8415            });
 8416        })
 8417    }
 8418
 8419    pub fn select_to_previous_word_start(
 8420        &mut self,
 8421        _: &SelectToPreviousWordStart,
 8422        window: &mut Window,
 8423        cx: &mut Context<Self>,
 8424    ) {
 8425        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8426            s.move_heads_with(|map, head, _| {
 8427                (
 8428                    movement::previous_word_start(map, head),
 8429                    SelectionGoal::None,
 8430                )
 8431            });
 8432        })
 8433    }
 8434
 8435    pub fn select_to_previous_subword_start(
 8436        &mut self,
 8437        _: &SelectToPreviousSubwordStart,
 8438        window: &mut Window,
 8439        cx: &mut Context<Self>,
 8440    ) {
 8441        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8442            s.move_heads_with(|map, head, _| {
 8443                (
 8444                    movement::previous_subword_start(map, head),
 8445                    SelectionGoal::None,
 8446                )
 8447            });
 8448        })
 8449    }
 8450
 8451    pub fn delete_to_previous_word_start(
 8452        &mut self,
 8453        action: &DeleteToPreviousWordStart,
 8454        window: &mut Window,
 8455        cx: &mut Context<Self>,
 8456    ) {
 8457        self.transact(window, cx, |this, window, cx| {
 8458            this.select_autoclose_pair(window, cx);
 8459            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8460                let line_mode = s.line_mode;
 8461                s.move_with(|map, selection| {
 8462                    if selection.is_empty() && !line_mode {
 8463                        let cursor = if action.ignore_newlines {
 8464                            movement::previous_word_start(map, selection.head())
 8465                        } else {
 8466                            movement::previous_word_start_or_newline(map, selection.head())
 8467                        };
 8468                        selection.set_head(cursor, SelectionGoal::None);
 8469                    }
 8470                });
 8471            });
 8472            this.insert("", window, cx);
 8473        });
 8474    }
 8475
 8476    pub fn delete_to_previous_subword_start(
 8477        &mut self,
 8478        _: &DeleteToPreviousSubwordStart,
 8479        window: &mut Window,
 8480        cx: &mut Context<Self>,
 8481    ) {
 8482        self.transact(window, cx, |this, window, cx| {
 8483            this.select_autoclose_pair(window, cx);
 8484            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8485                let line_mode = s.line_mode;
 8486                s.move_with(|map, selection| {
 8487                    if selection.is_empty() && !line_mode {
 8488                        let cursor = movement::previous_subword_start(map, selection.head());
 8489                        selection.set_head(cursor, SelectionGoal::None);
 8490                    }
 8491                });
 8492            });
 8493            this.insert("", window, cx);
 8494        });
 8495    }
 8496
 8497    pub fn move_to_next_word_end(
 8498        &mut self,
 8499        _: &MoveToNextWordEnd,
 8500        window: &mut Window,
 8501        cx: &mut Context<Self>,
 8502    ) {
 8503        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8504            s.move_cursors_with(|map, head, _| {
 8505                (movement::next_word_end(map, head), SelectionGoal::None)
 8506            });
 8507        })
 8508    }
 8509
 8510    pub fn move_to_next_subword_end(
 8511        &mut self,
 8512        _: &MoveToNextSubwordEnd,
 8513        window: &mut Window,
 8514        cx: &mut Context<Self>,
 8515    ) {
 8516        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8517            s.move_cursors_with(|map, head, _| {
 8518                (movement::next_subword_end(map, head), SelectionGoal::None)
 8519            });
 8520        })
 8521    }
 8522
 8523    pub fn select_to_next_word_end(
 8524        &mut self,
 8525        _: &SelectToNextWordEnd,
 8526        window: &mut Window,
 8527        cx: &mut Context<Self>,
 8528    ) {
 8529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8530            s.move_heads_with(|map, head, _| {
 8531                (movement::next_word_end(map, head), SelectionGoal::None)
 8532            });
 8533        })
 8534    }
 8535
 8536    pub fn select_to_next_subword_end(
 8537        &mut self,
 8538        _: &SelectToNextSubwordEnd,
 8539        window: &mut Window,
 8540        cx: &mut Context<Self>,
 8541    ) {
 8542        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8543            s.move_heads_with(|map, head, _| {
 8544                (movement::next_subword_end(map, head), SelectionGoal::None)
 8545            });
 8546        })
 8547    }
 8548
 8549    pub fn delete_to_next_word_end(
 8550        &mut self,
 8551        action: &DeleteToNextWordEnd,
 8552        window: &mut Window,
 8553        cx: &mut Context<Self>,
 8554    ) {
 8555        self.transact(window, cx, |this, window, cx| {
 8556            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8557                let line_mode = s.line_mode;
 8558                s.move_with(|map, selection| {
 8559                    if selection.is_empty() && !line_mode {
 8560                        let cursor = if action.ignore_newlines {
 8561                            movement::next_word_end(map, selection.head())
 8562                        } else {
 8563                            movement::next_word_end_or_newline(map, selection.head())
 8564                        };
 8565                        selection.set_head(cursor, SelectionGoal::None);
 8566                    }
 8567                });
 8568            });
 8569            this.insert("", window, cx);
 8570        });
 8571    }
 8572
 8573    pub fn delete_to_next_subword_end(
 8574        &mut self,
 8575        _: &DeleteToNextSubwordEnd,
 8576        window: &mut Window,
 8577        cx: &mut Context<Self>,
 8578    ) {
 8579        self.transact(window, cx, |this, window, cx| {
 8580            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8581                s.move_with(|map, selection| {
 8582                    if selection.is_empty() {
 8583                        let cursor = movement::next_subword_end(map, selection.head());
 8584                        selection.set_head(cursor, SelectionGoal::None);
 8585                    }
 8586                });
 8587            });
 8588            this.insert("", window, cx);
 8589        });
 8590    }
 8591
 8592    pub fn move_to_beginning_of_line(
 8593        &mut self,
 8594        action: &MoveToBeginningOfLine,
 8595        window: &mut Window,
 8596        cx: &mut Context<Self>,
 8597    ) {
 8598        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8599            s.move_cursors_with(|map, head, _| {
 8600                (
 8601                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8602                    SelectionGoal::None,
 8603                )
 8604            });
 8605        })
 8606    }
 8607
 8608    pub fn select_to_beginning_of_line(
 8609        &mut self,
 8610        action: &SelectToBeginningOfLine,
 8611        window: &mut Window,
 8612        cx: &mut Context<Self>,
 8613    ) {
 8614        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8615            s.move_heads_with(|map, head, _| {
 8616                (
 8617                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8618                    SelectionGoal::None,
 8619                )
 8620            });
 8621        });
 8622    }
 8623
 8624    pub fn delete_to_beginning_of_line(
 8625        &mut self,
 8626        _: &DeleteToBeginningOfLine,
 8627        window: &mut Window,
 8628        cx: &mut Context<Self>,
 8629    ) {
 8630        self.transact(window, cx, |this, window, cx| {
 8631            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632                s.move_with(|_, selection| {
 8633                    selection.reversed = true;
 8634                });
 8635            });
 8636
 8637            this.select_to_beginning_of_line(
 8638                &SelectToBeginningOfLine {
 8639                    stop_at_soft_wraps: false,
 8640                },
 8641                window,
 8642                cx,
 8643            );
 8644            this.backspace(&Backspace, window, cx);
 8645        });
 8646    }
 8647
 8648    pub fn move_to_end_of_line(
 8649        &mut self,
 8650        action: &MoveToEndOfLine,
 8651        window: &mut Window,
 8652        cx: &mut Context<Self>,
 8653    ) {
 8654        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8655            s.move_cursors_with(|map, head, _| {
 8656                (
 8657                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8658                    SelectionGoal::None,
 8659                )
 8660            });
 8661        })
 8662    }
 8663
 8664    pub fn select_to_end_of_line(
 8665        &mut self,
 8666        action: &SelectToEndOfLine,
 8667        window: &mut Window,
 8668        cx: &mut Context<Self>,
 8669    ) {
 8670        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8671            s.move_heads_with(|map, head, _| {
 8672                (
 8673                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8674                    SelectionGoal::None,
 8675                )
 8676            });
 8677        })
 8678    }
 8679
 8680    pub fn delete_to_end_of_line(
 8681        &mut self,
 8682        _: &DeleteToEndOfLine,
 8683        window: &mut Window,
 8684        cx: &mut Context<Self>,
 8685    ) {
 8686        self.transact(window, cx, |this, window, cx| {
 8687            this.select_to_end_of_line(
 8688                &SelectToEndOfLine {
 8689                    stop_at_soft_wraps: false,
 8690                },
 8691                window,
 8692                cx,
 8693            );
 8694            this.delete(&Delete, window, cx);
 8695        });
 8696    }
 8697
 8698    pub fn cut_to_end_of_line(
 8699        &mut self,
 8700        _: &CutToEndOfLine,
 8701        window: &mut Window,
 8702        cx: &mut Context<Self>,
 8703    ) {
 8704        self.transact(window, cx, |this, window, cx| {
 8705            this.select_to_end_of_line(
 8706                &SelectToEndOfLine {
 8707                    stop_at_soft_wraps: false,
 8708                },
 8709                window,
 8710                cx,
 8711            );
 8712            this.cut(&Cut, window, cx);
 8713        });
 8714    }
 8715
 8716    pub fn move_to_start_of_paragraph(
 8717        &mut self,
 8718        _: &MoveToStartOfParagraph,
 8719        window: &mut Window,
 8720        cx: &mut Context<Self>,
 8721    ) {
 8722        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8723            cx.propagate();
 8724            return;
 8725        }
 8726
 8727        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8728            s.move_with(|map, selection| {
 8729                selection.collapse_to(
 8730                    movement::start_of_paragraph(map, selection.head(), 1),
 8731                    SelectionGoal::None,
 8732                )
 8733            });
 8734        })
 8735    }
 8736
 8737    pub fn move_to_end_of_paragraph(
 8738        &mut self,
 8739        _: &MoveToEndOfParagraph,
 8740        window: &mut Window,
 8741        cx: &mut Context<Self>,
 8742    ) {
 8743        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8744            cx.propagate();
 8745            return;
 8746        }
 8747
 8748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8749            s.move_with(|map, selection| {
 8750                selection.collapse_to(
 8751                    movement::end_of_paragraph(map, selection.head(), 1),
 8752                    SelectionGoal::None,
 8753                )
 8754            });
 8755        })
 8756    }
 8757
 8758    pub fn select_to_start_of_paragraph(
 8759        &mut self,
 8760        _: &SelectToStartOfParagraph,
 8761        window: &mut Window,
 8762        cx: &mut Context<Self>,
 8763    ) {
 8764        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8765            cx.propagate();
 8766            return;
 8767        }
 8768
 8769        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8770            s.move_heads_with(|map, head, _| {
 8771                (
 8772                    movement::start_of_paragraph(map, head, 1),
 8773                    SelectionGoal::None,
 8774                )
 8775            });
 8776        })
 8777    }
 8778
 8779    pub fn select_to_end_of_paragraph(
 8780        &mut self,
 8781        _: &SelectToEndOfParagraph,
 8782        window: &mut Window,
 8783        cx: &mut Context<Self>,
 8784    ) {
 8785        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8786            cx.propagate();
 8787            return;
 8788        }
 8789
 8790        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8791            s.move_heads_with(|map, head, _| {
 8792                (
 8793                    movement::end_of_paragraph(map, head, 1),
 8794                    SelectionGoal::None,
 8795                )
 8796            });
 8797        })
 8798    }
 8799
 8800    pub fn move_to_beginning(
 8801        &mut self,
 8802        _: &MoveToBeginning,
 8803        window: &mut Window,
 8804        cx: &mut Context<Self>,
 8805    ) {
 8806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8807            cx.propagate();
 8808            return;
 8809        }
 8810
 8811        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8812            s.select_ranges(vec![0..0]);
 8813        });
 8814    }
 8815
 8816    pub fn select_to_beginning(
 8817        &mut self,
 8818        _: &SelectToBeginning,
 8819        window: &mut Window,
 8820        cx: &mut Context<Self>,
 8821    ) {
 8822        let mut selection = self.selections.last::<Point>(cx);
 8823        selection.set_head(Point::zero(), SelectionGoal::None);
 8824
 8825        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8826            s.select(vec![selection]);
 8827        });
 8828    }
 8829
 8830    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8831        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8832            cx.propagate();
 8833            return;
 8834        }
 8835
 8836        let cursor = self.buffer.read(cx).read(cx).len();
 8837        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8838            s.select_ranges(vec![cursor..cursor])
 8839        });
 8840    }
 8841
 8842    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8843        self.nav_history = nav_history;
 8844    }
 8845
 8846    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8847        self.nav_history.as_ref()
 8848    }
 8849
 8850    fn push_to_nav_history(
 8851        &mut self,
 8852        cursor_anchor: Anchor,
 8853        new_position: Option<Point>,
 8854        cx: &mut Context<Self>,
 8855    ) {
 8856        if let Some(nav_history) = self.nav_history.as_mut() {
 8857            let buffer = self.buffer.read(cx).read(cx);
 8858            let cursor_position = cursor_anchor.to_point(&buffer);
 8859            let scroll_state = self.scroll_manager.anchor();
 8860            let scroll_top_row = scroll_state.top_row(&buffer);
 8861            drop(buffer);
 8862
 8863            if let Some(new_position) = new_position {
 8864                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8865                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8866                    return;
 8867                }
 8868            }
 8869
 8870            nav_history.push(
 8871                Some(NavigationData {
 8872                    cursor_anchor,
 8873                    cursor_position,
 8874                    scroll_anchor: scroll_state,
 8875                    scroll_top_row,
 8876                }),
 8877                cx,
 8878            );
 8879        }
 8880    }
 8881
 8882    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8883        let buffer = self.buffer.read(cx).snapshot(cx);
 8884        let mut selection = self.selections.first::<usize>(cx);
 8885        selection.set_head(buffer.len(), SelectionGoal::None);
 8886        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8887            s.select(vec![selection]);
 8888        });
 8889    }
 8890
 8891    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8892        let end = self.buffer.read(cx).read(cx).len();
 8893        self.change_selections(None, window, cx, |s| {
 8894            s.select_ranges(vec![0..end]);
 8895        });
 8896    }
 8897
 8898    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8899        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8900        let mut selections = self.selections.all::<Point>(cx);
 8901        let max_point = display_map.buffer_snapshot.max_point();
 8902        for selection in &mut selections {
 8903            let rows = selection.spanned_rows(true, &display_map);
 8904            selection.start = Point::new(rows.start.0, 0);
 8905            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8906            selection.reversed = false;
 8907        }
 8908        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8909            s.select(selections);
 8910        });
 8911    }
 8912
 8913    pub fn split_selection_into_lines(
 8914        &mut self,
 8915        _: &SplitSelectionIntoLines,
 8916        window: &mut Window,
 8917        cx: &mut Context<Self>,
 8918    ) {
 8919        let mut to_unfold = Vec::new();
 8920        let mut new_selection_ranges = Vec::new();
 8921        {
 8922            let selections = self.selections.all::<Point>(cx);
 8923            let buffer = self.buffer.read(cx).read(cx);
 8924            for selection in selections {
 8925                for row in selection.start.row..selection.end.row {
 8926                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8927                    new_selection_ranges.push(cursor..cursor);
 8928                }
 8929                new_selection_ranges.push(selection.end..selection.end);
 8930                to_unfold.push(selection.start..selection.end);
 8931            }
 8932        }
 8933        self.unfold_ranges(&to_unfold, true, true, cx);
 8934        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8935            s.select_ranges(new_selection_ranges);
 8936        });
 8937    }
 8938
 8939    pub fn add_selection_above(
 8940        &mut self,
 8941        _: &AddSelectionAbove,
 8942        window: &mut Window,
 8943        cx: &mut Context<Self>,
 8944    ) {
 8945        self.add_selection(true, window, cx);
 8946    }
 8947
 8948    pub fn add_selection_below(
 8949        &mut self,
 8950        _: &AddSelectionBelow,
 8951        window: &mut Window,
 8952        cx: &mut Context<Self>,
 8953    ) {
 8954        self.add_selection(false, window, cx);
 8955    }
 8956
 8957    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8958        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8959        let mut selections = self.selections.all::<Point>(cx);
 8960        let text_layout_details = self.text_layout_details(window);
 8961        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8962            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8963            let range = oldest_selection.display_range(&display_map).sorted();
 8964
 8965            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8966            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8967            let positions = start_x.min(end_x)..start_x.max(end_x);
 8968
 8969            selections.clear();
 8970            let mut stack = Vec::new();
 8971            for row in range.start.row().0..=range.end.row().0 {
 8972                if let Some(selection) = self.selections.build_columnar_selection(
 8973                    &display_map,
 8974                    DisplayRow(row),
 8975                    &positions,
 8976                    oldest_selection.reversed,
 8977                    &text_layout_details,
 8978                ) {
 8979                    stack.push(selection.id);
 8980                    selections.push(selection);
 8981                }
 8982            }
 8983
 8984            if above {
 8985                stack.reverse();
 8986            }
 8987
 8988            AddSelectionsState { above, stack }
 8989        });
 8990
 8991        let last_added_selection = *state.stack.last().unwrap();
 8992        let mut new_selections = Vec::new();
 8993        if above == state.above {
 8994            let end_row = if above {
 8995                DisplayRow(0)
 8996            } else {
 8997                display_map.max_point().row()
 8998            };
 8999
 9000            'outer: for selection in selections {
 9001                if selection.id == last_added_selection {
 9002                    let range = selection.display_range(&display_map).sorted();
 9003                    debug_assert_eq!(range.start.row(), range.end.row());
 9004                    let mut row = range.start.row();
 9005                    let positions =
 9006                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9007                            px(start)..px(end)
 9008                        } else {
 9009                            let start_x =
 9010                                display_map.x_for_display_point(range.start, &text_layout_details);
 9011                            let end_x =
 9012                                display_map.x_for_display_point(range.end, &text_layout_details);
 9013                            start_x.min(end_x)..start_x.max(end_x)
 9014                        };
 9015
 9016                    while row != end_row {
 9017                        if above {
 9018                            row.0 -= 1;
 9019                        } else {
 9020                            row.0 += 1;
 9021                        }
 9022
 9023                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9024                            &display_map,
 9025                            row,
 9026                            &positions,
 9027                            selection.reversed,
 9028                            &text_layout_details,
 9029                        ) {
 9030                            state.stack.push(new_selection.id);
 9031                            if above {
 9032                                new_selections.push(new_selection);
 9033                                new_selections.push(selection);
 9034                            } else {
 9035                                new_selections.push(selection);
 9036                                new_selections.push(new_selection);
 9037                            }
 9038
 9039                            continue 'outer;
 9040                        }
 9041                    }
 9042                }
 9043
 9044                new_selections.push(selection);
 9045            }
 9046        } else {
 9047            new_selections = selections;
 9048            new_selections.retain(|s| s.id != last_added_selection);
 9049            state.stack.pop();
 9050        }
 9051
 9052        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9053            s.select(new_selections);
 9054        });
 9055        if state.stack.len() > 1 {
 9056            self.add_selections_state = Some(state);
 9057        }
 9058    }
 9059
 9060    pub fn select_next_match_internal(
 9061        &mut self,
 9062        display_map: &DisplaySnapshot,
 9063        replace_newest: bool,
 9064        autoscroll: Option<Autoscroll>,
 9065        window: &mut Window,
 9066        cx: &mut Context<Self>,
 9067    ) -> Result<()> {
 9068        fn select_next_match_ranges(
 9069            this: &mut Editor,
 9070            range: Range<usize>,
 9071            replace_newest: bool,
 9072            auto_scroll: Option<Autoscroll>,
 9073            window: &mut Window,
 9074            cx: &mut Context<Editor>,
 9075        ) {
 9076            this.unfold_ranges(&[range.clone()], false, true, cx);
 9077            this.change_selections(auto_scroll, window, cx, |s| {
 9078                if replace_newest {
 9079                    s.delete(s.newest_anchor().id);
 9080                }
 9081                s.insert_range(range.clone());
 9082            });
 9083        }
 9084
 9085        let buffer = &display_map.buffer_snapshot;
 9086        let mut selections = self.selections.all::<usize>(cx);
 9087        if let Some(mut select_next_state) = self.select_next_state.take() {
 9088            let query = &select_next_state.query;
 9089            if !select_next_state.done {
 9090                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9091                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9092                let mut next_selected_range = None;
 9093
 9094                let bytes_after_last_selection =
 9095                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9096                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9097                let query_matches = query
 9098                    .stream_find_iter(bytes_after_last_selection)
 9099                    .map(|result| (last_selection.end, result))
 9100                    .chain(
 9101                        query
 9102                            .stream_find_iter(bytes_before_first_selection)
 9103                            .map(|result| (0, result)),
 9104                    );
 9105
 9106                for (start_offset, query_match) in query_matches {
 9107                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9108                    let offset_range =
 9109                        start_offset + query_match.start()..start_offset + query_match.end();
 9110                    let display_range = offset_range.start.to_display_point(display_map)
 9111                        ..offset_range.end.to_display_point(display_map);
 9112
 9113                    if !select_next_state.wordwise
 9114                        || (!movement::is_inside_word(display_map, display_range.start)
 9115                            && !movement::is_inside_word(display_map, display_range.end))
 9116                    {
 9117                        // TODO: This is n^2, because we might check all the selections
 9118                        if !selections
 9119                            .iter()
 9120                            .any(|selection| selection.range().overlaps(&offset_range))
 9121                        {
 9122                            next_selected_range = Some(offset_range);
 9123                            break;
 9124                        }
 9125                    }
 9126                }
 9127
 9128                if let Some(next_selected_range) = next_selected_range {
 9129                    select_next_match_ranges(
 9130                        self,
 9131                        next_selected_range,
 9132                        replace_newest,
 9133                        autoscroll,
 9134                        window,
 9135                        cx,
 9136                    );
 9137                } else {
 9138                    select_next_state.done = true;
 9139                }
 9140            }
 9141
 9142            self.select_next_state = Some(select_next_state);
 9143        } else {
 9144            let mut only_carets = true;
 9145            let mut same_text_selected = true;
 9146            let mut selected_text = None;
 9147
 9148            let mut selections_iter = selections.iter().peekable();
 9149            while let Some(selection) = selections_iter.next() {
 9150                if selection.start != selection.end {
 9151                    only_carets = false;
 9152                }
 9153
 9154                if same_text_selected {
 9155                    if selected_text.is_none() {
 9156                        selected_text =
 9157                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9158                    }
 9159
 9160                    if let Some(next_selection) = selections_iter.peek() {
 9161                        if next_selection.range().len() == selection.range().len() {
 9162                            let next_selected_text = buffer
 9163                                .text_for_range(next_selection.range())
 9164                                .collect::<String>();
 9165                            if Some(next_selected_text) != selected_text {
 9166                                same_text_selected = false;
 9167                                selected_text = None;
 9168                            }
 9169                        } else {
 9170                            same_text_selected = false;
 9171                            selected_text = None;
 9172                        }
 9173                    }
 9174                }
 9175            }
 9176
 9177            if only_carets {
 9178                for selection in &mut selections {
 9179                    let word_range = movement::surrounding_word(
 9180                        display_map,
 9181                        selection.start.to_display_point(display_map),
 9182                    );
 9183                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9184                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9185                    selection.goal = SelectionGoal::None;
 9186                    selection.reversed = false;
 9187                    select_next_match_ranges(
 9188                        self,
 9189                        selection.start..selection.end,
 9190                        replace_newest,
 9191                        autoscroll,
 9192                        window,
 9193                        cx,
 9194                    );
 9195                }
 9196
 9197                if selections.len() == 1 {
 9198                    let selection = selections
 9199                        .last()
 9200                        .expect("ensured that there's only one selection");
 9201                    let query = buffer
 9202                        .text_for_range(selection.start..selection.end)
 9203                        .collect::<String>();
 9204                    let is_empty = query.is_empty();
 9205                    let select_state = SelectNextState {
 9206                        query: AhoCorasick::new(&[query])?,
 9207                        wordwise: true,
 9208                        done: is_empty,
 9209                    };
 9210                    self.select_next_state = Some(select_state);
 9211                } else {
 9212                    self.select_next_state = None;
 9213                }
 9214            } else if let Some(selected_text) = selected_text {
 9215                self.select_next_state = Some(SelectNextState {
 9216                    query: AhoCorasick::new(&[selected_text])?,
 9217                    wordwise: false,
 9218                    done: false,
 9219                });
 9220                self.select_next_match_internal(
 9221                    display_map,
 9222                    replace_newest,
 9223                    autoscroll,
 9224                    window,
 9225                    cx,
 9226                )?;
 9227            }
 9228        }
 9229        Ok(())
 9230    }
 9231
 9232    pub fn select_all_matches(
 9233        &mut self,
 9234        _action: &SelectAllMatches,
 9235        window: &mut Window,
 9236        cx: &mut Context<Self>,
 9237    ) -> Result<()> {
 9238        self.push_to_selection_history();
 9239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9240
 9241        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9242        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9243            return Ok(());
 9244        };
 9245        if select_next_state.done {
 9246            return Ok(());
 9247        }
 9248
 9249        let mut new_selections = self.selections.all::<usize>(cx);
 9250
 9251        let buffer = &display_map.buffer_snapshot;
 9252        let query_matches = select_next_state
 9253            .query
 9254            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9255
 9256        for query_match in query_matches {
 9257            let query_match = query_match.unwrap(); // can only fail due to I/O
 9258            let offset_range = query_match.start()..query_match.end();
 9259            let display_range = offset_range.start.to_display_point(&display_map)
 9260                ..offset_range.end.to_display_point(&display_map);
 9261
 9262            if !select_next_state.wordwise
 9263                || (!movement::is_inside_word(&display_map, display_range.start)
 9264                    && !movement::is_inside_word(&display_map, display_range.end))
 9265            {
 9266                self.selections.change_with(cx, |selections| {
 9267                    new_selections.push(Selection {
 9268                        id: selections.new_selection_id(),
 9269                        start: offset_range.start,
 9270                        end: offset_range.end,
 9271                        reversed: false,
 9272                        goal: SelectionGoal::None,
 9273                    });
 9274                });
 9275            }
 9276        }
 9277
 9278        new_selections.sort_by_key(|selection| selection.start);
 9279        let mut ix = 0;
 9280        while ix + 1 < new_selections.len() {
 9281            let current_selection = &new_selections[ix];
 9282            let next_selection = &new_selections[ix + 1];
 9283            if current_selection.range().overlaps(&next_selection.range()) {
 9284                if current_selection.id < next_selection.id {
 9285                    new_selections.remove(ix + 1);
 9286                } else {
 9287                    new_selections.remove(ix);
 9288                }
 9289            } else {
 9290                ix += 1;
 9291            }
 9292        }
 9293
 9294        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9295
 9296        for selection in new_selections.iter_mut() {
 9297            selection.reversed = reversed;
 9298        }
 9299
 9300        select_next_state.done = true;
 9301        self.unfold_ranges(
 9302            &new_selections
 9303                .iter()
 9304                .map(|selection| selection.range())
 9305                .collect::<Vec<_>>(),
 9306            false,
 9307            false,
 9308            cx,
 9309        );
 9310        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9311            selections.select(new_selections)
 9312        });
 9313
 9314        Ok(())
 9315    }
 9316
 9317    pub fn select_next(
 9318        &mut self,
 9319        action: &SelectNext,
 9320        window: &mut Window,
 9321        cx: &mut Context<Self>,
 9322    ) -> Result<()> {
 9323        self.push_to_selection_history();
 9324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9325        self.select_next_match_internal(
 9326            &display_map,
 9327            action.replace_newest,
 9328            Some(Autoscroll::newest()),
 9329            window,
 9330            cx,
 9331        )?;
 9332        Ok(())
 9333    }
 9334
 9335    pub fn select_previous(
 9336        &mut self,
 9337        action: &SelectPrevious,
 9338        window: &mut Window,
 9339        cx: &mut Context<Self>,
 9340    ) -> Result<()> {
 9341        self.push_to_selection_history();
 9342        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9343        let buffer = &display_map.buffer_snapshot;
 9344        let mut selections = self.selections.all::<usize>(cx);
 9345        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9346            let query = &select_prev_state.query;
 9347            if !select_prev_state.done {
 9348                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9349                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9350                let mut next_selected_range = None;
 9351                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9352                let bytes_before_last_selection =
 9353                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9354                let bytes_after_first_selection =
 9355                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9356                let query_matches = query
 9357                    .stream_find_iter(bytes_before_last_selection)
 9358                    .map(|result| (last_selection.start, result))
 9359                    .chain(
 9360                        query
 9361                            .stream_find_iter(bytes_after_first_selection)
 9362                            .map(|result| (buffer.len(), result)),
 9363                    );
 9364                for (end_offset, query_match) in query_matches {
 9365                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9366                    let offset_range =
 9367                        end_offset - query_match.end()..end_offset - query_match.start();
 9368                    let display_range = offset_range.start.to_display_point(&display_map)
 9369                        ..offset_range.end.to_display_point(&display_map);
 9370
 9371                    if !select_prev_state.wordwise
 9372                        || (!movement::is_inside_word(&display_map, display_range.start)
 9373                            && !movement::is_inside_word(&display_map, display_range.end))
 9374                    {
 9375                        next_selected_range = Some(offset_range);
 9376                        break;
 9377                    }
 9378                }
 9379
 9380                if let Some(next_selected_range) = next_selected_range {
 9381                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9382                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9383                        if action.replace_newest {
 9384                            s.delete(s.newest_anchor().id);
 9385                        }
 9386                        s.insert_range(next_selected_range);
 9387                    });
 9388                } else {
 9389                    select_prev_state.done = true;
 9390                }
 9391            }
 9392
 9393            self.select_prev_state = Some(select_prev_state);
 9394        } else {
 9395            let mut only_carets = true;
 9396            let mut same_text_selected = true;
 9397            let mut selected_text = None;
 9398
 9399            let mut selections_iter = selections.iter().peekable();
 9400            while let Some(selection) = selections_iter.next() {
 9401                if selection.start != selection.end {
 9402                    only_carets = false;
 9403                }
 9404
 9405                if same_text_selected {
 9406                    if selected_text.is_none() {
 9407                        selected_text =
 9408                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9409                    }
 9410
 9411                    if let Some(next_selection) = selections_iter.peek() {
 9412                        if next_selection.range().len() == selection.range().len() {
 9413                            let next_selected_text = buffer
 9414                                .text_for_range(next_selection.range())
 9415                                .collect::<String>();
 9416                            if Some(next_selected_text) != selected_text {
 9417                                same_text_selected = false;
 9418                                selected_text = None;
 9419                            }
 9420                        } else {
 9421                            same_text_selected = false;
 9422                            selected_text = None;
 9423                        }
 9424                    }
 9425                }
 9426            }
 9427
 9428            if only_carets {
 9429                for selection in &mut selections {
 9430                    let word_range = movement::surrounding_word(
 9431                        &display_map,
 9432                        selection.start.to_display_point(&display_map),
 9433                    );
 9434                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9435                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9436                    selection.goal = SelectionGoal::None;
 9437                    selection.reversed = false;
 9438                }
 9439                if selections.len() == 1 {
 9440                    let selection = selections
 9441                        .last()
 9442                        .expect("ensured that there's only one selection");
 9443                    let query = buffer
 9444                        .text_for_range(selection.start..selection.end)
 9445                        .collect::<String>();
 9446                    let is_empty = query.is_empty();
 9447                    let select_state = SelectNextState {
 9448                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9449                        wordwise: true,
 9450                        done: is_empty,
 9451                    };
 9452                    self.select_prev_state = Some(select_state);
 9453                } else {
 9454                    self.select_prev_state = None;
 9455                }
 9456
 9457                self.unfold_ranges(
 9458                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9459                    false,
 9460                    true,
 9461                    cx,
 9462                );
 9463                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9464                    s.select(selections);
 9465                });
 9466            } else if let Some(selected_text) = selected_text {
 9467                self.select_prev_state = Some(SelectNextState {
 9468                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9469                    wordwise: false,
 9470                    done: false,
 9471                });
 9472                self.select_previous(action, window, cx)?;
 9473            }
 9474        }
 9475        Ok(())
 9476    }
 9477
 9478    pub fn toggle_comments(
 9479        &mut self,
 9480        action: &ToggleComments,
 9481        window: &mut Window,
 9482        cx: &mut Context<Self>,
 9483    ) {
 9484        if self.read_only(cx) {
 9485            return;
 9486        }
 9487        let text_layout_details = &self.text_layout_details(window);
 9488        self.transact(window, cx, |this, window, cx| {
 9489            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9490            let mut edits = Vec::new();
 9491            let mut selection_edit_ranges = Vec::new();
 9492            let mut last_toggled_row = None;
 9493            let snapshot = this.buffer.read(cx).read(cx);
 9494            let empty_str: Arc<str> = Arc::default();
 9495            let mut suffixes_inserted = Vec::new();
 9496            let ignore_indent = action.ignore_indent;
 9497
 9498            fn comment_prefix_range(
 9499                snapshot: &MultiBufferSnapshot,
 9500                row: MultiBufferRow,
 9501                comment_prefix: &str,
 9502                comment_prefix_whitespace: &str,
 9503                ignore_indent: bool,
 9504            ) -> Range<Point> {
 9505                let indent_size = if ignore_indent {
 9506                    0
 9507                } else {
 9508                    snapshot.indent_size_for_line(row).len
 9509                };
 9510
 9511                let start = Point::new(row.0, indent_size);
 9512
 9513                let mut line_bytes = snapshot
 9514                    .bytes_in_range(start..snapshot.max_point())
 9515                    .flatten()
 9516                    .copied();
 9517
 9518                // If this line currently begins with the line comment prefix, then record
 9519                // the range containing the prefix.
 9520                if line_bytes
 9521                    .by_ref()
 9522                    .take(comment_prefix.len())
 9523                    .eq(comment_prefix.bytes())
 9524                {
 9525                    // Include any whitespace that matches the comment prefix.
 9526                    let matching_whitespace_len = line_bytes
 9527                        .zip(comment_prefix_whitespace.bytes())
 9528                        .take_while(|(a, b)| a == b)
 9529                        .count() as u32;
 9530                    let end = Point::new(
 9531                        start.row,
 9532                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9533                    );
 9534                    start..end
 9535                } else {
 9536                    start..start
 9537                }
 9538            }
 9539
 9540            fn comment_suffix_range(
 9541                snapshot: &MultiBufferSnapshot,
 9542                row: MultiBufferRow,
 9543                comment_suffix: &str,
 9544                comment_suffix_has_leading_space: bool,
 9545            ) -> Range<Point> {
 9546                let end = Point::new(row.0, snapshot.line_len(row));
 9547                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9548
 9549                let mut line_end_bytes = snapshot
 9550                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9551                    .flatten()
 9552                    .copied();
 9553
 9554                let leading_space_len = if suffix_start_column > 0
 9555                    && line_end_bytes.next() == Some(b' ')
 9556                    && comment_suffix_has_leading_space
 9557                {
 9558                    1
 9559                } else {
 9560                    0
 9561                };
 9562
 9563                // If this line currently begins with the line comment prefix, then record
 9564                // the range containing the prefix.
 9565                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9566                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9567                    start..end
 9568                } else {
 9569                    end..end
 9570                }
 9571            }
 9572
 9573            // TODO: Handle selections that cross excerpts
 9574            for selection in &mut selections {
 9575                let start_column = snapshot
 9576                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9577                    .len;
 9578                let language = if let Some(language) =
 9579                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9580                {
 9581                    language
 9582                } else {
 9583                    continue;
 9584                };
 9585
 9586                selection_edit_ranges.clear();
 9587
 9588                // If multiple selections contain a given row, avoid processing that
 9589                // row more than once.
 9590                let mut start_row = MultiBufferRow(selection.start.row);
 9591                if last_toggled_row == Some(start_row) {
 9592                    start_row = start_row.next_row();
 9593                }
 9594                let end_row =
 9595                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9596                        MultiBufferRow(selection.end.row - 1)
 9597                    } else {
 9598                        MultiBufferRow(selection.end.row)
 9599                    };
 9600                last_toggled_row = Some(end_row);
 9601
 9602                if start_row > end_row {
 9603                    continue;
 9604                }
 9605
 9606                // If the language has line comments, toggle those.
 9607                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9608
 9609                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9610                if ignore_indent {
 9611                    full_comment_prefixes = full_comment_prefixes
 9612                        .into_iter()
 9613                        .map(|s| Arc::from(s.trim_end()))
 9614                        .collect();
 9615                }
 9616
 9617                if !full_comment_prefixes.is_empty() {
 9618                    let first_prefix = full_comment_prefixes
 9619                        .first()
 9620                        .expect("prefixes is non-empty");
 9621                    let prefix_trimmed_lengths = full_comment_prefixes
 9622                        .iter()
 9623                        .map(|p| p.trim_end_matches(' ').len())
 9624                        .collect::<SmallVec<[usize; 4]>>();
 9625
 9626                    let mut all_selection_lines_are_comments = true;
 9627
 9628                    for row in start_row.0..=end_row.0 {
 9629                        let row = MultiBufferRow(row);
 9630                        if start_row < end_row && snapshot.is_line_blank(row) {
 9631                            continue;
 9632                        }
 9633
 9634                        let prefix_range = full_comment_prefixes
 9635                            .iter()
 9636                            .zip(prefix_trimmed_lengths.iter().copied())
 9637                            .map(|(prefix, trimmed_prefix_len)| {
 9638                                comment_prefix_range(
 9639                                    snapshot.deref(),
 9640                                    row,
 9641                                    &prefix[..trimmed_prefix_len],
 9642                                    &prefix[trimmed_prefix_len..],
 9643                                    ignore_indent,
 9644                                )
 9645                            })
 9646                            .max_by_key(|range| range.end.column - range.start.column)
 9647                            .expect("prefixes is non-empty");
 9648
 9649                        if prefix_range.is_empty() {
 9650                            all_selection_lines_are_comments = false;
 9651                        }
 9652
 9653                        selection_edit_ranges.push(prefix_range);
 9654                    }
 9655
 9656                    if all_selection_lines_are_comments {
 9657                        edits.extend(
 9658                            selection_edit_ranges
 9659                                .iter()
 9660                                .cloned()
 9661                                .map(|range| (range, empty_str.clone())),
 9662                        );
 9663                    } else {
 9664                        let min_column = selection_edit_ranges
 9665                            .iter()
 9666                            .map(|range| range.start.column)
 9667                            .min()
 9668                            .unwrap_or(0);
 9669                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9670                            let position = Point::new(range.start.row, min_column);
 9671                            (position..position, first_prefix.clone())
 9672                        }));
 9673                    }
 9674                } else if let Some((full_comment_prefix, comment_suffix)) =
 9675                    language.block_comment_delimiters()
 9676                {
 9677                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9678                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9679                    let prefix_range = comment_prefix_range(
 9680                        snapshot.deref(),
 9681                        start_row,
 9682                        comment_prefix,
 9683                        comment_prefix_whitespace,
 9684                        ignore_indent,
 9685                    );
 9686                    let suffix_range = comment_suffix_range(
 9687                        snapshot.deref(),
 9688                        end_row,
 9689                        comment_suffix.trim_start_matches(' '),
 9690                        comment_suffix.starts_with(' '),
 9691                    );
 9692
 9693                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9694                        edits.push((
 9695                            prefix_range.start..prefix_range.start,
 9696                            full_comment_prefix.clone(),
 9697                        ));
 9698                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9699                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9700                    } else {
 9701                        edits.push((prefix_range, empty_str.clone()));
 9702                        edits.push((suffix_range, empty_str.clone()));
 9703                    }
 9704                } else {
 9705                    continue;
 9706                }
 9707            }
 9708
 9709            drop(snapshot);
 9710            this.buffer.update(cx, |buffer, cx| {
 9711                buffer.edit(edits, None, cx);
 9712            });
 9713
 9714            // Adjust selections so that they end before any comment suffixes that
 9715            // were inserted.
 9716            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9717            let mut selections = this.selections.all::<Point>(cx);
 9718            let snapshot = this.buffer.read(cx).read(cx);
 9719            for selection in &mut selections {
 9720                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9721                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9722                        Ordering::Less => {
 9723                            suffixes_inserted.next();
 9724                            continue;
 9725                        }
 9726                        Ordering::Greater => break,
 9727                        Ordering::Equal => {
 9728                            if selection.end.column == snapshot.line_len(row) {
 9729                                if selection.is_empty() {
 9730                                    selection.start.column -= suffix_len as u32;
 9731                                }
 9732                                selection.end.column -= suffix_len as u32;
 9733                            }
 9734                            break;
 9735                        }
 9736                    }
 9737                }
 9738            }
 9739
 9740            drop(snapshot);
 9741            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9742                s.select(selections)
 9743            });
 9744
 9745            let selections = this.selections.all::<Point>(cx);
 9746            let selections_on_single_row = selections.windows(2).all(|selections| {
 9747                selections[0].start.row == selections[1].start.row
 9748                    && selections[0].end.row == selections[1].end.row
 9749                    && selections[0].start.row == selections[0].end.row
 9750            });
 9751            let selections_selecting = selections
 9752                .iter()
 9753                .any(|selection| selection.start != selection.end);
 9754            let advance_downwards = action.advance_downwards
 9755                && selections_on_single_row
 9756                && !selections_selecting
 9757                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9758
 9759            if advance_downwards {
 9760                let snapshot = this.buffer.read(cx).snapshot(cx);
 9761
 9762                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9763                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9764                        let mut point = display_point.to_point(display_snapshot);
 9765                        point.row += 1;
 9766                        point = snapshot.clip_point(point, Bias::Left);
 9767                        let display_point = point.to_display_point(display_snapshot);
 9768                        let goal = SelectionGoal::HorizontalPosition(
 9769                            display_snapshot
 9770                                .x_for_display_point(display_point, text_layout_details)
 9771                                .into(),
 9772                        );
 9773                        (display_point, goal)
 9774                    })
 9775                });
 9776            }
 9777        });
 9778    }
 9779
 9780    pub fn select_enclosing_symbol(
 9781        &mut self,
 9782        _: &SelectEnclosingSymbol,
 9783        window: &mut Window,
 9784        cx: &mut Context<Self>,
 9785    ) {
 9786        let buffer = self.buffer.read(cx).snapshot(cx);
 9787        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9788
 9789        fn update_selection(
 9790            selection: &Selection<usize>,
 9791            buffer_snap: &MultiBufferSnapshot,
 9792        ) -> Option<Selection<usize>> {
 9793            let cursor = selection.head();
 9794            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9795            for symbol in symbols.iter().rev() {
 9796                let start = symbol.range.start.to_offset(buffer_snap);
 9797                let end = symbol.range.end.to_offset(buffer_snap);
 9798                let new_range = start..end;
 9799                if start < selection.start || end > selection.end {
 9800                    return Some(Selection {
 9801                        id: selection.id,
 9802                        start: new_range.start,
 9803                        end: new_range.end,
 9804                        goal: SelectionGoal::None,
 9805                        reversed: selection.reversed,
 9806                    });
 9807                }
 9808            }
 9809            None
 9810        }
 9811
 9812        let mut selected_larger_symbol = false;
 9813        let new_selections = old_selections
 9814            .iter()
 9815            .map(|selection| match update_selection(selection, &buffer) {
 9816                Some(new_selection) => {
 9817                    if new_selection.range() != selection.range() {
 9818                        selected_larger_symbol = true;
 9819                    }
 9820                    new_selection
 9821                }
 9822                None => selection.clone(),
 9823            })
 9824            .collect::<Vec<_>>();
 9825
 9826        if selected_larger_symbol {
 9827            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9828                s.select(new_selections);
 9829            });
 9830        }
 9831    }
 9832
 9833    pub fn select_larger_syntax_node(
 9834        &mut self,
 9835        _: &SelectLargerSyntaxNode,
 9836        window: &mut Window,
 9837        cx: &mut Context<Self>,
 9838    ) {
 9839        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9840        let buffer = self.buffer.read(cx).snapshot(cx);
 9841        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9842
 9843        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9844        let mut selected_larger_node = false;
 9845        let new_selections = old_selections
 9846            .iter()
 9847            .map(|selection| {
 9848                let old_range = selection.start..selection.end;
 9849                let mut new_range = old_range.clone();
 9850                let mut new_node = None;
 9851                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9852                {
 9853                    new_node = Some(node);
 9854                    new_range = containing_range;
 9855                    if !display_map.intersects_fold(new_range.start)
 9856                        && !display_map.intersects_fold(new_range.end)
 9857                    {
 9858                        break;
 9859                    }
 9860                }
 9861
 9862                if let Some(node) = new_node {
 9863                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9864                    // nodes. Parent and grandparent are also logged because this operation will not
 9865                    // visit nodes that have the same range as their parent.
 9866                    log::info!("Node: {node:?}");
 9867                    let parent = node.parent();
 9868                    log::info!("Parent: {parent:?}");
 9869                    let grandparent = parent.and_then(|x| x.parent());
 9870                    log::info!("Grandparent: {grandparent:?}");
 9871                }
 9872
 9873                selected_larger_node |= new_range != old_range;
 9874                Selection {
 9875                    id: selection.id,
 9876                    start: new_range.start,
 9877                    end: new_range.end,
 9878                    goal: SelectionGoal::None,
 9879                    reversed: selection.reversed,
 9880                }
 9881            })
 9882            .collect::<Vec<_>>();
 9883
 9884        if selected_larger_node {
 9885            stack.push(old_selections);
 9886            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9887                s.select(new_selections);
 9888            });
 9889        }
 9890        self.select_larger_syntax_node_stack = stack;
 9891    }
 9892
 9893    pub fn select_smaller_syntax_node(
 9894        &mut self,
 9895        _: &SelectSmallerSyntaxNode,
 9896        window: &mut Window,
 9897        cx: &mut Context<Self>,
 9898    ) {
 9899        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9900        if let Some(selections) = stack.pop() {
 9901            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9902                s.select(selections.to_vec());
 9903            });
 9904        }
 9905        self.select_larger_syntax_node_stack = stack;
 9906    }
 9907
 9908    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9909        if !EditorSettings::get_global(cx).gutter.runnables {
 9910            self.clear_tasks();
 9911            return Task::ready(());
 9912        }
 9913        let project = self.project.as_ref().map(Entity::downgrade);
 9914        cx.spawn_in(window, |this, mut cx| async move {
 9915            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9916            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9917                return;
 9918            };
 9919            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9920                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9921            }) else {
 9922                return;
 9923            };
 9924
 9925            let hide_runnables = project
 9926                .update(&mut cx, |project, cx| {
 9927                    // Do not display any test indicators in non-dev server remote projects.
 9928                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9929                })
 9930                .unwrap_or(true);
 9931            if hide_runnables {
 9932                return;
 9933            }
 9934            let new_rows =
 9935                cx.background_executor()
 9936                    .spawn({
 9937                        let snapshot = display_snapshot.clone();
 9938                        async move {
 9939                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9940                        }
 9941                    })
 9942                    .await;
 9943
 9944            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9945            this.update(&mut cx, |this, _| {
 9946                this.clear_tasks();
 9947                for (key, value) in rows {
 9948                    this.insert_tasks(key, value);
 9949                }
 9950            })
 9951            .ok();
 9952        })
 9953    }
 9954    fn fetch_runnable_ranges(
 9955        snapshot: &DisplaySnapshot,
 9956        range: Range<Anchor>,
 9957    ) -> Vec<language::RunnableRange> {
 9958        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9959    }
 9960
 9961    fn runnable_rows(
 9962        project: Entity<Project>,
 9963        snapshot: DisplaySnapshot,
 9964        runnable_ranges: Vec<RunnableRange>,
 9965        mut cx: AsyncWindowContext,
 9966    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9967        runnable_ranges
 9968            .into_iter()
 9969            .filter_map(|mut runnable| {
 9970                let tasks = cx
 9971                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9972                    .ok()?;
 9973                if tasks.is_empty() {
 9974                    return None;
 9975                }
 9976
 9977                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9978
 9979                let row = snapshot
 9980                    .buffer_snapshot
 9981                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9982                    .1
 9983                    .start
 9984                    .row;
 9985
 9986                let context_range =
 9987                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9988                Some((
 9989                    (runnable.buffer_id, row),
 9990                    RunnableTasks {
 9991                        templates: tasks,
 9992                        offset: MultiBufferOffset(runnable.run_range.start),
 9993                        context_range,
 9994                        column: point.column,
 9995                        extra_variables: runnable.extra_captures,
 9996                    },
 9997                ))
 9998            })
 9999            .collect()
10000    }
10001
10002    fn templates_with_tags(
10003        project: &Entity<Project>,
10004        runnable: &mut Runnable,
10005        cx: &mut App,
10006    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10007        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10008            let (worktree_id, file) = project
10009                .buffer_for_id(runnable.buffer, cx)
10010                .and_then(|buffer| buffer.read(cx).file())
10011                .map(|file| (file.worktree_id(cx), file.clone()))
10012                .unzip();
10013
10014            (
10015                project.task_store().read(cx).task_inventory().cloned(),
10016                worktree_id,
10017                file,
10018            )
10019        });
10020
10021        let tags = mem::take(&mut runnable.tags);
10022        let mut tags: Vec<_> = tags
10023            .into_iter()
10024            .flat_map(|tag| {
10025                let tag = tag.0.clone();
10026                inventory
10027                    .as_ref()
10028                    .into_iter()
10029                    .flat_map(|inventory| {
10030                        inventory.read(cx).list_tasks(
10031                            file.clone(),
10032                            Some(runnable.language.clone()),
10033                            worktree_id,
10034                            cx,
10035                        )
10036                    })
10037                    .filter(move |(_, template)| {
10038                        template.tags.iter().any(|source_tag| source_tag == &tag)
10039                    })
10040            })
10041            .sorted_by_key(|(kind, _)| kind.to_owned())
10042            .collect();
10043        if let Some((leading_tag_source, _)) = tags.first() {
10044            // Strongest source wins; if we have worktree tag binding, prefer that to
10045            // global and language bindings;
10046            // if we have a global binding, prefer that to language binding.
10047            let first_mismatch = tags
10048                .iter()
10049                .position(|(tag_source, _)| tag_source != leading_tag_source);
10050            if let Some(index) = first_mismatch {
10051                tags.truncate(index);
10052            }
10053        }
10054
10055        tags
10056    }
10057
10058    pub fn move_to_enclosing_bracket(
10059        &mut self,
10060        _: &MoveToEnclosingBracket,
10061        window: &mut Window,
10062        cx: &mut Context<Self>,
10063    ) {
10064        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10065            s.move_offsets_with(|snapshot, selection| {
10066                let Some(enclosing_bracket_ranges) =
10067                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10068                else {
10069                    return;
10070                };
10071
10072                let mut best_length = usize::MAX;
10073                let mut best_inside = false;
10074                let mut best_in_bracket_range = false;
10075                let mut best_destination = None;
10076                for (open, close) in enclosing_bracket_ranges {
10077                    let close = close.to_inclusive();
10078                    let length = close.end() - open.start;
10079                    let inside = selection.start >= open.end && selection.end <= *close.start();
10080                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10081                        || close.contains(&selection.head());
10082
10083                    // If best is next to a bracket and current isn't, skip
10084                    if !in_bracket_range && best_in_bracket_range {
10085                        continue;
10086                    }
10087
10088                    // Prefer smaller lengths unless best is inside and current isn't
10089                    if length > best_length && (best_inside || !inside) {
10090                        continue;
10091                    }
10092
10093                    best_length = length;
10094                    best_inside = inside;
10095                    best_in_bracket_range = in_bracket_range;
10096                    best_destination = Some(
10097                        if close.contains(&selection.start) && close.contains(&selection.end) {
10098                            if inside {
10099                                open.end
10100                            } else {
10101                                open.start
10102                            }
10103                        } else if inside {
10104                            *close.start()
10105                        } else {
10106                            *close.end()
10107                        },
10108                    );
10109                }
10110
10111                if let Some(destination) = best_destination {
10112                    selection.collapse_to(destination, SelectionGoal::None);
10113                }
10114            })
10115        });
10116    }
10117
10118    pub fn undo_selection(
10119        &mut self,
10120        _: &UndoSelection,
10121        window: &mut Window,
10122        cx: &mut Context<Self>,
10123    ) {
10124        self.end_selection(window, cx);
10125        self.selection_history.mode = SelectionHistoryMode::Undoing;
10126        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10127            self.change_selections(None, window, cx, |s| {
10128                s.select_anchors(entry.selections.to_vec())
10129            });
10130            self.select_next_state = entry.select_next_state;
10131            self.select_prev_state = entry.select_prev_state;
10132            self.add_selections_state = entry.add_selections_state;
10133            self.request_autoscroll(Autoscroll::newest(), cx);
10134        }
10135        self.selection_history.mode = SelectionHistoryMode::Normal;
10136    }
10137
10138    pub fn redo_selection(
10139        &mut self,
10140        _: &RedoSelection,
10141        window: &mut Window,
10142        cx: &mut Context<Self>,
10143    ) {
10144        self.end_selection(window, cx);
10145        self.selection_history.mode = SelectionHistoryMode::Redoing;
10146        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10147            self.change_selections(None, window, cx, |s| {
10148                s.select_anchors(entry.selections.to_vec())
10149            });
10150            self.select_next_state = entry.select_next_state;
10151            self.select_prev_state = entry.select_prev_state;
10152            self.add_selections_state = entry.add_selections_state;
10153            self.request_autoscroll(Autoscroll::newest(), cx);
10154        }
10155        self.selection_history.mode = SelectionHistoryMode::Normal;
10156    }
10157
10158    pub fn expand_excerpts(
10159        &mut self,
10160        action: &ExpandExcerpts,
10161        _: &mut Window,
10162        cx: &mut Context<Self>,
10163    ) {
10164        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10165    }
10166
10167    pub fn expand_excerpts_down(
10168        &mut self,
10169        action: &ExpandExcerptsDown,
10170        _: &mut Window,
10171        cx: &mut Context<Self>,
10172    ) {
10173        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10174    }
10175
10176    pub fn expand_excerpts_up(
10177        &mut self,
10178        action: &ExpandExcerptsUp,
10179        _: &mut Window,
10180        cx: &mut Context<Self>,
10181    ) {
10182        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10183    }
10184
10185    pub fn expand_excerpts_for_direction(
10186        &mut self,
10187        lines: u32,
10188        direction: ExpandExcerptDirection,
10189
10190        cx: &mut Context<Self>,
10191    ) {
10192        let selections = self.selections.disjoint_anchors();
10193
10194        let lines = if lines == 0 {
10195            EditorSettings::get_global(cx).expand_excerpt_lines
10196        } else {
10197            lines
10198        };
10199
10200        self.buffer.update(cx, |buffer, cx| {
10201            let snapshot = buffer.snapshot(cx);
10202            let mut excerpt_ids = selections
10203                .iter()
10204                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10205                .collect::<Vec<_>>();
10206            excerpt_ids.sort();
10207            excerpt_ids.dedup();
10208            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10209        })
10210    }
10211
10212    pub fn expand_excerpt(
10213        &mut self,
10214        excerpt: ExcerptId,
10215        direction: ExpandExcerptDirection,
10216        cx: &mut Context<Self>,
10217    ) {
10218        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10219        self.buffer.update(cx, |buffer, cx| {
10220            buffer.expand_excerpts([excerpt], lines, direction, cx)
10221        })
10222    }
10223
10224    pub fn go_to_singleton_buffer_point(
10225        &mut self,
10226        point: Point,
10227        window: &mut Window,
10228        cx: &mut Context<Self>,
10229    ) {
10230        self.go_to_singleton_buffer_range(point..point, window, cx);
10231    }
10232
10233    pub fn go_to_singleton_buffer_range(
10234        &mut self,
10235        range: Range<Point>,
10236        window: &mut Window,
10237        cx: &mut Context<Self>,
10238    ) {
10239        let multibuffer = self.buffer().read(cx);
10240        let Some(buffer) = multibuffer.as_singleton() else {
10241            return;
10242        };
10243        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10244            return;
10245        };
10246        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10247            return;
10248        };
10249        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10250            s.select_anchor_ranges([start..end])
10251        });
10252    }
10253
10254    fn go_to_diagnostic(
10255        &mut self,
10256        _: &GoToDiagnostic,
10257        window: &mut Window,
10258        cx: &mut Context<Self>,
10259    ) {
10260        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10261    }
10262
10263    fn go_to_prev_diagnostic(
10264        &mut self,
10265        _: &GoToPrevDiagnostic,
10266        window: &mut Window,
10267        cx: &mut Context<Self>,
10268    ) {
10269        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10270    }
10271
10272    pub fn go_to_diagnostic_impl(
10273        &mut self,
10274        direction: Direction,
10275        window: &mut Window,
10276        cx: &mut Context<Self>,
10277    ) {
10278        let buffer = self.buffer.read(cx).snapshot(cx);
10279        let selection = self.selections.newest::<usize>(cx);
10280
10281        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10282        if direction == Direction::Next {
10283            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10284                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10285                    return;
10286                };
10287                self.activate_diagnostics(
10288                    buffer_id,
10289                    popover.local_diagnostic.diagnostic.group_id,
10290                    window,
10291                    cx,
10292                );
10293                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10294                    let primary_range_start = active_diagnostics.primary_range.start;
10295                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10296                        let mut new_selection = s.newest_anchor().clone();
10297                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10298                        s.select_anchors(vec![new_selection.clone()]);
10299                    });
10300                    self.refresh_inline_completion(false, true, window, cx);
10301                }
10302                return;
10303            }
10304        }
10305
10306        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10307            active_diagnostics
10308                .primary_range
10309                .to_offset(&buffer)
10310                .to_inclusive()
10311        });
10312        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10313            if active_primary_range.contains(&selection.head()) {
10314                *active_primary_range.start()
10315            } else {
10316                selection.head()
10317            }
10318        } else {
10319            selection.head()
10320        };
10321        let snapshot = self.snapshot(window, cx);
10322        loop {
10323            let mut diagnostics;
10324            if direction == Direction::Prev {
10325                diagnostics = buffer
10326                    .diagnostics_in_range::<usize>(0..search_start)
10327                    .collect::<Vec<_>>();
10328                diagnostics.reverse();
10329            } else {
10330                diagnostics = buffer
10331                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10332                    .collect::<Vec<_>>();
10333            };
10334            let group = diagnostics
10335                .into_iter()
10336                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10337                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10338                // be sorted in a stable way
10339                // skip until we are at current active diagnostic, if it exists
10340                .skip_while(|entry| {
10341                    let is_in_range = match direction {
10342                        Direction::Prev => entry.range.end > search_start,
10343                        Direction::Next => entry.range.start < search_start,
10344                    };
10345                    is_in_range
10346                        && self
10347                            .active_diagnostics
10348                            .as_ref()
10349                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10350                })
10351                .find_map(|entry| {
10352                    if entry.diagnostic.is_primary
10353                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10354                        && entry.range.start != entry.range.end
10355                        // if we match with the active diagnostic, skip it
10356                        && Some(entry.diagnostic.group_id)
10357                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10358                    {
10359                        Some((entry.range, entry.diagnostic.group_id))
10360                    } else {
10361                        None
10362                    }
10363                });
10364
10365            if let Some((primary_range, group_id)) = group {
10366                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10367                    return;
10368                };
10369                self.activate_diagnostics(buffer_id, group_id, window, cx);
10370                if self.active_diagnostics.is_some() {
10371                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10372                        s.select(vec![Selection {
10373                            id: selection.id,
10374                            start: primary_range.start,
10375                            end: primary_range.start,
10376                            reversed: false,
10377                            goal: SelectionGoal::None,
10378                        }]);
10379                    });
10380                    self.refresh_inline_completion(false, true, window, cx);
10381                }
10382                break;
10383            } else {
10384                // Cycle around to the start of the buffer, potentially moving back to the start of
10385                // the currently active diagnostic.
10386                active_primary_range.take();
10387                if direction == Direction::Prev {
10388                    if search_start == buffer.len() {
10389                        break;
10390                    } else {
10391                        search_start = buffer.len();
10392                    }
10393                } else if search_start == 0 {
10394                    break;
10395                } else {
10396                    search_start = 0;
10397                }
10398            }
10399        }
10400    }
10401
10402    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10403        let snapshot = self.snapshot(window, cx);
10404        let selection = self.selections.newest::<Point>(cx);
10405        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10406    }
10407
10408    fn go_to_hunk_after_position(
10409        &mut self,
10410        snapshot: &EditorSnapshot,
10411        position: Point,
10412        window: &mut Window,
10413        cx: &mut Context<Editor>,
10414    ) -> Option<MultiBufferDiffHunk> {
10415        let mut hunk = snapshot
10416            .buffer_snapshot
10417            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10418            .find(|hunk| hunk.row_range.start.0 > position.row);
10419        if hunk.is_none() {
10420            hunk = snapshot
10421                .buffer_snapshot
10422                .diff_hunks_in_range(Point::zero()..position)
10423                .find(|hunk| hunk.row_range.end.0 < position.row)
10424        }
10425        if let Some(hunk) = &hunk {
10426            let destination = Point::new(hunk.row_range.start.0, 0);
10427            self.unfold_ranges(&[destination..destination], false, false, cx);
10428            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10429                s.select_ranges(vec![destination..destination]);
10430            });
10431        }
10432
10433        hunk
10434    }
10435
10436    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10437        let snapshot = self.snapshot(window, cx);
10438        let selection = self.selections.newest::<Point>(cx);
10439        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10440    }
10441
10442    fn go_to_hunk_before_position(
10443        &mut self,
10444        snapshot: &EditorSnapshot,
10445        position: Point,
10446        window: &mut Window,
10447        cx: &mut Context<Editor>,
10448    ) -> Option<MultiBufferDiffHunk> {
10449        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10450        if hunk.is_none() {
10451            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10452        }
10453        if let Some(hunk) = &hunk {
10454            let destination = Point::new(hunk.row_range.start.0, 0);
10455            self.unfold_ranges(&[destination..destination], false, false, cx);
10456            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457                s.select_ranges(vec![destination..destination]);
10458            });
10459        }
10460
10461        hunk
10462    }
10463
10464    pub fn go_to_definition(
10465        &mut self,
10466        _: &GoToDefinition,
10467        window: &mut Window,
10468        cx: &mut Context<Self>,
10469    ) -> Task<Result<Navigated>> {
10470        let definition =
10471            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10472        cx.spawn_in(window, |editor, mut cx| async move {
10473            if definition.await? == Navigated::Yes {
10474                return Ok(Navigated::Yes);
10475            }
10476            match editor.update_in(&mut cx, |editor, window, cx| {
10477                editor.find_all_references(&FindAllReferences, window, cx)
10478            })? {
10479                Some(references) => references.await,
10480                None => Ok(Navigated::No),
10481            }
10482        })
10483    }
10484
10485    pub fn go_to_declaration(
10486        &mut self,
10487        _: &GoToDeclaration,
10488        window: &mut Window,
10489        cx: &mut Context<Self>,
10490    ) -> Task<Result<Navigated>> {
10491        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10492    }
10493
10494    pub fn go_to_declaration_split(
10495        &mut self,
10496        _: &GoToDeclaration,
10497        window: &mut Window,
10498        cx: &mut Context<Self>,
10499    ) -> Task<Result<Navigated>> {
10500        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10501    }
10502
10503    pub fn go_to_implementation(
10504        &mut self,
10505        _: &GoToImplementation,
10506        window: &mut Window,
10507        cx: &mut Context<Self>,
10508    ) -> Task<Result<Navigated>> {
10509        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10510    }
10511
10512    pub fn go_to_implementation_split(
10513        &mut self,
10514        _: &GoToImplementationSplit,
10515        window: &mut Window,
10516        cx: &mut Context<Self>,
10517    ) -> Task<Result<Navigated>> {
10518        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10519    }
10520
10521    pub fn go_to_type_definition(
10522        &mut self,
10523        _: &GoToTypeDefinition,
10524        window: &mut Window,
10525        cx: &mut Context<Self>,
10526    ) -> Task<Result<Navigated>> {
10527        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10528    }
10529
10530    pub fn go_to_definition_split(
10531        &mut self,
10532        _: &GoToDefinitionSplit,
10533        window: &mut Window,
10534        cx: &mut Context<Self>,
10535    ) -> Task<Result<Navigated>> {
10536        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10537    }
10538
10539    pub fn go_to_type_definition_split(
10540        &mut self,
10541        _: &GoToTypeDefinitionSplit,
10542        window: &mut Window,
10543        cx: &mut Context<Self>,
10544    ) -> Task<Result<Navigated>> {
10545        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10546    }
10547
10548    fn go_to_definition_of_kind(
10549        &mut self,
10550        kind: GotoDefinitionKind,
10551        split: bool,
10552        window: &mut Window,
10553        cx: &mut Context<Self>,
10554    ) -> Task<Result<Navigated>> {
10555        let Some(provider) = self.semantics_provider.clone() else {
10556            return Task::ready(Ok(Navigated::No));
10557        };
10558        let head = self.selections.newest::<usize>(cx).head();
10559        let buffer = self.buffer.read(cx);
10560        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10561            text_anchor
10562        } else {
10563            return Task::ready(Ok(Navigated::No));
10564        };
10565
10566        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10567            return Task::ready(Ok(Navigated::No));
10568        };
10569
10570        cx.spawn_in(window, |editor, mut cx| async move {
10571            let definitions = definitions.await?;
10572            let navigated = editor
10573                .update_in(&mut cx, |editor, window, cx| {
10574                    editor.navigate_to_hover_links(
10575                        Some(kind),
10576                        definitions
10577                            .into_iter()
10578                            .filter(|location| {
10579                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10580                            })
10581                            .map(HoverLink::Text)
10582                            .collect::<Vec<_>>(),
10583                        split,
10584                        window,
10585                        cx,
10586                    )
10587                })?
10588                .await?;
10589            anyhow::Ok(navigated)
10590        })
10591    }
10592
10593    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10594        let selection = self.selections.newest_anchor();
10595        let head = selection.head();
10596        let tail = selection.tail();
10597
10598        let Some((buffer, start_position)) =
10599            self.buffer.read(cx).text_anchor_for_position(head, cx)
10600        else {
10601            return;
10602        };
10603
10604        let end_position = if head != tail {
10605            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10606                return;
10607            };
10608            Some(pos)
10609        } else {
10610            None
10611        };
10612
10613        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10614            let url = if let Some(end_pos) = end_position {
10615                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10616            } else {
10617                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10618            };
10619
10620            if let Some(url) = url {
10621                editor.update(&mut cx, |_, cx| {
10622                    cx.open_url(&url);
10623                })
10624            } else {
10625                Ok(())
10626            }
10627        });
10628
10629        url_finder.detach();
10630    }
10631
10632    pub fn open_selected_filename(
10633        &mut self,
10634        _: &OpenSelectedFilename,
10635        window: &mut Window,
10636        cx: &mut Context<Self>,
10637    ) {
10638        let Some(workspace) = self.workspace() else {
10639            return;
10640        };
10641
10642        let position = self.selections.newest_anchor().head();
10643
10644        let Some((buffer, buffer_position)) =
10645            self.buffer.read(cx).text_anchor_for_position(position, cx)
10646        else {
10647            return;
10648        };
10649
10650        let project = self.project.clone();
10651
10652        cx.spawn_in(window, |_, mut cx| async move {
10653            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10654
10655            if let Some((_, path)) = result {
10656                workspace
10657                    .update_in(&mut cx, |workspace, window, cx| {
10658                        workspace.open_resolved_path(path, window, cx)
10659                    })?
10660                    .await?;
10661            }
10662            anyhow::Ok(())
10663        })
10664        .detach();
10665    }
10666
10667    pub(crate) fn navigate_to_hover_links(
10668        &mut self,
10669        kind: Option<GotoDefinitionKind>,
10670        mut definitions: Vec<HoverLink>,
10671        split: bool,
10672        window: &mut Window,
10673        cx: &mut Context<Editor>,
10674    ) -> Task<Result<Navigated>> {
10675        // If there is one definition, just open it directly
10676        if definitions.len() == 1 {
10677            let definition = definitions.pop().unwrap();
10678
10679            enum TargetTaskResult {
10680                Location(Option<Location>),
10681                AlreadyNavigated,
10682            }
10683
10684            let target_task = match definition {
10685                HoverLink::Text(link) => {
10686                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10687                }
10688                HoverLink::InlayHint(lsp_location, server_id) => {
10689                    let computation =
10690                        self.compute_target_location(lsp_location, server_id, window, cx);
10691                    cx.background_executor().spawn(async move {
10692                        let location = computation.await?;
10693                        Ok(TargetTaskResult::Location(location))
10694                    })
10695                }
10696                HoverLink::Url(url) => {
10697                    cx.open_url(&url);
10698                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10699                }
10700                HoverLink::File(path) => {
10701                    if let Some(workspace) = self.workspace() {
10702                        cx.spawn_in(window, |_, mut cx| async move {
10703                            workspace
10704                                .update_in(&mut cx, |workspace, window, cx| {
10705                                    workspace.open_resolved_path(path, window, cx)
10706                                })?
10707                                .await
10708                                .map(|_| TargetTaskResult::AlreadyNavigated)
10709                        })
10710                    } else {
10711                        Task::ready(Ok(TargetTaskResult::Location(None)))
10712                    }
10713                }
10714            };
10715            cx.spawn_in(window, |editor, mut cx| async move {
10716                let target = match target_task.await.context("target resolution task")? {
10717                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10718                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10719                    TargetTaskResult::Location(Some(target)) => target,
10720                };
10721
10722                editor.update_in(&mut cx, |editor, window, cx| {
10723                    let Some(workspace) = editor.workspace() else {
10724                        return Navigated::No;
10725                    };
10726                    let pane = workspace.read(cx).active_pane().clone();
10727
10728                    let range = target.range.to_point(target.buffer.read(cx));
10729                    let range = editor.range_for_match(&range);
10730                    let range = collapse_multiline_range(range);
10731
10732                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10733                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10734                    } else {
10735                        window.defer(cx, move |window, cx| {
10736                            let target_editor: Entity<Self> =
10737                                workspace.update(cx, |workspace, cx| {
10738                                    let pane = if split {
10739                                        workspace.adjacent_pane(window, cx)
10740                                    } else {
10741                                        workspace.active_pane().clone()
10742                                    };
10743
10744                                    workspace.open_project_item(
10745                                        pane,
10746                                        target.buffer.clone(),
10747                                        true,
10748                                        true,
10749                                        window,
10750                                        cx,
10751                                    )
10752                                });
10753                            target_editor.update(cx, |target_editor, cx| {
10754                                // When selecting a definition in a different buffer, disable the nav history
10755                                // to avoid creating a history entry at the previous cursor location.
10756                                pane.update(cx, |pane, _| pane.disable_history());
10757                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10758                                pane.update(cx, |pane, _| pane.enable_history());
10759                            });
10760                        });
10761                    }
10762                    Navigated::Yes
10763                })
10764            })
10765        } else if !definitions.is_empty() {
10766            cx.spawn_in(window, |editor, mut cx| async move {
10767                let (title, location_tasks, workspace) = editor
10768                    .update_in(&mut cx, |editor, window, cx| {
10769                        let tab_kind = match kind {
10770                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10771                            _ => "Definitions",
10772                        };
10773                        let title = definitions
10774                            .iter()
10775                            .find_map(|definition| match definition {
10776                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10777                                    let buffer = origin.buffer.read(cx);
10778                                    format!(
10779                                        "{} for {}",
10780                                        tab_kind,
10781                                        buffer
10782                                            .text_for_range(origin.range.clone())
10783                                            .collect::<String>()
10784                                    )
10785                                }),
10786                                HoverLink::InlayHint(_, _) => None,
10787                                HoverLink::Url(_) => None,
10788                                HoverLink::File(_) => None,
10789                            })
10790                            .unwrap_or(tab_kind.to_string());
10791                        let location_tasks = definitions
10792                            .into_iter()
10793                            .map(|definition| match definition {
10794                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10795                                HoverLink::InlayHint(lsp_location, server_id) => editor
10796                                    .compute_target_location(lsp_location, server_id, window, cx),
10797                                HoverLink::Url(_) => Task::ready(Ok(None)),
10798                                HoverLink::File(_) => Task::ready(Ok(None)),
10799                            })
10800                            .collect::<Vec<_>>();
10801                        (title, location_tasks, editor.workspace().clone())
10802                    })
10803                    .context("location tasks preparation")?;
10804
10805                let locations = future::join_all(location_tasks)
10806                    .await
10807                    .into_iter()
10808                    .filter_map(|location| location.transpose())
10809                    .collect::<Result<_>>()
10810                    .context("location tasks")?;
10811
10812                let Some(workspace) = workspace else {
10813                    return Ok(Navigated::No);
10814                };
10815                let opened = workspace
10816                    .update_in(&mut cx, |workspace, window, cx| {
10817                        Self::open_locations_in_multibuffer(
10818                            workspace,
10819                            locations,
10820                            title,
10821                            split,
10822                            MultibufferSelectionMode::First,
10823                            window,
10824                            cx,
10825                        )
10826                    })
10827                    .ok();
10828
10829                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10830            })
10831        } else {
10832            Task::ready(Ok(Navigated::No))
10833        }
10834    }
10835
10836    fn compute_target_location(
10837        &self,
10838        lsp_location: lsp::Location,
10839        server_id: LanguageServerId,
10840        window: &mut Window,
10841        cx: &mut Context<Self>,
10842    ) -> Task<anyhow::Result<Option<Location>>> {
10843        let Some(project) = self.project.clone() else {
10844            return Task::ready(Ok(None));
10845        };
10846
10847        cx.spawn_in(window, move |editor, mut cx| async move {
10848            let location_task = editor.update(&mut cx, |_, cx| {
10849                project.update(cx, |project, cx| {
10850                    let language_server_name = project
10851                        .language_server_statuses(cx)
10852                        .find(|(id, _)| server_id == *id)
10853                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10854                    language_server_name.map(|language_server_name| {
10855                        project.open_local_buffer_via_lsp(
10856                            lsp_location.uri.clone(),
10857                            server_id,
10858                            language_server_name,
10859                            cx,
10860                        )
10861                    })
10862                })
10863            })?;
10864            let location = match location_task {
10865                Some(task) => Some({
10866                    let target_buffer_handle = task.await.context("open local buffer")?;
10867                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10868                        let target_start = target_buffer
10869                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10870                        let target_end = target_buffer
10871                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10872                        target_buffer.anchor_after(target_start)
10873                            ..target_buffer.anchor_before(target_end)
10874                    })?;
10875                    Location {
10876                        buffer: target_buffer_handle,
10877                        range,
10878                    }
10879                }),
10880                None => None,
10881            };
10882            Ok(location)
10883        })
10884    }
10885
10886    pub fn find_all_references(
10887        &mut self,
10888        _: &FindAllReferences,
10889        window: &mut Window,
10890        cx: &mut Context<Self>,
10891    ) -> Option<Task<Result<Navigated>>> {
10892        let selection = self.selections.newest::<usize>(cx);
10893        let multi_buffer = self.buffer.read(cx);
10894        let head = selection.head();
10895
10896        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10897        let head_anchor = multi_buffer_snapshot.anchor_at(
10898            head,
10899            if head < selection.tail() {
10900                Bias::Right
10901            } else {
10902                Bias::Left
10903            },
10904        );
10905
10906        match self
10907            .find_all_references_task_sources
10908            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10909        {
10910            Ok(_) => {
10911                log::info!(
10912                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10913                );
10914                return None;
10915            }
10916            Err(i) => {
10917                self.find_all_references_task_sources.insert(i, head_anchor);
10918            }
10919        }
10920
10921        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10922        let workspace = self.workspace()?;
10923        let project = workspace.read(cx).project().clone();
10924        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10925        Some(cx.spawn_in(window, |editor, mut cx| async move {
10926            let _cleanup = defer({
10927                let mut cx = cx.clone();
10928                move || {
10929                    let _ = editor.update(&mut cx, |editor, _| {
10930                        if let Ok(i) =
10931                            editor
10932                                .find_all_references_task_sources
10933                                .binary_search_by(|anchor| {
10934                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10935                                })
10936                        {
10937                            editor.find_all_references_task_sources.remove(i);
10938                        }
10939                    });
10940                }
10941            });
10942
10943            let locations = references.await?;
10944            if locations.is_empty() {
10945                return anyhow::Ok(Navigated::No);
10946            }
10947
10948            workspace.update_in(&mut cx, |workspace, window, cx| {
10949                let title = locations
10950                    .first()
10951                    .as_ref()
10952                    .map(|location| {
10953                        let buffer = location.buffer.read(cx);
10954                        format!(
10955                            "References to `{}`",
10956                            buffer
10957                                .text_for_range(location.range.clone())
10958                                .collect::<String>()
10959                        )
10960                    })
10961                    .unwrap();
10962                Self::open_locations_in_multibuffer(
10963                    workspace,
10964                    locations,
10965                    title,
10966                    false,
10967                    MultibufferSelectionMode::First,
10968                    window,
10969                    cx,
10970                );
10971                Navigated::Yes
10972            })
10973        }))
10974    }
10975
10976    /// Opens a multibuffer with the given project locations in it
10977    pub fn open_locations_in_multibuffer(
10978        workspace: &mut Workspace,
10979        mut locations: Vec<Location>,
10980        title: String,
10981        split: bool,
10982        multibuffer_selection_mode: MultibufferSelectionMode,
10983        window: &mut Window,
10984        cx: &mut Context<Workspace>,
10985    ) {
10986        // If there are multiple definitions, open them in a multibuffer
10987        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10988        let mut locations = locations.into_iter().peekable();
10989        let mut ranges = Vec::new();
10990        let capability = workspace.project().read(cx).capability();
10991
10992        let excerpt_buffer = cx.new(|cx| {
10993            let mut multibuffer = MultiBuffer::new(capability);
10994            while let Some(location) = locations.next() {
10995                let buffer = location.buffer.read(cx);
10996                let mut ranges_for_buffer = Vec::new();
10997                let range = location.range.to_offset(buffer);
10998                ranges_for_buffer.push(range.clone());
10999
11000                while let Some(next_location) = locations.peek() {
11001                    if next_location.buffer == location.buffer {
11002                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11003                        locations.next();
11004                    } else {
11005                        break;
11006                    }
11007                }
11008
11009                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11010                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11011                    location.buffer.clone(),
11012                    ranges_for_buffer,
11013                    DEFAULT_MULTIBUFFER_CONTEXT,
11014                    cx,
11015                ))
11016            }
11017
11018            multibuffer.with_title(title)
11019        });
11020
11021        let editor = cx.new(|cx| {
11022            Editor::for_multibuffer(
11023                excerpt_buffer,
11024                Some(workspace.project().clone()),
11025                true,
11026                window,
11027                cx,
11028            )
11029        });
11030        editor.update(cx, |editor, cx| {
11031            match multibuffer_selection_mode {
11032                MultibufferSelectionMode::First => {
11033                    if let Some(first_range) = ranges.first() {
11034                        editor.change_selections(None, window, cx, |selections| {
11035                            selections.clear_disjoint();
11036                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11037                        });
11038                    }
11039                    editor.highlight_background::<Self>(
11040                        &ranges,
11041                        |theme| theme.editor_highlighted_line_background,
11042                        cx,
11043                    );
11044                }
11045                MultibufferSelectionMode::All => {
11046                    editor.change_selections(None, window, cx, |selections| {
11047                        selections.clear_disjoint();
11048                        selections.select_anchor_ranges(ranges);
11049                    });
11050                }
11051            }
11052            editor.register_buffers_with_language_servers(cx);
11053        });
11054
11055        let item = Box::new(editor);
11056        let item_id = item.item_id();
11057
11058        if split {
11059            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11060        } else {
11061            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11062                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11063                    pane.close_current_preview_item(window, cx)
11064                } else {
11065                    None
11066                }
11067            });
11068            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11069        }
11070        workspace.active_pane().update(cx, |pane, cx| {
11071            pane.set_preview_item_id(Some(item_id), cx);
11072        });
11073    }
11074
11075    pub fn rename(
11076        &mut self,
11077        _: &Rename,
11078        window: &mut Window,
11079        cx: &mut Context<Self>,
11080    ) -> Option<Task<Result<()>>> {
11081        use language::ToOffset as _;
11082
11083        let provider = self.semantics_provider.clone()?;
11084        let selection = self.selections.newest_anchor().clone();
11085        let (cursor_buffer, cursor_buffer_position) = self
11086            .buffer
11087            .read(cx)
11088            .text_anchor_for_position(selection.head(), cx)?;
11089        let (tail_buffer, cursor_buffer_position_end) = self
11090            .buffer
11091            .read(cx)
11092            .text_anchor_for_position(selection.tail(), cx)?;
11093        if tail_buffer != cursor_buffer {
11094            return None;
11095        }
11096
11097        let snapshot = cursor_buffer.read(cx).snapshot();
11098        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11099        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11100        let prepare_rename = provider
11101            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11102            .unwrap_or_else(|| Task::ready(Ok(None)));
11103        drop(snapshot);
11104
11105        Some(cx.spawn_in(window, |this, mut cx| async move {
11106            let rename_range = if let Some(range) = prepare_rename.await? {
11107                Some(range)
11108            } else {
11109                this.update(&mut cx, |this, cx| {
11110                    let buffer = this.buffer.read(cx).snapshot(cx);
11111                    let mut buffer_highlights = this
11112                        .document_highlights_for_position(selection.head(), &buffer)
11113                        .filter(|highlight| {
11114                            highlight.start.excerpt_id == selection.head().excerpt_id
11115                                && highlight.end.excerpt_id == selection.head().excerpt_id
11116                        });
11117                    buffer_highlights
11118                        .next()
11119                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11120                })?
11121            };
11122            if let Some(rename_range) = rename_range {
11123                this.update_in(&mut cx, |this, window, cx| {
11124                    let snapshot = cursor_buffer.read(cx).snapshot();
11125                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11126                    let cursor_offset_in_rename_range =
11127                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11128                    let cursor_offset_in_rename_range_end =
11129                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11130
11131                    this.take_rename(false, window, cx);
11132                    let buffer = this.buffer.read(cx).read(cx);
11133                    let cursor_offset = selection.head().to_offset(&buffer);
11134                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11135                    let rename_end = rename_start + rename_buffer_range.len();
11136                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11137                    let mut old_highlight_id = None;
11138                    let old_name: Arc<str> = buffer
11139                        .chunks(rename_start..rename_end, true)
11140                        .map(|chunk| {
11141                            if old_highlight_id.is_none() {
11142                                old_highlight_id = chunk.syntax_highlight_id;
11143                            }
11144                            chunk.text
11145                        })
11146                        .collect::<String>()
11147                        .into();
11148
11149                    drop(buffer);
11150
11151                    // Position the selection in the rename editor so that it matches the current selection.
11152                    this.show_local_selections = false;
11153                    let rename_editor = cx.new(|cx| {
11154                        let mut editor = Editor::single_line(window, cx);
11155                        editor.buffer.update(cx, |buffer, cx| {
11156                            buffer.edit([(0..0, old_name.clone())], None, cx)
11157                        });
11158                        let rename_selection_range = match cursor_offset_in_rename_range
11159                            .cmp(&cursor_offset_in_rename_range_end)
11160                        {
11161                            Ordering::Equal => {
11162                                editor.select_all(&SelectAll, window, cx);
11163                                return editor;
11164                            }
11165                            Ordering::Less => {
11166                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11167                            }
11168                            Ordering::Greater => {
11169                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11170                            }
11171                        };
11172                        if rename_selection_range.end > old_name.len() {
11173                            editor.select_all(&SelectAll, window, cx);
11174                        } else {
11175                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11176                                s.select_ranges([rename_selection_range]);
11177                            });
11178                        }
11179                        editor
11180                    });
11181                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11182                        if e == &EditorEvent::Focused {
11183                            cx.emit(EditorEvent::FocusedIn)
11184                        }
11185                    })
11186                    .detach();
11187
11188                    let write_highlights =
11189                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11190                    let read_highlights =
11191                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11192                    let ranges = write_highlights
11193                        .iter()
11194                        .flat_map(|(_, ranges)| ranges.iter())
11195                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11196                        .cloned()
11197                        .collect();
11198
11199                    this.highlight_text::<Rename>(
11200                        ranges,
11201                        HighlightStyle {
11202                            fade_out: Some(0.6),
11203                            ..Default::default()
11204                        },
11205                        cx,
11206                    );
11207                    let rename_focus_handle = rename_editor.focus_handle(cx);
11208                    window.focus(&rename_focus_handle);
11209                    let block_id = this.insert_blocks(
11210                        [BlockProperties {
11211                            style: BlockStyle::Flex,
11212                            placement: BlockPlacement::Below(range.start),
11213                            height: 1,
11214                            render: Arc::new({
11215                                let rename_editor = rename_editor.clone();
11216                                move |cx: &mut BlockContext| {
11217                                    let mut text_style = cx.editor_style.text.clone();
11218                                    if let Some(highlight_style) = old_highlight_id
11219                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11220                                    {
11221                                        text_style = text_style.highlight(highlight_style);
11222                                    }
11223                                    div()
11224                                        .block_mouse_down()
11225                                        .pl(cx.anchor_x)
11226                                        .child(EditorElement::new(
11227                                            &rename_editor,
11228                                            EditorStyle {
11229                                                background: cx.theme().system().transparent,
11230                                                local_player: cx.editor_style.local_player,
11231                                                text: text_style,
11232                                                scrollbar_width: cx.editor_style.scrollbar_width,
11233                                                syntax: cx.editor_style.syntax.clone(),
11234                                                status: cx.editor_style.status.clone(),
11235                                                inlay_hints_style: HighlightStyle {
11236                                                    font_weight: Some(FontWeight::BOLD),
11237                                                    ..make_inlay_hints_style(cx.app)
11238                                                },
11239                                                inline_completion_styles: make_suggestion_styles(
11240                                                    cx.app,
11241                                                ),
11242                                                ..EditorStyle::default()
11243                                            },
11244                                        ))
11245                                        .into_any_element()
11246                                }
11247                            }),
11248                            priority: 0,
11249                        }],
11250                        Some(Autoscroll::fit()),
11251                        cx,
11252                    )[0];
11253                    this.pending_rename = Some(RenameState {
11254                        range,
11255                        old_name,
11256                        editor: rename_editor,
11257                        block_id,
11258                    });
11259                })?;
11260            }
11261
11262            Ok(())
11263        }))
11264    }
11265
11266    pub fn confirm_rename(
11267        &mut self,
11268        _: &ConfirmRename,
11269        window: &mut Window,
11270        cx: &mut Context<Self>,
11271    ) -> Option<Task<Result<()>>> {
11272        let rename = self.take_rename(false, window, cx)?;
11273        let workspace = self.workspace()?.downgrade();
11274        let (buffer, start) = self
11275            .buffer
11276            .read(cx)
11277            .text_anchor_for_position(rename.range.start, cx)?;
11278        let (end_buffer, _) = self
11279            .buffer
11280            .read(cx)
11281            .text_anchor_for_position(rename.range.end, cx)?;
11282        if buffer != end_buffer {
11283            return None;
11284        }
11285
11286        let old_name = rename.old_name;
11287        let new_name = rename.editor.read(cx).text(cx);
11288
11289        let rename = self.semantics_provider.as_ref()?.perform_rename(
11290            &buffer,
11291            start,
11292            new_name.clone(),
11293            cx,
11294        )?;
11295
11296        Some(cx.spawn_in(window, |editor, mut cx| async move {
11297            let project_transaction = rename.await?;
11298            Self::open_project_transaction(
11299                &editor,
11300                workspace,
11301                project_transaction,
11302                format!("Rename: {}{}", old_name, new_name),
11303                cx.clone(),
11304            )
11305            .await?;
11306
11307            editor.update(&mut cx, |editor, cx| {
11308                editor.refresh_document_highlights(cx);
11309            })?;
11310            Ok(())
11311        }))
11312    }
11313
11314    fn take_rename(
11315        &mut self,
11316        moving_cursor: bool,
11317        window: &mut Window,
11318        cx: &mut Context<Self>,
11319    ) -> Option<RenameState> {
11320        let rename = self.pending_rename.take()?;
11321        if rename.editor.focus_handle(cx).is_focused(window) {
11322            window.focus(&self.focus_handle);
11323        }
11324
11325        self.remove_blocks(
11326            [rename.block_id].into_iter().collect(),
11327            Some(Autoscroll::fit()),
11328            cx,
11329        );
11330        self.clear_highlights::<Rename>(cx);
11331        self.show_local_selections = true;
11332
11333        if moving_cursor {
11334            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11335                editor.selections.newest::<usize>(cx).head()
11336            });
11337
11338            // Update the selection to match the position of the selection inside
11339            // the rename editor.
11340            let snapshot = self.buffer.read(cx).read(cx);
11341            let rename_range = rename.range.to_offset(&snapshot);
11342            let cursor_in_editor = snapshot
11343                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11344                .min(rename_range.end);
11345            drop(snapshot);
11346
11347            self.change_selections(None, window, cx, |s| {
11348                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11349            });
11350        } else {
11351            self.refresh_document_highlights(cx);
11352        }
11353
11354        Some(rename)
11355    }
11356
11357    pub fn pending_rename(&self) -> Option<&RenameState> {
11358        self.pending_rename.as_ref()
11359    }
11360
11361    fn format(
11362        &mut self,
11363        _: &Format,
11364        window: &mut Window,
11365        cx: &mut Context<Self>,
11366    ) -> Option<Task<Result<()>>> {
11367        let project = match &self.project {
11368            Some(project) => project.clone(),
11369            None => return None,
11370        };
11371
11372        Some(self.perform_format(
11373            project,
11374            FormatTrigger::Manual,
11375            FormatTarget::Buffers,
11376            window,
11377            cx,
11378        ))
11379    }
11380
11381    fn format_selections(
11382        &mut self,
11383        _: &FormatSelections,
11384        window: &mut Window,
11385        cx: &mut Context<Self>,
11386    ) -> Option<Task<Result<()>>> {
11387        let project = match &self.project {
11388            Some(project) => project.clone(),
11389            None => return None,
11390        };
11391
11392        let ranges = self
11393            .selections
11394            .all_adjusted(cx)
11395            .into_iter()
11396            .map(|selection| selection.range())
11397            .collect_vec();
11398
11399        Some(self.perform_format(
11400            project,
11401            FormatTrigger::Manual,
11402            FormatTarget::Ranges(ranges),
11403            window,
11404            cx,
11405        ))
11406    }
11407
11408    fn perform_format(
11409        &mut self,
11410        project: Entity<Project>,
11411        trigger: FormatTrigger,
11412        target: FormatTarget,
11413        window: &mut Window,
11414        cx: &mut Context<Self>,
11415    ) -> Task<Result<()>> {
11416        let buffer = self.buffer.clone();
11417        let (buffers, target) = match target {
11418            FormatTarget::Buffers => {
11419                let mut buffers = buffer.read(cx).all_buffers();
11420                if trigger == FormatTrigger::Save {
11421                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11422                }
11423                (buffers, LspFormatTarget::Buffers)
11424            }
11425            FormatTarget::Ranges(selection_ranges) => {
11426                let multi_buffer = buffer.read(cx);
11427                let snapshot = multi_buffer.read(cx);
11428                let mut buffers = HashSet::default();
11429                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11430                    BTreeMap::new();
11431                for selection_range in selection_ranges {
11432                    for (buffer, buffer_range, _) in
11433                        snapshot.range_to_buffer_ranges(selection_range)
11434                    {
11435                        let buffer_id = buffer.remote_id();
11436                        let start = buffer.anchor_before(buffer_range.start);
11437                        let end = buffer.anchor_after(buffer_range.end);
11438                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11439                        buffer_id_to_ranges
11440                            .entry(buffer_id)
11441                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11442                            .or_insert_with(|| vec![start..end]);
11443                    }
11444                }
11445                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11446            }
11447        };
11448
11449        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11450        let format = project.update(cx, |project, cx| {
11451            project.format(buffers, target, true, trigger, cx)
11452        });
11453
11454        cx.spawn_in(window, |_, mut cx| async move {
11455            let transaction = futures::select_biased! {
11456                () = timeout => {
11457                    log::warn!("timed out waiting for formatting");
11458                    None
11459                }
11460                transaction = format.log_err().fuse() => transaction,
11461            };
11462
11463            buffer
11464                .update(&mut cx, |buffer, cx| {
11465                    if let Some(transaction) = transaction {
11466                        if !buffer.is_singleton() {
11467                            buffer.push_transaction(&transaction.0, cx);
11468                        }
11469                    }
11470
11471                    cx.notify();
11472                })
11473                .ok();
11474
11475            Ok(())
11476        })
11477    }
11478
11479    fn restart_language_server(
11480        &mut self,
11481        _: &RestartLanguageServer,
11482        _: &mut Window,
11483        cx: &mut Context<Self>,
11484    ) {
11485        if let Some(project) = self.project.clone() {
11486            self.buffer.update(cx, |multi_buffer, cx| {
11487                project.update(cx, |project, cx| {
11488                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11489                });
11490            })
11491        }
11492    }
11493
11494    fn cancel_language_server_work(
11495        workspace: &mut Workspace,
11496        _: &actions::CancelLanguageServerWork,
11497        _: &mut Window,
11498        cx: &mut Context<Workspace>,
11499    ) {
11500        let project = workspace.project();
11501        let buffers = workspace
11502            .active_item(cx)
11503            .and_then(|item| item.act_as::<Editor>(cx))
11504            .map_or(HashSet::default(), |editor| {
11505                editor.read(cx).buffer.read(cx).all_buffers()
11506            });
11507        project.update(cx, |project, cx| {
11508            project.cancel_language_server_work_for_buffers(buffers, cx);
11509        });
11510    }
11511
11512    fn show_character_palette(
11513        &mut self,
11514        _: &ShowCharacterPalette,
11515        window: &mut Window,
11516        _: &mut Context<Self>,
11517    ) {
11518        window.show_character_palette();
11519    }
11520
11521    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11522        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11523            let buffer = self.buffer.read(cx).snapshot(cx);
11524            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11525            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11526            let is_valid = buffer
11527                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11528                .any(|entry| {
11529                    entry.diagnostic.is_primary
11530                        && !entry.range.is_empty()
11531                        && entry.range.start == primary_range_start
11532                        && entry.diagnostic.message == active_diagnostics.primary_message
11533                });
11534
11535            if is_valid != active_diagnostics.is_valid {
11536                active_diagnostics.is_valid = is_valid;
11537                let mut new_styles = HashMap::default();
11538                for (block_id, diagnostic) in &active_diagnostics.blocks {
11539                    new_styles.insert(
11540                        *block_id,
11541                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11542                    );
11543                }
11544                self.display_map.update(cx, |display_map, _cx| {
11545                    display_map.replace_blocks(new_styles)
11546                });
11547            }
11548        }
11549    }
11550
11551    fn activate_diagnostics(
11552        &mut self,
11553        buffer_id: BufferId,
11554        group_id: usize,
11555        window: &mut Window,
11556        cx: &mut Context<Self>,
11557    ) {
11558        self.dismiss_diagnostics(cx);
11559        let snapshot = self.snapshot(window, cx);
11560        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11561            let buffer = self.buffer.read(cx).snapshot(cx);
11562
11563            let mut primary_range = None;
11564            let mut primary_message = None;
11565            let diagnostic_group = buffer
11566                .diagnostic_group(buffer_id, group_id)
11567                .filter_map(|entry| {
11568                    let start = entry.range.start;
11569                    let end = entry.range.end;
11570                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11571                        && (start.row == end.row
11572                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11573                    {
11574                        return None;
11575                    }
11576                    if entry.diagnostic.is_primary {
11577                        primary_range = Some(entry.range.clone());
11578                        primary_message = Some(entry.diagnostic.message.clone());
11579                    }
11580                    Some(entry)
11581                })
11582                .collect::<Vec<_>>();
11583            let primary_range = primary_range?;
11584            let primary_message = primary_message?;
11585
11586            let blocks = display_map
11587                .insert_blocks(
11588                    diagnostic_group.iter().map(|entry| {
11589                        let diagnostic = entry.diagnostic.clone();
11590                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11591                        BlockProperties {
11592                            style: BlockStyle::Fixed,
11593                            placement: BlockPlacement::Below(
11594                                buffer.anchor_after(entry.range.start),
11595                            ),
11596                            height: message_height,
11597                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11598                            priority: 0,
11599                        }
11600                    }),
11601                    cx,
11602                )
11603                .into_iter()
11604                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11605                .collect();
11606
11607            Some(ActiveDiagnosticGroup {
11608                primary_range: buffer.anchor_before(primary_range.start)
11609                    ..buffer.anchor_after(primary_range.end),
11610                primary_message,
11611                group_id,
11612                blocks,
11613                is_valid: true,
11614            })
11615        });
11616    }
11617
11618    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11619        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11620            self.display_map.update(cx, |display_map, cx| {
11621                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11622            });
11623            cx.notify();
11624        }
11625    }
11626
11627    pub fn set_selections_from_remote(
11628        &mut self,
11629        selections: Vec<Selection<Anchor>>,
11630        pending_selection: Option<Selection<Anchor>>,
11631        window: &mut Window,
11632        cx: &mut Context<Self>,
11633    ) {
11634        let old_cursor_position = self.selections.newest_anchor().head();
11635        self.selections.change_with(cx, |s| {
11636            s.select_anchors(selections);
11637            if let Some(pending_selection) = pending_selection {
11638                s.set_pending(pending_selection, SelectMode::Character);
11639            } else {
11640                s.clear_pending();
11641            }
11642        });
11643        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11644    }
11645
11646    fn push_to_selection_history(&mut self) {
11647        self.selection_history.push(SelectionHistoryEntry {
11648            selections: self.selections.disjoint_anchors(),
11649            select_next_state: self.select_next_state.clone(),
11650            select_prev_state: self.select_prev_state.clone(),
11651            add_selections_state: self.add_selections_state.clone(),
11652        });
11653    }
11654
11655    pub fn transact(
11656        &mut self,
11657        window: &mut Window,
11658        cx: &mut Context<Self>,
11659        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11660    ) -> Option<TransactionId> {
11661        self.start_transaction_at(Instant::now(), window, cx);
11662        update(self, window, cx);
11663        self.end_transaction_at(Instant::now(), cx)
11664    }
11665
11666    pub fn start_transaction_at(
11667        &mut self,
11668        now: Instant,
11669        window: &mut Window,
11670        cx: &mut Context<Self>,
11671    ) {
11672        self.end_selection(window, cx);
11673        if let Some(tx_id) = self
11674            .buffer
11675            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11676        {
11677            self.selection_history
11678                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11679            cx.emit(EditorEvent::TransactionBegun {
11680                transaction_id: tx_id,
11681            })
11682        }
11683    }
11684
11685    pub fn end_transaction_at(
11686        &mut self,
11687        now: Instant,
11688        cx: &mut Context<Self>,
11689    ) -> Option<TransactionId> {
11690        if let Some(transaction_id) = self
11691            .buffer
11692            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11693        {
11694            if let Some((_, end_selections)) =
11695                self.selection_history.transaction_mut(transaction_id)
11696            {
11697                *end_selections = Some(self.selections.disjoint_anchors());
11698            } else {
11699                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11700            }
11701
11702            cx.emit(EditorEvent::Edited { transaction_id });
11703            Some(transaction_id)
11704        } else {
11705            None
11706        }
11707    }
11708
11709    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11710        if self.selection_mark_mode {
11711            self.change_selections(None, window, cx, |s| {
11712                s.move_with(|_, sel| {
11713                    sel.collapse_to(sel.head(), SelectionGoal::None);
11714                });
11715            })
11716        }
11717        self.selection_mark_mode = true;
11718        cx.notify();
11719    }
11720
11721    pub fn swap_selection_ends(
11722        &mut self,
11723        _: &actions::SwapSelectionEnds,
11724        window: &mut Window,
11725        cx: &mut Context<Self>,
11726    ) {
11727        self.change_selections(None, window, cx, |s| {
11728            s.move_with(|_, sel| {
11729                if sel.start != sel.end {
11730                    sel.reversed = !sel.reversed
11731                }
11732            });
11733        });
11734        self.request_autoscroll(Autoscroll::newest(), cx);
11735        cx.notify();
11736    }
11737
11738    pub fn toggle_fold(
11739        &mut self,
11740        _: &actions::ToggleFold,
11741        window: &mut Window,
11742        cx: &mut Context<Self>,
11743    ) {
11744        if self.is_singleton(cx) {
11745            let selection = self.selections.newest::<Point>(cx);
11746
11747            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11748            let range = if selection.is_empty() {
11749                let point = selection.head().to_display_point(&display_map);
11750                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11751                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11752                    .to_point(&display_map);
11753                start..end
11754            } else {
11755                selection.range()
11756            };
11757            if display_map.folds_in_range(range).next().is_some() {
11758                self.unfold_lines(&Default::default(), window, cx)
11759            } else {
11760                self.fold(&Default::default(), window, cx)
11761            }
11762        } else {
11763            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11764            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11765                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11766                .map(|(snapshot, _, _)| snapshot.remote_id())
11767                .collect();
11768
11769            for buffer_id in buffer_ids {
11770                if self.is_buffer_folded(buffer_id, cx) {
11771                    self.unfold_buffer(buffer_id, cx);
11772                } else {
11773                    self.fold_buffer(buffer_id, cx);
11774                }
11775            }
11776        }
11777    }
11778
11779    pub fn toggle_fold_recursive(
11780        &mut self,
11781        _: &actions::ToggleFoldRecursive,
11782        window: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        let selection = self.selections.newest::<Point>(cx);
11786
11787        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11788        let range = if selection.is_empty() {
11789            let point = selection.head().to_display_point(&display_map);
11790            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11791            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11792                .to_point(&display_map);
11793            start..end
11794        } else {
11795            selection.range()
11796        };
11797        if display_map.folds_in_range(range).next().is_some() {
11798            self.unfold_recursive(&Default::default(), window, cx)
11799        } else {
11800            self.fold_recursive(&Default::default(), window, cx)
11801        }
11802    }
11803
11804    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11805        if self.is_singleton(cx) {
11806            let mut to_fold = Vec::new();
11807            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11808            let selections = self.selections.all_adjusted(cx);
11809
11810            for selection in selections {
11811                let range = selection.range().sorted();
11812                let buffer_start_row = range.start.row;
11813
11814                if range.start.row != range.end.row {
11815                    let mut found = false;
11816                    let mut row = range.start.row;
11817                    while row <= range.end.row {
11818                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11819                        {
11820                            found = true;
11821                            row = crease.range().end.row + 1;
11822                            to_fold.push(crease);
11823                        } else {
11824                            row += 1
11825                        }
11826                    }
11827                    if found {
11828                        continue;
11829                    }
11830                }
11831
11832                for row in (0..=range.start.row).rev() {
11833                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11834                        if crease.range().end.row >= buffer_start_row {
11835                            to_fold.push(crease);
11836                            if row <= range.start.row {
11837                                break;
11838                            }
11839                        }
11840                    }
11841                }
11842            }
11843
11844            self.fold_creases(to_fold, true, window, cx);
11845        } else {
11846            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11847
11848            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11849                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11850                .map(|(snapshot, _, _)| snapshot.remote_id())
11851                .collect();
11852            for buffer_id in buffer_ids {
11853                self.fold_buffer(buffer_id, cx);
11854            }
11855        }
11856    }
11857
11858    fn fold_at_level(
11859        &mut self,
11860        fold_at: &FoldAtLevel,
11861        window: &mut Window,
11862        cx: &mut Context<Self>,
11863    ) {
11864        if !self.buffer.read(cx).is_singleton() {
11865            return;
11866        }
11867
11868        let fold_at_level = fold_at.0;
11869        let snapshot = self.buffer.read(cx).snapshot(cx);
11870        let mut to_fold = Vec::new();
11871        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11872
11873        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11874            while start_row < end_row {
11875                match self
11876                    .snapshot(window, cx)
11877                    .crease_for_buffer_row(MultiBufferRow(start_row))
11878                {
11879                    Some(crease) => {
11880                        let nested_start_row = crease.range().start.row + 1;
11881                        let nested_end_row = crease.range().end.row;
11882
11883                        if current_level < fold_at_level {
11884                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11885                        } else if current_level == fold_at_level {
11886                            to_fold.push(crease);
11887                        }
11888
11889                        start_row = nested_end_row + 1;
11890                    }
11891                    None => start_row += 1,
11892                }
11893            }
11894        }
11895
11896        self.fold_creases(to_fold, true, window, cx);
11897    }
11898
11899    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11900        if self.buffer.read(cx).is_singleton() {
11901            let mut fold_ranges = Vec::new();
11902            let snapshot = self.buffer.read(cx).snapshot(cx);
11903
11904            for row in 0..snapshot.max_row().0 {
11905                if let Some(foldable_range) = self
11906                    .snapshot(window, cx)
11907                    .crease_for_buffer_row(MultiBufferRow(row))
11908                {
11909                    fold_ranges.push(foldable_range);
11910                }
11911            }
11912
11913            self.fold_creases(fold_ranges, true, window, cx);
11914        } else {
11915            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11916                editor
11917                    .update_in(&mut cx, |editor, _, cx| {
11918                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11919                            editor.fold_buffer(buffer_id, cx);
11920                        }
11921                    })
11922                    .ok();
11923            });
11924        }
11925    }
11926
11927    pub fn fold_function_bodies(
11928        &mut self,
11929        _: &actions::FoldFunctionBodies,
11930        window: &mut Window,
11931        cx: &mut Context<Self>,
11932    ) {
11933        let snapshot = self.buffer.read(cx).snapshot(cx);
11934
11935        let ranges = snapshot
11936            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11937            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11938            .collect::<Vec<_>>();
11939
11940        let creases = ranges
11941            .into_iter()
11942            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11943            .collect();
11944
11945        self.fold_creases(creases, true, window, cx);
11946    }
11947
11948    pub fn fold_recursive(
11949        &mut self,
11950        _: &actions::FoldRecursive,
11951        window: &mut Window,
11952        cx: &mut Context<Self>,
11953    ) {
11954        let mut to_fold = Vec::new();
11955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11956        let selections = self.selections.all_adjusted(cx);
11957
11958        for selection in selections {
11959            let range = selection.range().sorted();
11960            let buffer_start_row = range.start.row;
11961
11962            if range.start.row != range.end.row {
11963                let mut found = false;
11964                for row in range.start.row..=range.end.row {
11965                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11966                        found = true;
11967                        to_fold.push(crease);
11968                    }
11969                }
11970                if found {
11971                    continue;
11972                }
11973            }
11974
11975            for row in (0..=range.start.row).rev() {
11976                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11977                    if crease.range().end.row >= buffer_start_row {
11978                        to_fold.push(crease);
11979                    } else {
11980                        break;
11981                    }
11982                }
11983            }
11984        }
11985
11986        self.fold_creases(to_fold, true, window, cx);
11987    }
11988
11989    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11990        let buffer_row = fold_at.buffer_row;
11991        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11992
11993        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11994            let autoscroll = self
11995                .selections
11996                .all::<Point>(cx)
11997                .iter()
11998                .any(|selection| crease.range().overlaps(&selection.range()));
11999
12000            self.fold_creases(vec![crease], autoscroll, window, cx);
12001        }
12002    }
12003
12004    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12005        if self.is_singleton(cx) {
12006            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12007            let buffer = &display_map.buffer_snapshot;
12008            let selections = self.selections.all::<Point>(cx);
12009            let ranges = selections
12010                .iter()
12011                .map(|s| {
12012                    let range = s.display_range(&display_map).sorted();
12013                    let mut start = range.start.to_point(&display_map);
12014                    let mut end = range.end.to_point(&display_map);
12015                    start.column = 0;
12016                    end.column = buffer.line_len(MultiBufferRow(end.row));
12017                    start..end
12018                })
12019                .collect::<Vec<_>>();
12020
12021            self.unfold_ranges(&ranges, true, true, cx);
12022        } else {
12023            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12024            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12025                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12026                .map(|(snapshot, _, _)| snapshot.remote_id())
12027                .collect();
12028            for buffer_id in buffer_ids {
12029                self.unfold_buffer(buffer_id, cx);
12030            }
12031        }
12032    }
12033
12034    pub fn unfold_recursive(
12035        &mut self,
12036        _: &UnfoldRecursive,
12037        _window: &mut Window,
12038        cx: &mut Context<Self>,
12039    ) {
12040        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12041        let selections = self.selections.all::<Point>(cx);
12042        let ranges = selections
12043            .iter()
12044            .map(|s| {
12045                let mut range = s.display_range(&display_map).sorted();
12046                *range.start.column_mut() = 0;
12047                *range.end.column_mut() = display_map.line_len(range.end.row());
12048                let start = range.start.to_point(&display_map);
12049                let end = range.end.to_point(&display_map);
12050                start..end
12051            })
12052            .collect::<Vec<_>>();
12053
12054        self.unfold_ranges(&ranges, true, true, cx);
12055    }
12056
12057    pub fn unfold_at(
12058        &mut self,
12059        unfold_at: &UnfoldAt,
12060        _window: &mut Window,
12061        cx: &mut Context<Self>,
12062    ) {
12063        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12064
12065        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12066            ..Point::new(
12067                unfold_at.buffer_row.0,
12068                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12069            );
12070
12071        let autoscroll = self
12072            .selections
12073            .all::<Point>(cx)
12074            .iter()
12075            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12076
12077        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12078    }
12079
12080    pub fn unfold_all(
12081        &mut self,
12082        _: &actions::UnfoldAll,
12083        _window: &mut Window,
12084        cx: &mut Context<Self>,
12085    ) {
12086        if self.buffer.read(cx).is_singleton() {
12087            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12088            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12089        } else {
12090            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12091                editor
12092                    .update(&mut cx, |editor, cx| {
12093                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12094                            editor.unfold_buffer(buffer_id, cx);
12095                        }
12096                    })
12097                    .ok();
12098            });
12099        }
12100    }
12101
12102    pub fn fold_selected_ranges(
12103        &mut self,
12104        _: &FoldSelectedRanges,
12105        window: &mut Window,
12106        cx: &mut Context<Self>,
12107    ) {
12108        let selections = self.selections.all::<Point>(cx);
12109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12110        let line_mode = self.selections.line_mode;
12111        let ranges = selections
12112            .into_iter()
12113            .map(|s| {
12114                if line_mode {
12115                    let start = Point::new(s.start.row, 0);
12116                    let end = Point::new(
12117                        s.end.row,
12118                        display_map
12119                            .buffer_snapshot
12120                            .line_len(MultiBufferRow(s.end.row)),
12121                    );
12122                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12123                } else {
12124                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12125                }
12126            })
12127            .collect::<Vec<_>>();
12128        self.fold_creases(ranges, true, window, cx);
12129    }
12130
12131    pub fn fold_ranges<T: ToOffset + Clone>(
12132        &mut self,
12133        ranges: Vec<Range<T>>,
12134        auto_scroll: bool,
12135        window: &mut Window,
12136        cx: &mut Context<Self>,
12137    ) {
12138        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12139        let ranges = ranges
12140            .into_iter()
12141            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12142            .collect::<Vec<_>>();
12143        self.fold_creases(ranges, auto_scroll, window, cx);
12144    }
12145
12146    pub fn fold_creases<T: ToOffset + Clone>(
12147        &mut self,
12148        creases: Vec<Crease<T>>,
12149        auto_scroll: bool,
12150        window: &mut Window,
12151        cx: &mut Context<Self>,
12152    ) {
12153        if creases.is_empty() {
12154            return;
12155        }
12156
12157        let mut buffers_affected = HashSet::default();
12158        let multi_buffer = self.buffer().read(cx);
12159        for crease in &creases {
12160            if let Some((_, buffer, _)) =
12161                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12162            {
12163                buffers_affected.insert(buffer.read(cx).remote_id());
12164            };
12165        }
12166
12167        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12168
12169        if auto_scroll {
12170            self.request_autoscroll(Autoscroll::fit(), cx);
12171        }
12172
12173        cx.notify();
12174
12175        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12176            // Clear diagnostics block when folding a range that contains it.
12177            let snapshot = self.snapshot(window, cx);
12178            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12179                drop(snapshot);
12180                self.active_diagnostics = Some(active_diagnostics);
12181                self.dismiss_diagnostics(cx);
12182            } else {
12183                self.active_diagnostics = Some(active_diagnostics);
12184            }
12185        }
12186
12187        self.scrollbar_marker_state.dirty = true;
12188    }
12189
12190    /// Removes any folds whose ranges intersect any of the given ranges.
12191    pub fn unfold_ranges<T: ToOffset + Clone>(
12192        &mut self,
12193        ranges: &[Range<T>],
12194        inclusive: bool,
12195        auto_scroll: bool,
12196        cx: &mut Context<Self>,
12197    ) {
12198        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12199            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12200        });
12201    }
12202
12203    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12204        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12205            return;
12206        }
12207        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12208        self.display_map
12209            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12210        cx.emit(EditorEvent::BufferFoldToggled {
12211            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12212            folded: true,
12213        });
12214        cx.notify();
12215    }
12216
12217    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12218        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12219            return;
12220        }
12221        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12222        self.display_map.update(cx, |display_map, cx| {
12223            display_map.unfold_buffer(buffer_id, cx);
12224        });
12225        cx.emit(EditorEvent::BufferFoldToggled {
12226            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12227            folded: false,
12228        });
12229        cx.notify();
12230    }
12231
12232    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12233        self.display_map.read(cx).is_buffer_folded(buffer)
12234    }
12235
12236    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12237        self.display_map.read(cx).folded_buffers()
12238    }
12239
12240    /// Removes any folds with the given ranges.
12241    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12242        &mut self,
12243        ranges: &[Range<T>],
12244        type_id: TypeId,
12245        auto_scroll: bool,
12246        cx: &mut Context<Self>,
12247    ) {
12248        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12249            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12250        });
12251    }
12252
12253    fn remove_folds_with<T: ToOffset + Clone>(
12254        &mut self,
12255        ranges: &[Range<T>],
12256        auto_scroll: bool,
12257        cx: &mut Context<Self>,
12258        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12259    ) {
12260        if ranges.is_empty() {
12261            return;
12262        }
12263
12264        let mut buffers_affected = HashSet::default();
12265        let multi_buffer = self.buffer().read(cx);
12266        for range in ranges {
12267            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12268                buffers_affected.insert(buffer.read(cx).remote_id());
12269            };
12270        }
12271
12272        self.display_map.update(cx, update);
12273
12274        if auto_scroll {
12275            self.request_autoscroll(Autoscroll::fit(), cx);
12276        }
12277
12278        cx.notify();
12279        self.scrollbar_marker_state.dirty = true;
12280        self.active_indent_guides_state.dirty = true;
12281    }
12282
12283    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12284        self.display_map.read(cx).fold_placeholder.clone()
12285    }
12286
12287    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12288        self.buffer.update(cx, |buffer, cx| {
12289            buffer.set_all_diff_hunks_expanded(cx);
12290        });
12291    }
12292
12293    pub fn expand_all_diff_hunks(
12294        &mut self,
12295        _: &ExpandAllHunkDiffs,
12296        _window: &mut Window,
12297        cx: &mut Context<Self>,
12298    ) {
12299        self.buffer.update(cx, |buffer, cx| {
12300            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12301        });
12302    }
12303
12304    pub fn toggle_selected_diff_hunks(
12305        &mut self,
12306        _: &ToggleSelectedDiffHunks,
12307        _window: &mut Window,
12308        cx: &mut Context<Self>,
12309    ) {
12310        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12311        self.toggle_diff_hunks_in_ranges(ranges, cx);
12312    }
12313
12314    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12315        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12316        self.buffer
12317            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12318    }
12319
12320    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12321        self.buffer.update(cx, |buffer, cx| {
12322            let ranges = vec![Anchor::min()..Anchor::max()];
12323            if !buffer.all_diff_hunks_expanded()
12324                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12325            {
12326                buffer.collapse_diff_hunks(ranges, cx);
12327                true
12328            } else {
12329                false
12330            }
12331        })
12332    }
12333
12334    fn toggle_diff_hunks_in_ranges(
12335        &mut self,
12336        ranges: Vec<Range<Anchor>>,
12337        cx: &mut Context<'_, Editor>,
12338    ) {
12339        self.buffer.update(cx, |buffer, cx| {
12340            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12341            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12342        })
12343    }
12344
12345    fn toggle_diff_hunks_in_ranges_narrow(
12346        &mut self,
12347        ranges: Vec<Range<Anchor>>,
12348        cx: &mut Context<'_, Editor>,
12349    ) {
12350        self.buffer.update(cx, |buffer, cx| {
12351            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12352            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12353        })
12354    }
12355
12356    pub(crate) fn apply_all_diff_hunks(
12357        &mut self,
12358        _: &ApplyAllDiffHunks,
12359        window: &mut Window,
12360        cx: &mut Context<Self>,
12361    ) {
12362        let buffers = self.buffer.read(cx).all_buffers();
12363        for branch_buffer in buffers {
12364            branch_buffer.update(cx, |branch_buffer, cx| {
12365                branch_buffer.merge_into_base(Vec::new(), cx);
12366            });
12367        }
12368
12369        if let Some(project) = self.project.clone() {
12370            self.save(true, project, window, cx).detach_and_log_err(cx);
12371        }
12372    }
12373
12374    pub(crate) fn apply_selected_diff_hunks(
12375        &mut self,
12376        _: &ApplyDiffHunk,
12377        window: &mut Window,
12378        cx: &mut Context<Self>,
12379    ) {
12380        let snapshot = self.snapshot(window, cx);
12381        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12382        let mut ranges_by_buffer = HashMap::default();
12383        self.transact(window, cx, |editor, _window, cx| {
12384            for hunk in hunks {
12385                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12386                    ranges_by_buffer
12387                        .entry(buffer.clone())
12388                        .or_insert_with(Vec::new)
12389                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12390                }
12391            }
12392
12393            for (buffer, ranges) in ranges_by_buffer {
12394                buffer.update(cx, |buffer, cx| {
12395                    buffer.merge_into_base(ranges, cx);
12396                });
12397            }
12398        });
12399
12400        if let Some(project) = self.project.clone() {
12401            self.save(true, project, window, cx).detach_and_log_err(cx);
12402        }
12403    }
12404
12405    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12406        if hovered != self.gutter_hovered {
12407            self.gutter_hovered = hovered;
12408            cx.notify();
12409        }
12410    }
12411
12412    pub fn insert_blocks(
12413        &mut self,
12414        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12415        autoscroll: Option<Autoscroll>,
12416        cx: &mut Context<Self>,
12417    ) -> Vec<CustomBlockId> {
12418        let blocks = self
12419            .display_map
12420            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12421        if let Some(autoscroll) = autoscroll {
12422            self.request_autoscroll(autoscroll, cx);
12423        }
12424        cx.notify();
12425        blocks
12426    }
12427
12428    pub fn resize_blocks(
12429        &mut self,
12430        heights: HashMap<CustomBlockId, u32>,
12431        autoscroll: Option<Autoscroll>,
12432        cx: &mut Context<Self>,
12433    ) {
12434        self.display_map
12435            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12436        if let Some(autoscroll) = autoscroll {
12437            self.request_autoscroll(autoscroll, cx);
12438        }
12439        cx.notify();
12440    }
12441
12442    pub fn replace_blocks(
12443        &mut self,
12444        renderers: HashMap<CustomBlockId, RenderBlock>,
12445        autoscroll: Option<Autoscroll>,
12446        cx: &mut Context<Self>,
12447    ) {
12448        self.display_map
12449            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12450        if let Some(autoscroll) = autoscroll {
12451            self.request_autoscroll(autoscroll, cx);
12452        }
12453        cx.notify();
12454    }
12455
12456    pub fn remove_blocks(
12457        &mut self,
12458        block_ids: HashSet<CustomBlockId>,
12459        autoscroll: Option<Autoscroll>,
12460        cx: &mut Context<Self>,
12461    ) {
12462        self.display_map.update(cx, |display_map, cx| {
12463            display_map.remove_blocks(block_ids, cx)
12464        });
12465        if let Some(autoscroll) = autoscroll {
12466            self.request_autoscroll(autoscroll, cx);
12467        }
12468        cx.notify();
12469    }
12470
12471    pub fn row_for_block(
12472        &self,
12473        block_id: CustomBlockId,
12474        cx: &mut Context<Self>,
12475    ) -> Option<DisplayRow> {
12476        self.display_map
12477            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12478    }
12479
12480    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12481        self.focused_block = Some(focused_block);
12482    }
12483
12484    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12485        self.focused_block.take()
12486    }
12487
12488    pub fn insert_creases(
12489        &mut self,
12490        creases: impl IntoIterator<Item = Crease<Anchor>>,
12491        cx: &mut Context<Self>,
12492    ) -> Vec<CreaseId> {
12493        self.display_map
12494            .update(cx, |map, cx| map.insert_creases(creases, cx))
12495    }
12496
12497    pub fn remove_creases(
12498        &mut self,
12499        ids: impl IntoIterator<Item = CreaseId>,
12500        cx: &mut Context<Self>,
12501    ) {
12502        self.display_map
12503            .update(cx, |map, cx| map.remove_creases(ids, cx));
12504    }
12505
12506    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12507        self.display_map
12508            .update(cx, |map, cx| map.snapshot(cx))
12509            .longest_row()
12510    }
12511
12512    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12513        self.display_map
12514            .update(cx, |map, cx| map.snapshot(cx))
12515            .max_point()
12516    }
12517
12518    pub fn text(&self, cx: &App) -> String {
12519        self.buffer.read(cx).read(cx).text()
12520    }
12521
12522    pub fn is_empty(&self, cx: &App) -> bool {
12523        self.buffer.read(cx).read(cx).is_empty()
12524    }
12525
12526    pub fn text_option(&self, cx: &App) -> Option<String> {
12527        let text = self.text(cx);
12528        let text = text.trim();
12529
12530        if text.is_empty() {
12531            return None;
12532        }
12533
12534        Some(text.to_string())
12535    }
12536
12537    pub fn set_text(
12538        &mut self,
12539        text: impl Into<Arc<str>>,
12540        window: &mut Window,
12541        cx: &mut Context<Self>,
12542    ) {
12543        self.transact(window, cx, |this, _, cx| {
12544            this.buffer
12545                .read(cx)
12546                .as_singleton()
12547                .expect("you can only call set_text on editors for singleton buffers")
12548                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12549        });
12550    }
12551
12552    pub fn display_text(&self, cx: &mut App) -> String {
12553        self.display_map
12554            .update(cx, |map, cx| map.snapshot(cx))
12555            .text()
12556    }
12557
12558    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12559        let mut wrap_guides = smallvec::smallvec![];
12560
12561        if self.show_wrap_guides == Some(false) {
12562            return wrap_guides;
12563        }
12564
12565        let settings = self.buffer.read(cx).settings_at(0, cx);
12566        if settings.show_wrap_guides {
12567            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12568                wrap_guides.push((soft_wrap as usize, true));
12569            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12570                wrap_guides.push((soft_wrap as usize, true));
12571            }
12572            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12573        }
12574
12575        wrap_guides
12576    }
12577
12578    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12579        let settings = self.buffer.read(cx).settings_at(0, cx);
12580        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12581        match mode {
12582            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12583                SoftWrap::None
12584            }
12585            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12586            language_settings::SoftWrap::PreferredLineLength => {
12587                SoftWrap::Column(settings.preferred_line_length)
12588            }
12589            language_settings::SoftWrap::Bounded => {
12590                SoftWrap::Bounded(settings.preferred_line_length)
12591            }
12592        }
12593    }
12594
12595    pub fn set_soft_wrap_mode(
12596        &mut self,
12597        mode: language_settings::SoftWrap,
12598
12599        cx: &mut Context<Self>,
12600    ) {
12601        self.soft_wrap_mode_override = Some(mode);
12602        cx.notify();
12603    }
12604
12605    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12606        self.text_style_refinement = Some(style);
12607    }
12608
12609    /// called by the Element so we know what style we were most recently rendered with.
12610    pub(crate) fn set_style(
12611        &mut self,
12612        style: EditorStyle,
12613        window: &mut Window,
12614        cx: &mut Context<Self>,
12615    ) {
12616        let rem_size = window.rem_size();
12617        self.display_map.update(cx, |map, cx| {
12618            map.set_font(
12619                style.text.font(),
12620                style.text.font_size.to_pixels(rem_size),
12621                cx,
12622            )
12623        });
12624        self.style = Some(style);
12625    }
12626
12627    pub fn style(&self) -> Option<&EditorStyle> {
12628        self.style.as_ref()
12629    }
12630
12631    // Called by the element. This method is not designed to be called outside of the editor
12632    // element's layout code because it does not notify when rewrapping is computed synchronously.
12633    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12634        self.display_map
12635            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12636    }
12637
12638    pub fn set_soft_wrap(&mut self) {
12639        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12640    }
12641
12642    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12643        if self.soft_wrap_mode_override.is_some() {
12644            self.soft_wrap_mode_override.take();
12645        } else {
12646            let soft_wrap = match self.soft_wrap_mode(cx) {
12647                SoftWrap::GitDiff => return,
12648                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12649                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12650                    language_settings::SoftWrap::None
12651                }
12652            };
12653            self.soft_wrap_mode_override = Some(soft_wrap);
12654        }
12655        cx.notify();
12656    }
12657
12658    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12659        let Some(workspace) = self.workspace() else {
12660            return;
12661        };
12662        let fs = workspace.read(cx).app_state().fs.clone();
12663        let current_show = TabBarSettings::get_global(cx).show;
12664        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12665            setting.show = Some(!current_show);
12666        });
12667    }
12668
12669    pub fn toggle_indent_guides(
12670        &mut self,
12671        _: &ToggleIndentGuides,
12672        _: &mut Window,
12673        cx: &mut Context<Self>,
12674    ) {
12675        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12676            self.buffer
12677                .read(cx)
12678                .settings_at(0, cx)
12679                .indent_guides
12680                .enabled
12681        });
12682        self.show_indent_guides = Some(!currently_enabled);
12683        cx.notify();
12684    }
12685
12686    fn should_show_indent_guides(&self) -> Option<bool> {
12687        self.show_indent_guides
12688    }
12689
12690    pub fn toggle_line_numbers(
12691        &mut self,
12692        _: &ToggleLineNumbers,
12693        _: &mut Window,
12694        cx: &mut Context<Self>,
12695    ) {
12696        let mut editor_settings = EditorSettings::get_global(cx).clone();
12697        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12698        EditorSettings::override_global(editor_settings, cx);
12699    }
12700
12701    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12702        self.use_relative_line_numbers
12703            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12704    }
12705
12706    pub fn toggle_relative_line_numbers(
12707        &mut self,
12708        _: &ToggleRelativeLineNumbers,
12709        _: &mut Window,
12710        cx: &mut Context<Self>,
12711    ) {
12712        let is_relative = self.should_use_relative_line_numbers(cx);
12713        self.set_relative_line_number(Some(!is_relative), cx)
12714    }
12715
12716    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12717        self.use_relative_line_numbers = is_relative;
12718        cx.notify();
12719    }
12720
12721    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12722        self.show_gutter = show_gutter;
12723        cx.notify();
12724    }
12725
12726    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12727        self.show_scrollbars = show_scrollbars;
12728        cx.notify();
12729    }
12730
12731    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12732        self.show_line_numbers = Some(show_line_numbers);
12733        cx.notify();
12734    }
12735
12736    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12737        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12738        cx.notify();
12739    }
12740
12741    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12742        self.show_code_actions = Some(show_code_actions);
12743        cx.notify();
12744    }
12745
12746    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12747        self.show_runnables = Some(show_runnables);
12748        cx.notify();
12749    }
12750
12751    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12752        if self.display_map.read(cx).masked != masked {
12753            self.display_map.update(cx, |map, _| map.masked = masked);
12754        }
12755        cx.notify()
12756    }
12757
12758    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12759        self.show_wrap_guides = Some(show_wrap_guides);
12760        cx.notify();
12761    }
12762
12763    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12764        self.show_indent_guides = Some(show_indent_guides);
12765        cx.notify();
12766    }
12767
12768    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12769        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12770            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12771                if let Some(dir) = file.abs_path(cx).parent() {
12772                    return Some(dir.to_owned());
12773                }
12774            }
12775
12776            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12777                return Some(project_path.path.to_path_buf());
12778            }
12779        }
12780
12781        None
12782    }
12783
12784    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12785        self.active_excerpt(cx)?
12786            .1
12787            .read(cx)
12788            .file()
12789            .and_then(|f| f.as_local())
12790    }
12791
12792    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12793        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12794            let project_path = buffer.read(cx).project_path(cx)?;
12795            let project = self.project.as_ref()?.read(cx);
12796            project.absolute_path(&project_path, cx)
12797        })
12798    }
12799
12800    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12801        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12802            let project_path = buffer.read(cx).project_path(cx)?;
12803            let project = self.project.as_ref()?.read(cx);
12804            let entry = project.entry_for_path(&project_path, cx)?;
12805            let path = entry.path.to_path_buf();
12806            Some(path)
12807        })
12808    }
12809
12810    pub fn reveal_in_finder(
12811        &mut self,
12812        _: &RevealInFileManager,
12813        _window: &mut Window,
12814        cx: &mut Context<Self>,
12815    ) {
12816        if let Some(target) = self.target_file(cx) {
12817            cx.reveal_path(&target.abs_path(cx));
12818        }
12819    }
12820
12821    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12822        if let Some(path) = self.target_file_abs_path(cx) {
12823            if let Some(path) = path.to_str() {
12824                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12825            }
12826        }
12827    }
12828
12829    pub fn copy_relative_path(
12830        &mut self,
12831        _: &CopyRelativePath,
12832        _window: &mut Window,
12833        cx: &mut Context<Self>,
12834    ) {
12835        if let Some(path) = self.target_file_path(cx) {
12836            if let Some(path) = path.to_str() {
12837                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12838            }
12839        }
12840    }
12841
12842    pub fn toggle_git_blame(
12843        &mut self,
12844        _: &ToggleGitBlame,
12845        window: &mut Window,
12846        cx: &mut Context<Self>,
12847    ) {
12848        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12849
12850        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12851            self.start_git_blame(true, window, cx);
12852        }
12853
12854        cx.notify();
12855    }
12856
12857    pub fn toggle_git_blame_inline(
12858        &mut self,
12859        _: &ToggleGitBlameInline,
12860        window: &mut Window,
12861        cx: &mut Context<Self>,
12862    ) {
12863        self.toggle_git_blame_inline_internal(true, window, cx);
12864        cx.notify();
12865    }
12866
12867    pub fn git_blame_inline_enabled(&self) -> bool {
12868        self.git_blame_inline_enabled
12869    }
12870
12871    pub fn toggle_selection_menu(
12872        &mut self,
12873        _: &ToggleSelectionMenu,
12874        _: &mut Window,
12875        cx: &mut Context<Self>,
12876    ) {
12877        self.show_selection_menu = self
12878            .show_selection_menu
12879            .map(|show_selections_menu| !show_selections_menu)
12880            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12881
12882        cx.notify();
12883    }
12884
12885    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12886        self.show_selection_menu
12887            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12888    }
12889
12890    fn start_git_blame(
12891        &mut self,
12892        user_triggered: bool,
12893        window: &mut Window,
12894        cx: &mut Context<Self>,
12895    ) {
12896        if let Some(project) = self.project.as_ref() {
12897            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12898                return;
12899            };
12900
12901            if buffer.read(cx).file().is_none() {
12902                return;
12903            }
12904
12905            let focused = self.focus_handle(cx).contains_focused(window, cx);
12906
12907            let project = project.clone();
12908            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12909            self.blame_subscription =
12910                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12911            self.blame = Some(blame);
12912        }
12913    }
12914
12915    fn toggle_git_blame_inline_internal(
12916        &mut self,
12917        user_triggered: bool,
12918        window: &mut Window,
12919        cx: &mut Context<Self>,
12920    ) {
12921        if self.git_blame_inline_enabled {
12922            self.git_blame_inline_enabled = false;
12923            self.show_git_blame_inline = false;
12924            self.show_git_blame_inline_delay_task.take();
12925        } else {
12926            self.git_blame_inline_enabled = true;
12927            self.start_git_blame_inline(user_triggered, window, cx);
12928        }
12929
12930        cx.notify();
12931    }
12932
12933    fn start_git_blame_inline(
12934        &mut self,
12935        user_triggered: bool,
12936        window: &mut Window,
12937        cx: &mut Context<Self>,
12938    ) {
12939        self.start_git_blame(user_triggered, window, cx);
12940
12941        if ProjectSettings::get_global(cx)
12942            .git
12943            .inline_blame_delay()
12944            .is_some()
12945        {
12946            self.start_inline_blame_timer(window, cx);
12947        } else {
12948            self.show_git_blame_inline = true
12949        }
12950    }
12951
12952    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12953        self.blame.as_ref()
12954    }
12955
12956    pub fn show_git_blame_gutter(&self) -> bool {
12957        self.show_git_blame_gutter
12958    }
12959
12960    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12961        self.show_git_blame_gutter && self.has_blame_entries(cx)
12962    }
12963
12964    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12965        self.show_git_blame_inline
12966            && self.focus_handle.is_focused(window)
12967            && !self.newest_selection_head_on_empty_line(cx)
12968            && self.has_blame_entries(cx)
12969    }
12970
12971    fn has_blame_entries(&self, cx: &App) -> bool {
12972        self.blame()
12973            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12974    }
12975
12976    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12977        let cursor_anchor = self.selections.newest_anchor().head();
12978
12979        let snapshot = self.buffer.read(cx).snapshot(cx);
12980        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12981
12982        snapshot.line_len(buffer_row) == 0
12983    }
12984
12985    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12986        let buffer_and_selection = maybe!({
12987            let selection = self.selections.newest::<Point>(cx);
12988            let selection_range = selection.range();
12989
12990            let multi_buffer = self.buffer().read(cx);
12991            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12992            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12993
12994            let (buffer, range, _) = if selection.reversed {
12995                buffer_ranges.first()
12996            } else {
12997                buffer_ranges.last()
12998            }?;
12999
13000            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13001                ..text::ToPoint::to_point(&range.end, &buffer).row;
13002            Some((
13003                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13004                selection,
13005            ))
13006        });
13007
13008        let Some((buffer, selection)) = buffer_and_selection else {
13009            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13010        };
13011
13012        let Some(project) = self.project.as_ref() else {
13013            return Task::ready(Err(anyhow!("editor does not have project")));
13014        };
13015
13016        project.update(cx, |project, cx| {
13017            project.get_permalink_to_line(&buffer, selection, cx)
13018        })
13019    }
13020
13021    pub fn copy_permalink_to_line(
13022        &mut self,
13023        _: &CopyPermalinkToLine,
13024        window: &mut Window,
13025        cx: &mut Context<Self>,
13026    ) {
13027        let permalink_task = self.get_permalink_to_line(cx);
13028        let workspace = self.workspace();
13029
13030        cx.spawn_in(window, |_, mut cx| async move {
13031            match permalink_task.await {
13032                Ok(permalink) => {
13033                    cx.update(|_, cx| {
13034                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13035                    })
13036                    .ok();
13037                }
13038                Err(err) => {
13039                    let message = format!("Failed to copy permalink: {err}");
13040
13041                    Err::<(), anyhow::Error>(err).log_err();
13042
13043                    if let Some(workspace) = workspace {
13044                        workspace
13045                            .update_in(&mut cx, |workspace, _, cx| {
13046                                struct CopyPermalinkToLine;
13047
13048                                workspace.show_toast(
13049                                    Toast::new(
13050                                        NotificationId::unique::<CopyPermalinkToLine>(),
13051                                        message,
13052                                    ),
13053                                    cx,
13054                                )
13055                            })
13056                            .ok();
13057                    }
13058                }
13059            }
13060        })
13061        .detach();
13062    }
13063
13064    pub fn copy_file_location(
13065        &mut self,
13066        _: &CopyFileLocation,
13067        _: &mut Window,
13068        cx: &mut Context<Self>,
13069    ) {
13070        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13071        if let Some(file) = self.target_file(cx) {
13072            if let Some(path) = file.path().to_str() {
13073                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13074            }
13075        }
13076    }
13077
13078    pub fn open_permalink_to_line(
13079        &mut self,
13080        _: &OpenPermalinkToLine,
13081        window: &mut Window,
13082        cx: &mut Context<Self>,
13083    ) {
13084        let permalink_task = self.get_permalink_to_line(cx);
13085        let workspace = self.workspace();
13086
13087        cx.spawn_in(window, |_, mut cx| async move {
13088            match permalink_task.await {
13089                Ok(permalink) => {
13090                    cx.update(|_, cx| {
13091                        cx.open_url(permalink.as_ref());
13092                    })
13093                    .ok();
13094                }
13095                Err(err) => {
13096                    let message = format!("Failed to open permalink: {err}");
13097
13098                    Err::<(), anyhow::Error>(err).log_err();
13099
13100                    if let Some(workspace) = workspace {
13101                        workspace
13102                            .update(&mut cx, |workspace, cx| {
13103                                struct OpenPermalinkToLine;
13104
13105                                workspace.show_toast(
13106                                    Toast::new(
13107                                        NotificationId::unique::<OpenPermalinkToLine>(),
13108                                        message,
13109                                    ),
13110                                    cx,
13111                                )
13112                            })
13113                            .ok();
13114                    }
13115                }
13116            }
13117        })
13118        .detach();
13119    }
13120
13121    pub fn insert_uuid_v4(
13122        &mut self,
13123        _: &InsertUuidV4,
13124        window: &mut Window,
13125        cx: &mut Context<Self>,
13126    ) {
13127        self.insert_uuid(UuidVersion::V4, window, cx);
13128    }
13129
13130    pub fn insert_uuid_v7(
13131        &mut self,
13132        _: &InsertUuidV7,
13133        window: &mut Window,
13134        cx: &mut Context<Self>,
13135    ) {
13136        self.insert_uuid(UuidVersion::V7, window, cx);
13137    }
13138
13139    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13140        self.transact(window, cx, |this, window, cx| {
13141            let edits = this
13142                .selections
13143                .all::<Point>(cx)
13144                .into_iter()
13145                .map(|selection| {
13146                    let uuid = match version {
13147                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13148                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13149                    };
13150
13151                    (selection.range(), uuid.to_string())
13152                });
13153            this.edit(edits, cx);
13154            this.refresh_inline_completion(true, false, window, cx);
13155        });
13156    }
13157
13158    pub fn open_selections_in_multibuffer(
13159        &mut self,
13160        _: &OpenSelectionsInMultibuffer,
13161        window: &mut Window,
13162        cx: &mut Context<Self>,
13163    ) {
13164        let multibuffer = self.buffer.read(cx);
13165
13166        let Some(buffer) = multibuffer.as_singleton() else {
13167            return;
13168        };
13169
13170        let Some(workspace) = self.workspace() else {
13171            return;
13172        };
13173
13174        let locations = self
13175            .selections
13176            .disjoint_anchors()
13177            .iter()
13178            .map(|range| Location {
13179                buffer: buffer.clone(),
13180                range: range.start.text_anchor..range.end.text_anchor,
13181            })
13182            .collect::<Vec<_>>();
13183
13184        let title = multibuffer.title(cx).to_string();
13185
13186        cx.spawn_in(window, |_, mut cx| async move {
13187            workspace.update_in(&mut cx, |workspace, window, cx| {
13188                Self::open_locations_in_multibuffer(
13189                    workspace,
13190                    locations,
13191                    format!("Selections for '{title}'"),
13192                    false,
13193                    MultibufferSelectionMode::All,
13194                    window,
13195                    cx,
13196                );
13197            })
13198        })
13199        .detach();
13200    }
13201
13202    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13203    /// last highlight added will be used.
13204    ///
13205    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13206    pub fn highlight_rows<T: 'static>(
13207        &mut self,
13208        range: Range<Anchor>,
13209        color: Hsla,
13210        should_autoscroll: bool,
13211        cx: &mut Context<Self>,
13212    ) {
13213        let snapshot = self.buffer().read(cx).snapshot(cx);
13214        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13215        let ix = row_highlights.binary_search_by(|highlight| {
13216            Ordering::Equal
13217                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13218                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13219        });
13220
13221        if let Err(mut ix) = ix {
13222            let index = post_inc(&mut self.highlight_order);
13223
13224            // If this range intersects with the preceding highlight, then merge it with
13225            // the preceding highlight. Otherwise insert a new highlight.
13226            let mut merged = false;
13227            if ix > 0 {
13228                let prev_highlight = &mut row_highlights[ix - 1];
13229                if prev_highlight
13230                    .range
13231                    .end
13232                    .cmp(&range.start, &snapshot)
13233                    .is_ge()
13234                {
13235                    ix -= 1;
13236                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13237                        prev_highlight.range.end = range.end;
13238                    }
13239                    merged = true;
13240                    prev_highlight.index = index;
13241                    prev_highlight.color = color;
13242                    prev_highlight.should_autoscroll = should_autoscroll;
13243                }
13244            }
13245
13246            if !merged {
13247                row_highlights.insert(
13248                    ix,
13249                    RowHighlight {
13250                        range: range.clone(),
13251                        index,
13252                        color,
13253                        should_autoscroll,
13254                    },
13255                );
13256            }
13257
13258            // If any of the following highlights intersect with this one, merge them.
13259            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13260                let highlight = &row_highlights[ix];
13261                if next_highlight
13262                    .range
13263                    .start
13264                    .cmp(&highlight.range.end, &snapshot)
13265                    .is_le()
13266                {
13267                    if next_highlight
13268                        .range
13269                        .end
13270                        .cmp(&highlight.range.end, &snapshot)
13271                        .is_gt()
13272                    {
13273                        row_highlights[ix].range.end = next_highlight.range.end;
13274                    }
13275                    row_highlights.remove(ix + 1);
13276                } else {
13277                    break;
13278                }
13279            }
13280        }
13281    }
13282
13283    /// Remove any highlighted row ranges of the given type that intersect the
13284    /// given ranges.
13285    pub fn remove_highlighted_rows<T: 'static>(
13286        &mut self,
13287        ranges_to_remove: Vec<Range<Anchor>>,
13288        cx: &mut Context<Self>,
13289    ) {
13290        let snapshot = self.buffer().read(cx).snapshot(cx);
13291        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13292        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13293        row_highlights.retain(|highlight| {
13294            while let Some(range_to_remove) = ranges_to_remove.peek() {
13295                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13296                    Ordering::Less | Ordering::Equal => {
13297                        ranges_to_remove.next();
13298                    }
13299                    Ordering::Greater => {
13300                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13301                            Ordering::Less | Ordering::Equal => {
13302                                return false;
13303                            }
13304                            Ordering::Greater => break,
13305                        }
13306                    }
13307                }
13308            }
13309
13310            true
13311        })
13312    }
13313
13314    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13315    pub fn clear_row_highlights<T: 'static>(&mut self) {
13316        self.highlighted_rows.remove(&TypeId::of::<T>());
13317    }
13318
13319    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13320    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13321        self.highlighted_rows
13322            .get(&TypeId::of::<T>())
13323            .map_or(&[] as &[_], |vec| vec.as_slice())
13324            .iter()
13325            .map(|highlight| (highlight.range.clone(), highlight.color))
13326    }
13327
13328    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13329    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13330    /// Allows to ignore certain kinds of highlights.
13331    pub fn highlighted_display_rows(
13332        &self,
13333        window: &mut Window,
13334        cx: &mut App,
13335    ) -> BTreeMap<DisplayRow, Hsla> {
13336        let snapshot = self.snapshot(window, cx);
13337        let mut used_highlight_orders = HashMap::default();
13338        self.highlighted_rows
13339            .iter()
13340            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13341            .fold(
13342                BTreeMap::<DisplayRow, Hsla>::new(),
13343                |mut unique_rows, highlight| {
13344                    let start = highlight.range.start.to_display_point(&snapshot);
13345                    let end = highlight.range.end.to_display_point(&snapshot);
13346                    let start_row = start.row().0;
13347                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13348                        && end.column() == 0
13349                    {
13350                        end.row().0.saturating_sub(1)
13351                    } else {
13352                        end.row().0
13353                    };
13354                    for row in start_row..=end_row {
13355                        let used_index =
13356                            used_highlight_orders.entry(row).or_insert(highlight.index);
13357                        if highlight.index >= *used_index {
13358                            *used_index = highlight.index;
13359                            unique_rows.insert(DisplayRow(row), highlight.color);
13360                        }
13361                    }
13362                    unique_rows
13363                },
13364            )
13365    }
13366
13367    pub fn highlighted_display_row_for_autoscroll(
13368        &self,
13369        snapshot: &DisplaySnapshot,
13370    ) -> Option<DisplayRow> {
13371        self.highlighted_rows
13372            .values()
13373            .flat_map(|highlighted_rows| highlighted_rows.iter())
13374            .filter_map(|highlight| {
13375                if highlight.should_autoscroll {
13376                    Some(highlight.range.start.to_display_point(snapshot).row())
13377                } else {
13378                    None
13379                }
13380            })
13381            .min()
13382    }
13383
13384    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13385        self.highlight_background::<SearchWithinRange>(
13386            ranges,
13387            |colors| colors.editor_document_highlight_read_background,
13388            cx,
13389        )
13390    }
13391
13392    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13393        self.breadcrumb_header = Some(new_header);
13394    }
13395
13396    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13397        self.clear_background_highlights::<SearchWithinRange>(cx);
13398    }
13399
13400    pub fn highlight_background<T: 'static>(
13401        &mut self,
13402        ranges: &[Range<Anchor>],
13403        color_fetcher: fn(&ThemeColors) -> Hsla,
13404        cx: &mut Context<Self>,
13405    ) {
13406        self.background_highlights
13407            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13408        self.scrollbar_marker_state.dirty = true;
13409        cx.notify();
13410    }
13411
13412    pub fn clear_background_highlights<T: 'static>(
13413        &mut self,
13414        cx: &mut Context<Self>,
13415    ) -> Option<BackgroundHighlight> {
13416        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13417        if !text_highlights.1.is_empty() {
13418            self.scrollbar_marker_state.dirty = true;
13419            cx.notify();
13420        }
13421        Some(text_highlights)
13422    }
13423
13424    pub fn highlight_gutter<T: 'static>(
13425        &mut self,
13426        ranges: &[Range<Anchor>],
13427        color_fetcher: fn(&App) -> Hsla,
13428        cx: &mut Context<Self>,
13429    ) {
13430        self.gutter_highlights
13431            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13432        cx.notify();
13433    }
13434
13435    pub fn clear_gutter_highlights<T: 'static>(
13436        &mut self,
13437        cx: &mut Context<Self>,
13438    ) -> Option<GutterHighlight> {
13439        cx.notify();
13440        self.gutter_highlights.remove(&TypeId::of::<T>())
13441    }
13442
13443    #[cfg(feature = "test-support")]
13444    pub fn all_text_background_highlights(
13445        &self,
13446        window: &mut Window,
13447        cx: &mut Context<Self>,
13448    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13449        let snapshot = self.snapshot(window, cx);
13450        let buffer = &snapshot.buffer_snapshot;
13451        let start = buffer.anchor_before(0);
13452        let end = buffer.anchor_after(buffer.len());
13453        let theme = cx.theme().colors();
13454        self.background_highlights_in_range(start..end, &snapshot, theme)
13455    }
13456
13457    #[cfg(feature = "test-support")]
13458    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13459        let snapshot = self.buffer().read(cx).snapshot(cx);
13460
13461        let highlights = self
13462            .background_highlights
13463            .get(&TypeId::of::<items::BufferSearchHighlights>());
13464
13465        if let Some((_color, ranges)) = highlights {
13466            ranges
13467                .iter()
13468                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13469                .collect_vec()
13470        } else {
13471            vec![]
13472        }
13473    }
13474
13475    fn document_highlights_for_position<'a>(
13476        &'a self,
13477        position: Anchor,
13478        buffer: &'a MultiBufferSnapshot,
13479    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13480        let read_highlights = self
13481            .background_highlights
13482            .get(&TypeId::of::<DocumentHighlightRead>())
13483            .map(|h| &h.1);
13484        let write_highlights = self
13485            .background_highlights
13486            .get(&TypeId::of::<DocumentHighlightWrite>())
13487            .map(|h| &h.1);
13488        let left_position = position.bias_left(buffer);
13489        let right_position = position.bias_right(buffer);
13490        read_highlights
13491            .into_iter()
13492            .chain(write_highlights)
13493            .flat_map(move |ranges| {
13494                let start_ix = match ranges.binary_search_by(|probe| {
13495                    let cmp = probe.end.cmp(&left_position, buffer);
13496                    if cmp.is_ge() {
13497                        Ordering::Greater
13498                    } else {
13499                        Ordering::Less
13500                    }
13501                }) {
13502                    Ok(i) | Err(i) => i,
13503                };
13504
13505                ranges[start_ix..]
13506                    .iter()
13507                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13508            })
13509    }
13510
13511    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13512        self.background_highlights
13513            .get(&TypeId::of::<T>())
13514            .map_or(false, |(_, highlights)| !highlights.is_empty())
13515    }
13516
13517    pub fn background_highlights_in_range(
13518        &self,
13519        search_range: Range<Anchor>,
13520        display_snapshot: &DisplaySnapshot,
13521        theme: &ThemeColors,
13522    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13523        let mut results = Vec::new();
13524        for (color_fetcher, ranges) in self.background_highlights.values() {
13525            let color = color_fetcher(theme);
13526            let start_ix = match ranges.binary_search_by(|probe| {
13527                let cmp = probe
13528                    .end
13529                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13530                if cmp.is_gt() {
13531                    Ordering::Greater
13532                } else {
13533                    Ordering::Less
13534                }
13535            }) {
13536                Ok(i) | Err(i) => i,
13537            };
13538            for range in &ranges[start_ix..] {
13539                if range
13540                    .start
13541                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13542                    .is_ge()
13543                {
13544                    break;
13545                }
13546
13547                let start = range.start.to_display_point(display_snapshot);
13548                let end = range.end.to_display_point(display_snapshot);
13549                results.push((start..end, color))
13550            }
13551        }
13552        results
13553    }
13554
13555    pub fn background_highlight_row_ranges<T: 'static>(
13556        &self,
13557        search_range: Range<Anchor>,
13558        display_snapshot: &DisplaySnapshot,
13559        count: usize,
13560    ) -> Vec<RangeInclusive<DisplayPoint>> {
13561        let mut results = Vec::new();
13562        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13563            return vec![];
13564        };
13565
13566        let start_ix = match ranges.binary_search_by(|probe| {
13567            let cmp = probe
13568                .end
13569                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13570            if cmp.is_gt() {
13571                Ordering::Greater
13572            } else {
13573                Ordering::Less
13574            }
13575        }) {
13576            Ok(i) | Err(i) => i,
13577        };
13578        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13579            if let (Some(start_display), Some(end_display)) = (start, end) {
13580                results.push(
13581                    start_display.to_display_point(display_snapshot)
13582                        ..=end_display.to_display_point(display_snapshot),
13583                );
13584            }
13585        };
13586        let mut start_row: Option<Point> = None;
13587        let mut end_row: Option<Point> = None;
13588        if ranges.len() > count {
13589            return Vec::new();
13590        }
13591        for range in &ranges[start_ix..] {
13592            if range
13593                .start
13594                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13595                .is_ge()
13596            {
13597                break;
13598            }
13599            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13600            if let Some(current_row) = &end_row {
13601                if end.row == current_row.row {
13602                    continue;
13603                }
13604            }
13605            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13606            if start_row.is_none() {
13607                assert_eq!(end_row, None);
13608                start_row = Some(start);
13609                end_row = Some(end);
13610                continue;
13611            }
13612            if let Some(current_end) = end_row.as_mut() {
13613                if start.row > current_end.row + 1 {
13614                    push_region(start_row, end_row);
13615                    start_row = Some(start);
13616                    end_row = Some(end);
13617                } else {
13618                    // Merge two hunks.
13619                    *current_end = end;
13620                }
13621            } else {
13622                unreachable!();
13623            }
13624        }
13625        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13626        push_region(start_row, end_row);
13627        results
13628    }
13629
13630    pub fn gutter_highlights_in_range(
13631        &self,
13632        search_range: Range<Anchor>,
13633        display_snapshot: &DisplaySnapshot,
13634        cx: &App,
13635    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13636        let mut results = Vec::new();
13637        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13638            let color = color_fetcher(cx);
13639            let start_ix = match ranges.binary_search_by(|probe| {
13640                let cmp = probe
13641                    .end
13642                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13643                if cmp.is_gt() {
13644                    Ordering::Greater
13645                } else {
13646                    Ordering::Less
13647                }
13648            }) {
13649                Ok(i) | Err(i) => i,
13650            };
13651            for range in &ranges[start_ix..] {
13652                if range
13653                    .start
13654                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13655                    .is_ge()
13656                {
13657                    break;
13658                }
13659
13660                let start = range.start.to_display_point(display_snapshot);
13661                let end = range.end.to_display_point(display_snapshot);
13662                results.push((start..end, color))
13663            }
13664        }
13665        results
13666    }
13667
13668    /// Get the text ranges corresponding to the redaction query
13669    pub fn redacted_ranges(
13670        &self,
13671        search_range: Range<Anchor>,
13672        display_snapshot: &DisplaySnapshot,
13673        cx: &App,
13674    ) -> Vec<Range<DisplayPoint>> {
13675        display_snapshot
13676            .buffer_snapshot
13677            .redacted_ranges(search_range, |file| {
13678                if let Some(file) = file {
13679                    file.is_private()
13680                        && EditorSettings::get(
13681                            Some(SettingsLocation {
13682                                worktree_id: file.worktree_id(cx),
13683                                path: file.path().as_ref(),
13684                            }),
13685                            cx,
13686                        )
13687                        .redact_private_values
13688                } else {
13689                    false
13690                }
13691            })
13692            .map(|range| {
13693                range.start.to_display_point(display_snapshot)
13694                    ..range.end.to_display_point(display_snapshot)
13695            })
13696            .collect()
13697    }
13698
13699    pub fn highlight_text<T: 'static>(
13700        &mut self,
13701        ranges: Vec<Range<Anchor>>,
13702        style: HighlightStyle,
13703        cx: &mut Context<Self>,
13704    ) {
13705        self.display_map.update(cx, |map, _| {
13706            map.highlight_text(TypeId::of::<T>(), ranges, style)
13707        });
13708        cx.notify();
13709    }
13710
13711    pub(crate) fn highlight_inlays<T: 'static>(
13712        &mut self,
13713        highlights: Vec<InlayHighlight>,
13714        style: HighlightStyle,
13715        cx: &mut Context<Self>,
13716    ) {
13717        self.display_map.update(cx, |map, _| {
13718            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13719        });
13720        cx.notify();
13721    }
13722
13723    pub fn text_highlights<'a, T: 'static>(
13724        &'a self,
13725        cx: &'a App,
13726    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13727        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13728    }
13729
13730    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13731        let cleared = self
13732            .display_map
13733            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13734        if cleared {
13735            cx.notify();
13736        }
13737    }
13738
13739    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13740        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13741            && self.focus_handle.is_focused(window)
13742    }
13743
13744    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13745        self.show_cursor_when_unfocused = is_enabled;
13746        cx.notify();
13747    }
13748
13749    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13750        self.project
13751            .as_ref()
13752            .map(|project| project.read(cx).lsp_store())
13753    }
13754
13755    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13756        cx.notify();
13757    }
13758
13759    fn on_buffer_event(
13760        &mut self,
13761        multibuffer: &Entity<MultiBuffer>,
13762        event: &multi_buffer::Event,
13763        window: &mut Window,
13764        cx: &mut Context<Self>,
13765    ) {
13766        match event {
13767            multi_buffer::Event::Edited {
13768                singleton_buffer_edited,
13769                edited_buffer: buffer_edited,
13770            } => {
13771                self.scrollbar_marker_state.dirty = true;
13772                self.active_indent_guides_state.dirty = true;
13773                self.refresh_active_diagnostics(cx);
13774                self.refresh_code_actions(window, cx);
13775                if self.has_active_inline_completion() {
13776                    self.update_visible_inline_completion(window, cx);
13777                }
13778                if let Some(buffer) = buffer_edited {
13779                    let buffer_id = buffer.read(cx).remote_id();
13780                    if !self.registered_buffers.contains_key(&buffer_id) {
13781                        if let Some(lsp_store) = self.lsp_store(cx) {
13782                            lsp_store.update(cx, |lsp_store, cx| {
13783                                self.registered_buffers.insert(
13784                                    buffer_id,
13785                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13786                                );
13787                            })
13788                        }
13789                    }
13790                }
13791                cx.emit(EditorEvent::BufferEdited);
13792                cx.emit(SearchEvent::MatchesInvalidated);
13793                if *singleton_buffer_edited {
13794                    if let Some(project) = &self.project {
13795                        let project = project.read(cx);
13796                        #[allow(clippy::mutable_key_type)]
13797                        let languages_affected = multibuffer
13798                            .read(cx)
13799                            .all_buffers()
13800                            .into_iter()
13801                            .filter_map(|buffer| {
13802                                let buffer = buffer.read(cx);
13803                                let language = buffer.language()?;
13804                                if project.is_local()
13805                                    && project
13806                                        .language_servers_for_local_buffer(buffer, cx)
13807                                        .count()
13808                                        == 0
13809                                {
13810                                    None
13811                                } else {
13812                                    Some(language)
13813                                }
13814                            })
13815                            .cloned()
13816                            .collect::<HashSet<_>>();
13817                        if !languages_affected.is_empty() {
13818                            self.refresh_inlay_hints(
13819                                InlayHintRefreshReason::BufferEdited(languages_affected),
13820                                cx,
13821                            );
13822                        }
13823                    }
13824                }
13825
13826                let Some(project) = &self.project else { return };
13827                let (telemetry, is_via_ssh) = {
13828                    let project = project.read(cx);
13829                    let telemetry = project.client().telemetry().clone();
13830                    let is_via_ssh = project.is_via_ssh();
13831                    (telemetry, is_via_ssh)
13832                };
13833                refresh_linked_ranges(self, window, cx);
13834                telemetry.log_edit_event("editor", is_via_ssh);
13835            }
13836            multi_buffer::Event::ExcerptsAdded {
13837                buffer,
13838                predecessor,
13839                excerpts,
13840            } => {
13841                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13842                let buffer_id = buffer.read(cx).remote_id();
13843                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13844                    if let Some(project) = &self.project {
13845                        get_uncommitted_diff_for_buffer(
13846                            project,
13847                            [buffer.clone()],
13848                            self.buffer.clone(),
13849                            cx,
13850                        );
13851                    }
13852                }
13853                cx.emit(EditorEvent::ExcerptsAdded {
13854                    buffer: buffer.clone(),
13855                    predecessor: *predecessor,
13856                    excerpts: excerpts.clone(),
13857                });
13858                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13859            }
13860            multi_buffer::Event::ExcerptsRemoved { ids } => {
13861                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13862                let buffer = self.buffer.read(cx);
13863                self.registered_buffers
13864                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13865                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13866            }
13867            multi_buffer::Event::ExcerptsEdited { ids } => {
13868                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13869            }
13870            multi_buffer::Event::ExcerptsExpanded { ids } => {
13871                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13872                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13873            }
13874            multi_buffer::Event::Reparsed(buffer_id) => {
13875                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13876
13877                cx.emit(EditorEvent::Reparsed(*buffer_id));
13878            }
13879            multi_buffer::Event::DiffHunksToggled => {
13880                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13881            }
13882            multi_buffer::Event::LanguageChanged(buffer_id) => {
13883                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13884                cx.emit(EditorEvent::Reparsed(*buffer_id));
13885                cx.notify();
13886            }
13887            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13888            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13889            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13890                cx.emit(EditorEvent::TitleChanged)
13891            }
13892            // multi_buffer::Event::DiffBaseChanged => {
13893            //     self.scrollbar_marker_state.dirty = true;
13894            //     cx.emit(EditorEvent::DiffBaseChanged);
13895            //     cx.notify();
13896            // }
13897            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13898            multi_buffer::Event::DiagnosticsUpdated => {
13899                self.refresh_active_diagnostics(cx);
13900                self.scrollbar_marker_state.dirty = true;
13901                cx.notify();
13902            }
13903            _ => {}
13904        };
13905    }
13906
13907    fn on_display_map_changed(
13908        &mut self,
13909        _: Entity<DisplayMap>,
13910        _: &mut Window,
13911        cx: &mut Context<Self>,
13912    ) {
13913        cx.notify();
13914    }
13915
13916    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13917        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13918        self.refresh_inline_completion(true, false, window, cx);
13919        self.refresh_inlay_hints(
13920            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13921                self.selections.newest_anchor().head(),
13922                &self.buffer.read(cx).snapshot(cx),
13923                cx,
13924            )),
13925            cx,
13926        );
13927
13928        let old_cursor_shape = self.cursor_shape;
13929
13930        {
13931            let editor_settings = EditorSettings::get_global(cx);
13932            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13933            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13934            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13935        }
13936
13937        if old_cursor_shape != self.cursor_shape {
13938            cx.emit(EditorEvent::CursorShapeChanged);
13939        }
13940
13941        let project_settings = ProjectSettings::get_global(cx);
13942        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13943
13944        if self.mode == EditorMode::Full {
13945            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13946            if self.git_blame_inline_enabled != inline_blame_enabled {
13947                self.toggle_git_blame_inline_internal(false, window, cx);
13948            }
13949        }
13950
13951        cx.notify();
13952    }
13953
13954    pub fn set_searchable(&mut self, searchable: bool) {
13955        self.searchable = searchable;
13956    }
13957
13958    pub fn searchable(&self) -> bool {
13959        self.searchable
13960    }
13961
13962    fn open_proposed_changes_editor(
13963        &mut self,
13964        _: &OpenProposedChangesEditor,
13965        window: &mut Window,
13966        cx: &mut Context<Self>,
13967    ) {
13968        let Some(workspace) = self.workspace() else {
13969            cx.propagate();
13970            return;
13971        };
13972
13973        let selections = self.selections.all::<usize>(cx);
13974        let multi_buffer = self.buffer.read(cx);
13975        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13976        let mut new_selections_by_buffer = HashMap::default();
13977        for selection in selections {
13978            for (buffer, range, _) in
13979                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13980            {
13981                let mut range = range.to_point(buffer);
13982                range.start.column = 0;
13983                range.end.column = buffer.line_len(range.end.row);
13984                new_selections_by_buffer
13985                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13986                    .or_insert(Vec::new())
13987                    .push(range)
13988            }
13989        }
13990
13991        let proposed_changes_buffers = new_selections_by_buffer
13992            .into_iter()
13993            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13994            .collect::<Vec<_>>();
13995        let proposed_changes_editor = cx.new(|cx| {
13996            ProposedChangesEditor::new(
13997                "Proposed changes",
13998                proposed_changes_buffers,
13999                self.project.clone(),
14000                window,
14001                cx,
14002            )
14003        });
14004
14005        window.defer(cx, move |window, cx| {
14006            workspace.update(cx, |workspace, cx| {
14007                workspace.active_pane().update(cx, |pane, cx| {
14008                    pane.add_item(
14009                        Box::new(proposed_changes_editor),
14010                        true,
14011                        true,
14012                        None,
14013                        window,
14014                        cx,
14015                    );
14016                });
14017            });
14018        });
14019    }
14020
14021    pub fn open_excerpts_in_split(
14022        &mut self,
14023        _: &OpenExcerptsSplit,
14024        window: &mut Window,
14025        cx: &mut Context<Self>,
14026    ) {
14027        self.open_excerpts_common(None, true, window, cx)
14028    }
14029
14030    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14031        self.open_excerpts_common(None, false, window, cx)
14032    }
14033
14034    fn open_excerpts_common(
14035        &mut self,
14036        jump_data: Option<JumpData>,
14037        split: bool,
14038        window: &mut Window,
14039        cx: &mut Context<Self>,
14040    ) {
14041        let Some(workspace) = self.workspace() else {
14042            cx.propagate();
14043            return;
14044        };
14045
14046        if self.buffer.read(cx).is_singleton() {
14047            cx.propagate();
14048            return;
14049        }
14050
14051        let mut new_selections_by_buffer = HashMap::default();
14052        match &jump_data {
14053            Some(JumpData::MultiBufferPoint {
14054                excerpt_id,
14055                position,
14056                anchor,
14057                line_offset_from_top,
14058            }) => {
14059                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14060                if let Some(buffer) = multi_buffer_snapshot
14061                    .buffer_id_for_excerpt(*excerpt_id)
14062                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14063                {
14064                    let buffer_snapshot = buffer.read(cx).snapshot();
14065                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14066                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14067                    } else {
14068                        buffer_snapshot.clip_point(*position, Bias::Left)
14069                    };
14070                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14071                    new_selections_by_buffer.insert(
14072                        buffer,
14073                        (
14074                            vec![jump_to_offset..jump_to_offset],
14075                            Some(*line_offset_from_top),
14076                        ),
14077                    );
14078                }
14079            }
14080            Some(JumpData::MultiBufferRow {
14081                row,
14082                line_offset_from_top,
14083            }) => {
14084                let point = MultiBufferPoint::new(row.0, 0);
14085                if let Some((buffer, buffer_point, _)) =
14086                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14087                {
14088                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14089                    new_selections_by_buffer
14090                        .entry(buffer)
14091                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14092                        .0
14093                        .push(buffer_offset..buffer_offset)
14094                }
14095            }
14096            None => {
14097                let selections = self.selections.all::<usize>(cx);
14098                let multi_buffer = self.buffer.read(cx);
14099                for selection in selections {
14100                    for (buffer, mut range, _) in multi_buffer
14101                        .snapshot(cx)
14102                        .range_to_buffer_ranges(selection.range())
14103                    {
14104                        // When editing branch buffers, jump to the corresponding location
14105                        // in their base buffer.
14106                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14107                        let buffer = buffer_handle.read(cx);
14108                        if let Some(base_buffer) = buffer.base_buffer() {
14109                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14110                            buffer_handle = base_buffer;
14111                        }
14112
14113                        if selection.reversed {
14114                            mem::swap(&mut range.start, &mut range.end);
14115                        }
14116                        new_selections_by_buffer
14117                            .entry(buffer_handle)
14118                            .or_insert((Vec::new(), None))
14119                            .0
14120                            .push(range)
14121                    }
14122                }
14123            }
14124        }
14125
14126        if new_selections_by_buffer.is_empty() {
14127            return;
14128        }
14129
14130        // We defer the pane interaction because we ourselves are a workspace item
14131        // and activating a new item causes the pane to call a method on us reentrantly,
14132        // which panics if we're on the stack.
14133        window.defer(cx, move |window, cx| {
14134            workspace.update(cx, |workspace, cx| {
14135                let pane = if split {
14136                    workspace.adjacent_pane(window, cx)
14137                } else {
14138                    workspace.active_pane().clone()
14139                };
14140
14141                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14142                    let editor = buffer
14143                        .read(cx)
14144                        .file()
14145                        .is_none()
14146                        .then(|| {
14147                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14148                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14149                            // Instead, we try to activate the existing editor in the pane first.
14150                            let (editor, pane_item_index) =
14151                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14152                                    let editor = item.downcast::<Editor>()?;
14153                                    let singleton_buffer =
14154                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14155                                    if singleton_buffer == buffer {
14156                                        Some((editor, i))
14157                                    } else {
14158                                        None
14159                                    }
14160                                })?;
14161                            pane.update(cx, |pane, cx| {
14162                                pane.activate_item(pane_item_index, true, true, window, cx)
14163                            });
14164                            Some(editor)
14165                        })
14166                        .flatten()
14167                        .unwrap_or_else(|| {
14168                            workspace.open_project_item::<Self>(
14169                                pane.clone(),
14170                                buffer,
14171                                true,
14172                                true,
14173                                window,
14174                                cx,
14175                            )
14176                        });
14177
14178                    editor.update(cx, |editor, cx| {
14179                        let autoscroll = match scroll_offset {
14180                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14181                            None => Autoscroll::newest(),
14182                        };
14183                        let nav_history = editor.nav_history.take();
14184                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14185                            s.select_ranges(ranges);
14186                        });
14187                        editor.nav_history = nav_history;
14188                    });
14189                }
14190            })
14191        });
14192    }
14193
14194    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14195        let snapshot = self.buffer.read(cx).read(cx);
14196        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14197        Some(
14198            ranges
14199                .iter()
14200                .map(move |range| {
14201                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14202                })
14203                .collect(),
14204        )
14205    }
14206
14207    fn selection_replacement_ranges(
14208        &self,
14209        range: Range<OffsetUtf16>,
14210        cx: &mut App,
14211    ) -> Vec<Range<OffsetUtf16>> {
14212        let selections = self.selections.all::<OffsetUtf16>(cx);
14213        let newest_selection = selections
14214            .iter()
14215            .max_by_key(|selection| selection.id)
14216            .unwrap();
14217        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14218        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14219        let snapshot = self.buffer.read(cx).read(cx);
14220        selections
14221            .into_iter()
14222            .map(|mut selection| {
14223                selection.start.0 =
14224                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14225                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14226                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14227                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14228            })
14229            .collect()
14230    }
14231
14232    fn report_editor_event(
14233        &self,
14234        event_type: &'static str,
14235        file_extension: Option<String>,
14236        cx: &App,
14237    ) {
14238        if cfg!(any(test, feature = "test-support")) {
14239            return;
14240        }
14241
14242        let Some(project) = &self.project else { return };
14243
14244        // If None, we are in a file without an extension
14245        let file = self
14246            .buffer
14247            .read(cx)
14248            .as_singleton()
14249            .and_then(|b| b.read(cx).file());
14250        let file_extension = file_extension.or(file
14251            .as_ref()
14252            .and_then(|file| Path::new(file.file_name(cx)).extension())
14253            .and_then(|e| e.to_str())
14254            .map(|a| a.to_string()));
14255
14256        let vim_mode = cx
14257            .global::<SettingsStore>()
14258            .raw_user_settings()
14259            .get("vim_mode")
14260            == Some(&serde_json::Value::Bool(true));
14261
14262        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14263        let copilot_enabled = edit_predictions_provider
14264            == language::language_settings::EditPredictionProvider::Copilot;
14265        let copilot_enabled_for_language = self
14266            .buffer
14267            .read(cx)
14268            .settings_at(0, cx)
14269            .show_edit_predictions;
14270
14271        let project = project.read(cx);
14272        telemetry::event!(
14273            event_type,
14274            file_extension,
14275            vim_mode,
14276            copilot_enabled,
14277            copilot_enabled_for_language,
14278            edit_predictions_provider,
14279            is_via_ssh = project.is_via_ssh(),
14280        );
14281    }
14282
14283    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14284    /// with each line being an array of {text, highlight} objects.
14285    fn copy_highlight_json(
14286        &mut self,
14287        _: &CopyHighlightJson,
14288        window: &mut Window,
14289        cx: &mut Context<Self>,
14290    ) {
14291        #[derive(Serialize)]
14292        struct Chunk<'a> {
14293            text: String,
14294            highlight: Option<&'a str>,
14295        }
14296
14297        let snapshot = self.buffer.read(cx).snapshot(cx);
14298        let range = self
14299            .selected_text_range(false, window, cx)
14300            .and_then(|selection| {
14301                if selection.range.is_empty() {
14302                    None
14303                } else {
14304                    Some(selection.range)
14305                }
14306            })
14307            .unwrap_or_else(|| 0..snapshot.len());
14308
14309        let chunks = snapshot.chunks(range, true);
14310        let mut lines = Vec::new();
14311        let mut line: VecDeque<Chunk> = VecDeque::new();
14312
14313        let Some(style) = self.style.as_ref() else {
14314            return;
14315        };
14316
14317        for chunk in chunks {
14318            let highlight = chunk
14319                .syntax_highlight_id
14320                .and_then(|id| id.name(&style.syntax));
14321            let mut chunk_lines = chunk.text.split('\n').peekable();
14322            while let Some(text) = chunk_lines.next() {
14323                let mut merged_with_last_token = false;
14324                if let Some(last_token) = line.back_mut() {
14325                    if last_token.highlight == highlight {
14326                        last_token.text.push_str(text);
14327                        merged_with_last_token = true;
14328                    }
14329                }
14330
14331                if !merged_with_last_token {
14332                    line.push_back(Chunk {
14333                        text: text.into(),
14334                        highlight,
14335                    });
14336                }
14337
14338                if chunk_lines.peek().is_some() {
14339                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14340                        line.pop_front();
14341                    }
14342                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14343                        line.pop_back();
14344                    }
14345
14346                    lines.push(mem::take(&mut line));
14347                }
14348            }
14349        }
14350
14351        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14352            return;
14353        };
14354        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14355    }
14356
14357    pub fn open_context_menu(
14358        &mut self,
14359        _: &OpenContextMenu,
14360        window: &mut Window,
14361        cx: &mut Context<Self>,
14362    ) {
14363        self.request_autoscroll(Autoscroll::newest(), cx);
14364        let position = self.selections.newest_display(cx).start;
14365        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14366    }
14367
14368    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14369        &self.inlay_hint_cache
14370    }
14371
14372    pub fn replay_insert_event(
14373        &mut self,
14374        text: &str,
14375        relative_utf16_range: Option<Range<isize>>,
14376        window: &mut Window,
14377        cx: &mut Context<Self>,
14378    ) {
14379        if !self.input_enabled {
14380            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14381            return;
14382        }
14383        if let Some(relative_utf16_range) = relative_utf16_range {
14384            let selections = self.selections.all::<OffsetUtf16>(cx);
14385            self.change_selections(None, window, cx, |s| {
14386                let new_ranges = selections.into_iter().map(|range| {
14387                    let start = OffsetUtf16(
14388                        range
14389                            .head()
14390                            .0
14391                            .saturating_add_signed(relative_utf16_range.start),
14392                    );
14393                    let end = OffsetUtf16(
14394                        range
14395                            .head()
14396                            .0
14397                            .saturating_add_signed(relative_utf16_range.end),
14398                    );
14399                    start..end
14400                });
14401                s.select_ranges(new_ranges);
14402            });
14403        }
14404
14405        self.handle_input(text, window, cx);
14406    }
14407
14408    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14409        let Some(provider) = self.semantics_provider.as_ref() else {
14410            return false;
14411        };
14412
14413        let mut supports = false;
14414        self.buffer().read(cx).for_each_buffer(|buffer| {
14415            supports |= provider.supports_inlay_hints(buffer, cx);
14416        });
14417        supports
14418    }
14419
14420    pub fn is_focused(&self, window: &Window) -> bool {
14421        self.focus_handle.is_focused(window)
14422    }
14423
14424    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14425        cx.emit(EditorEvent::Focused);
14426
14427        if let Some(descendant) = self
14428            .last_focused_descendant
14429            .take()
14430            .and_then(|descendant| descendant.upgrade())
14431        {
14432            window.focus(&descendant);
14433        } else {
14434            if let Some(blame) = self.blame.as_ref() {
14435                blame.update(cx, GitBlame::focus)
14436            }
14437
14438            self.blink_manager.update(cx, BlinkManager::enable);
14439            self.show_cursor_names(window, cx);
14440            self.buffer.update(cx, |buffer, cx| {
14441                buffer.finalize_last_transaction(cx);
14442                if self.leader_peer_id.is_none() {
14443                    buffer.set_active_selections(
14444                        &self.selections.disjoint_anchors(),
14445                        self.selections.line_mode,
14446                        self.cursor_shape,
14447                        cx,
14448                    );
14449                }
14450            });
14451        }
14452    }
14453
14454    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14455        cx.emit(EditorEvent::FocusedIn)
14456    }
14457
14458    fn handle_focus_out(
14459        &mut self,
14460        event: FocusOutEvent,
14461        _window: &mut Window,
14462        _cx: &mut Context<Self>,
14463    ) {
14464        if event.blurred != self.focus_handle {
14465            self.last_focused_descendant = Some(event.blurred);
14466        }
14467    }
14468
14469    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14470        self.blink_manager.update(cx, BlinkManager::disable);
14471        self.buffer
14472            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14473
14474        if let Some(blame) = self.blame.as_ref() {
14475            blame.update(cx, GitBlame::blur)
14476        }
14477        if !self.hover_state.focused(window, cx) {
14478            hide_hover(self, cx);
14479        }
14480
14481        self.hide_context_menu(window, cx);
14482        cx.emit(EditorEvent::Blurred);
14483        cx.notify();
14484    }
14485
14486    pub fn register_action<A: Action>(
14487        &mut self,
14488        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14489    ) -> Subscription {
14490        let id = self.next_editor_action_id.post_inc();
14491        let listener = Arc::new(listener);
14492        self.editor_actions.borrow_mut().insert(
14493            id,
14494            Box::new(move |window, _| {
14495                let listener = listener.clone();
14496                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14497                    let action = action.downcast_ref().unwrap();
14498                    if phase == DispatchPhase::Bubble {
14499                        listener(action, window, cx)
14500                    }
14501                })
14502            }),
14503        );
14504
14505        let editor_actions = self.editor_actions.clone();
14506        Subscription::new(move || {
14507            editor_actions.borrow_mut().remove(&id);
14508        })
14509    }
14510
14511    pub fn file_header_size(&self) -> u32 {
14512        FILE_HEADER_HEIGHT
14513    }
14514
14515    pub fn revert(
14516        &mut self,
14517        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14518        window: &mut Window,
14519        cx: &mut Context<Self>,
14520    ) {
14521        self.buffer().update(cx, |multi_buffer, cx| {
14522            for (buffer_id, changes) in revert_changes {
14523                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14524                    buffer.update(cx, |buffer, cx| {
14525                        buffer.edit(
14526                            changes.into_iter().map(|(range, text)| {
14527                                (range, text.to_string().map(Arc::<str>::from))
14528                            }),
14529                            None,
14530                            cx,
14531                        );
14532                    });
14533                }
14534            }
14535        });
14536        self.change_selections(None, window, cx, |selections| selections.refresh());
14537    }
14538
14539    pub fn to_pixel_point(
14540        &self,
14541        source: multi_buffer::Anchor,
14542        editor_snapshot: &EditorSnapshot,
14543        window: &mut Window,
14544    ) -> Option<gpui::Point<Pixels>> {
14545        let source_point = source.to_display_point(editor_snapshot);
14546        self.display_to_pixel_point(source_point, editor_snapshot, window)
14547    }
14548
14549    pub fn display_to_pixel_point(
14550        &self,
14551        source: DisplayPoint,
14552        editor_snapshot: &EditorSnapshot,
14553        window: &mut Window,
14554    ) -> Option<gpui::Point<Pixels>> {
14555        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14556        let text_layout_details = self.text_layout_details(window);
14557        let scroll_top = text_layout_details
14558            .scroll_anchor
14559            .scroll_position(editor_snapshot)
14560            .y;
14561
14562        if source.row().as_f32() < scroll_top.floor() {
14563            return None;
14564        }
14565        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14566        let source_y = line_height * (source.row().as_f32() - scroll_top);
14567        Some(gpui::Point::new(source_x, source_y))
14568    }
14569
14570    pub fn has_visible_completions_menu(&self) -> bool {
14571        !self.previewing_inline_completion
14572            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14573                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14574            })
14575    }
14576
14577    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14578        self.addons
14579            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14580    }
14581
14582    pub fn unregister_addon<T: Addon>(&mut self) {
14583        self.addons.remove(&std::any::TypeId::of::<T>());
14584    }
14585
14586    pub fn addon<T: Addon>(&self) -> Option<&T> {
14587        let type_id = std::any::TypeId::of::<T>();
14588        self.addons
14589            .get(&type_id)
14590            .and_then(|item| item.to_any().downcast_ref::<T>())
14591    }
14592
14593    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14594        let text_layout_details = self.text_layout_details(window);
14595        let style = &text_layout_details.editor_style;
14596        let font_id = window.text_system().resolve_font(&style.text.font());
14597        let font_size = style.text.font_size.to_pixels(window.rem_size());
14598        let line_height = style.text.line_height_in_pixels(window.rem_size());
14599        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14600
14601        gpui::Size::new(em_width, line_height)
14602    }
14603}
14604
14605fn get_uncommitted_diff_for_buffer(
14606    project: &Entity<Project>,
14607    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14608    buffer: Entity<MultiBuffer>,
14609    cx: &mut App,
14610) {
14611    let mut tasks = Vec::new();
14612    project.update(cx, |project, cx| {
14613        for buffer in buffers {
14614            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14615        }
14616    });
14617    cx.spawn(|mut cx| async move {
14618        let diffs = futures::future::join_all(tasks).await;
14619        buffer
14620            .update(&mut cx, |buffer, cx| {
14621                for diff in diffs.into_iter().flatten() {
14622                    buffer.add_diff(diff, cx);
14623                }
14624            })
14625            .ok();
14626    })
14627    .detach();
14628}
14629
14630fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14631    let tab_size = tab_size.get() as usize;
14632    let mut width = offset;
14633
14634    for ch in text.chars() {
14635        width += if ch == '\t' {
14636            tab_size - (width % tab_size)
14637        } else {
14638            1
14639        };
14640    }
14641
14642    width - offset
14643}
14644
14645#[cfg(test)]
14646mod tests {
14647    use super::*;
14648
14649    #[test]
14650    fn test_string_size_with_expanded_tabs() {
14651        let nz = |val| NonZeroU32::new(val).unwrap();
14652        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14653        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14654        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14655        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14656        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14657        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14658        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14659        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14660    }
14661}
14662
14663/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14664struct WordBreakingTokenizer<'a> {
14665    input: &'a str,
14666}
14667
14668impl<'a> WordBreakingTokenizer<'a> {
14669    fn new(input: &'a str) -> Self {
14670        Self { input }
14671    }
14672}
14673
14674fn is_char_ideographic(ch: char) -> bool {
14675    use unicode_script::Script::*;
14676    use unicode_script::UnicodeScript;
14677    matches!(ch.script(), Han | Tangut | Yi)
14678}
14679
14680fn is_grapheme_ideographic(text: &str) -> bool {
14681    text.chars().any(is_char_ideographic)
14682}
14683
14684fn is_grapheme_whitespace(text: &str) -> bool {
14685    text.chars().any(|x| x.is_whitespace())
14686}
14687
14688fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14689    text.chars().next().map_or(false, |ch| {
14690        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14691    })
14692}
14693
14694#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14695struct WordBreakToken<'a> {
14696    token: &'a str,
14697    grapheme_len: usize,
14698    is_whitespace: bool,
14699}
14700
14701impl<'a> Iterator for WordBreakingTokenizer<'a> {
14702    /// Yields a span, the count of graphemes in the token, and whether it was
14703    /// whitespace. Note that it also breaks at word boundaries.
14704    type Item = WordBreakToken<'a>;
14705
14706    fn next(&mut self) -> Option<Self::Item> {
14707        use unicode_segmentation::UnicodeSegmentation;
14708        if self.input.is_empty() {
14709            return None;
14710        }
14711
14712        let mut iter = self.input.graphemes(true).peekable();
14713        let mut offset = 0;
14714        let mut graphemes = 0;
14715        if let Some(first_grapheme) = iter.next() {
14716            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14717            offset += first_grapheme.len();
14718            graphemes += 1;
14719            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14720                if let Some(grapheme) = iter.peek().copied() {
14721                    if should_stay_with_preceding_ideograph(grapheme) {
14722                        offset += grapheme.len();
14723                        graphemes += 1;
14724                    }
14725                }
14726            } else {
14727                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14728                let mut next_word_bound = words.peek().copied();
14729                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14730                    next_word_bound = words.next();
14731                }
14732                while let Some(grapheme) = iter.peek().copied() {
14733                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14734                        break;
14735                    };
14736                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14737                        break;
14738                    };
14739                    offset += grapheme.len();
14740                    graphemes += 1;
14741                    iter.next();
14742                }
14743            }
14744            let token = &self.input[..offset];
14745            self.input = &self.input[offset..];
14746            if is_whitespace {
14747                Some(WordBreakToken {
14748                    token: " ",
14749                    grapheme_len: 1,
14750                    is_whitespace: true,
14751                })
14752            } else {
14753                Some(WordBreakToken {
14754                    token,
14755                    grapheme_len: graphemes,
14756                    is_whitespace: false,
14757                })
14758            }
14759        } else {
14760            None
14761        }
14762    }
14763}
14764
14765#[test]
14766fn test_word_breaking_tokenizer() {
14767    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14768        ("", &[]),
14769        ("  ", &[(" ", 1, true)]),
14770        ("Ʒ", &[("Ʒ", 1, false)]),
14771        ("Ǽ", &[("Ǽ", 1, false)]),
14772        ("", &[("", 1, false)]),
14773        ("⋑⋑", &[("⋑⋑", 2, false)]),
14774        (
14775            "原理,进而",
14776            &[
14777                ("", 1, false),
14778                ("理,", 2, false),
14779                ("", 1, false),
14780                ("", 1, false),
14781            ],
14782        ),
14783        (
14784            "hello world",
14785            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14786        ),
14787        (
14788            "hello, world",
14789            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14790        ),
14791        (
14792            "  hello world",
14793            &[
14794                (" ", 1, true),
14795                ("hello", 5, false),
14796                (" ", 1, true),
14797                ("world", 5, false),
14798            ],
14799        ),
14800        (
14801            "这是什么 \n 钢笔",
14802            &[
14803                ("", 1, false),
14804                ("", 1, false),
14805                ("", 1, false),
14806                ("", 1, false),
14807                (" ", 1, true),
14808                ("", 1, false),
14809                ("", 1, false),
14810            ],
14811        ),
14812        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14813    ];
14814
14815    for (input, result) in tests {
14816        assert_eq!(
14817            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14818            result
14819                .iter()
14820                .copied()
14821                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14822                    token,
14823                    grapheme_len,
14824                    is_whitespace,
14825                })
14826                .collect::<Vec<_>>()
14827        );
14828    }
14829}
14830
14831fn wrap_with_prefix(
14832    line_prefix: String,
14833    unwrapped_text: String,
14834    wrap_column: usize,
14835    tab_size: NonZeroU32,
14836) -> String {
14837    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14838    let mut wrapped_text = String::new();
14839    let mut current_line = line_prefix.clone();
14840
14841    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14842    let mut current_line_len = line_prefix_len;
14843    for WordBreakToken {
14844        token,
14845        grapheme_len,
14846        is_whitespace,
14847    } in tokenizer
14848    {
14849        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14850            wrapped_text.push_str(current_line.trim_end());
14851            wrapped_text.push('\n');
14852            current_line.truncate(line_prefix.len());
14853            current_line_len = line_prefix_len;
14854            if !is_whitespace {
14855                current_line.push_str(token);
14856                current_line_len += grapheme_len;
14857            }
14858        } else if !is_whitespace {
14859            current_line.push_str(token);
14860            current_line_len += grapheme_len;
14861        } else if current_line_len != line_prefix_len {
14862            current_line.push(' ');
14863            current_line_len += 1;
14864        }
14865    }
14866
14867    if !current_line.is_empty() {
14868        wrapped_text.push_str(&current_line);
14869    }
14870    wrapped_text
14871}
14872
14873#[test]
14874fn test_wrap_with_prefix() {
14875    assert_eq!(
14876        wrap_with_prefix(
14877            "# ".to_string(),
14878            "abcdefg".to_string(),
14879            4,
14880            NonZeroU32::new(4).unwrap()
14881        ),
14882        "# abcdefg"
14883    );
14884    assert_eq!(
14885        wrap_with_prefix(
14886            "".to_string(),
14887            "\thello world".to_string(),
14888            8,
14889            NonZeroU32::new(4).unwrap()
14890        ),
14891        "hello\nworld"
14892    );
14893    assert_eq!(
14894        wrap_with_prefix(
14895            "// ".to_string(),
14896            "xx \nyy zz aa bb cc".to_string(),
14897            12,
14898            NonZeroU32::new(4).unwrap()
14899        ),
14900        "// xx yy zz\n// aa bb cc"
14901    );
14902    assert_eq!(
14903        wrap_with_prefix(
14904            String::new(),
14905            "这是什么 \n 钢笔".to_string(),
14906            3,
14907            NonZeroU32::new(4).unwrap()
14908        ),
14909        "这是什\n么 钢\n"
14910    );
14911}
14912
14913pub trait CollaborationHub {
14914    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14915    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14916    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14917}
14918
14919impl CollaborationHub for Entity<Project> {
14920    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14921        self.read(cx).collaborators()
14922    }
14923
14924    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14925        self.read(cx).user_store().read(cx).participant_indices()
14926    }
14927
14928    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14929        let this = self.read(cx);
14930        let user_ids = this.collaborators().values().map(|c| c.user_id);
14931        this.user_store().read_with(cx, |user_store, cx| {
14932            user_store.participant_names(user_ids, cx)
14933        })
14934    }
14935}
14936
14937pub trait SemanticsProvider {
14938    fn hover(
14939        &self,
14940        buffer: &Entity<Buffer>,
14941        position: text::Anchor,
14942        cx: &mut App,
14943    ) -> Option<Task<Vec<project::Hover>>>;
14944
14945    fn inlay_hints(
14946        &self,
14947        buffer_handle: Entity<Buffer>,
14948        range: Range<text::Anchor>,
14949        cx: &mut App,
14950    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14951
14952    fn resolve_inlay_hint(
14953        &self,
14954        hint: InlayHint,
14955        buffer_handle: Entity<Buffer>,
14956        server_id: LanguageServerId,
14957        cx: &mut App,
14958    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14959
14960    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14961
14962    fn document_highlights(
14963        &self,
14964        buffer: &Entity<Buffer>,
14965        position: text::Anchor,
14966        cx: &mut App,
14967    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14968
14969    fn definitions(
14970        &self,
14971        buffer: &Entity<Buffer>,
14972        position: text::Anchor,
14973        kind: GotoDefinitionKind,
14974        cx: &mut App,
14975    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14976
14977    fn range_for_rename(
14978        &self,
14979        buffer: &Entity<Buffer>,
14980        position: text::Anchor,
14981        cx: &mut App,
14982    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14983
14984    fn perform_rename(
14985        &self,
14986        buffer: &Entity<Buffer>,
14987        position: text::Anchor,
14988        new_name: String,
14989        cx: &mut App,
14990    ) -> Option<Task<Result<ProjectTransaction>>>;
14991}
14992
14993pub trait CompletionProvider {
14994    fn completions(
14995        &self,
14996        buffer: &Entity<Buffer>,
14997        buffer_position: text::Anchor,
14998        trigger: CompletionContext,
14999        window: &mut Window,
15000        cx: &mut Context<Editor>,
15001    ) -> Task<Result<Vec<Completion>>>;
15002
15003    fn resolve_completions(
15004        &self,
15005        buffer: Entity<Buffer>,
15006        completion_indices: Vec<usize>,
15007        completions: Rc<RefCell<Box<[Completion]>>>,
15008        cx: &mut Context<Editor>,
15009    ) -> Task<Result<bool>>;
15010
15011    fn apply_additional_edits_for_completion(
15012        &self,
15013        _buffer: Entity<Buffer>,
15014        _completions: Rc<RefCell<Box<[Completion]>>>,
15015        _completion_index: usize,
15016        _push_to_history: bool,
15017        _cx: &mut Context<Editor>,
15018    ) -> Task<Result<Option<language::Transaction>>> {
15019        Task::ready(Ok(None))
15020    }
15021
15022    fn is_completion_trigger(
15023        &self,
15024        buffer: &Entity<Buffer>,
15025        position: language::Anchor,
15026        text: &str,
15027        trigger_in_words: bool,
15028        cx: &mut Context<Editor>,
15029    ) -> bool;
15030
15031    fn sort_completions(&self) -> bool {
15032        true
15033    }
15034}
15035
15036pub trait CodeActionProvider {
15037    fn id(&self) -> Arc<str>;
15038
15039    fn code_actions(
15040        &self,
15041        buffer: &Entity<Buffer>,
15042        range: Range<text::Anchor>,
15043        window: &mut Window,
15044        cx: &mut App,
15045    ) -> Task<Result<Vec<CodeAction>>>;
15046
15047    fn apply_code_action(
15048        &self,
15049        buffer_handle: Entity<Buffer>,
15050        action: CodeAction,
15051        excerpt_id: ExcerptId,
15052        push_to_history: bool,
15053        window: &mut Window,
15054        cx: &mut App,
15055    ) -> Task<Result<ProjectTransaction>>;
15056}
15057
15058impl CodeActionProvider for Entity<Project> {
15059    fn id(&self) -> Arc<str> {
15060        "project".into()
15061    }
15062
15063    fn code_actions(
15064        &self,
15065        buffer: &Entity<Buffer>,
15066        range: Range<text::Anchor>,
15067        _window: &mut Window,
15068        cx: &mut App,
15069    ) -> Task<Result<Vec<CodeAction>>> {
15070        self.update(cx, |project, cx| {
15071            project.code_actions(buffer, range, None, cx)
15072        })
15073    }
15074
15075    fn apply_code_action(
15076        &self,
15077        buffer_handle: Entity<Buffer>,
15078        action: CodeAction,
15079        _excerpt_id: ExcerptId,
15080        push_to_history: bool,
15081        _window: &mut Window,
15082        cx: &mut App,
15083    ) -> Task<Result<ProjectTransaction>> {
15084        self.update(cx, |project, cx| {
15085            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15086        })
15087    }
15088}
15089
15090fn snippet_completions(
15091    project: &Project,
15092    buffer: &Entity<Buffer>,
15093    buffer_position: text::Anchor,
15094    cx: &mut App,
15095) -> Task<Result<Vec<Completion>>> {
15096    let language = buffer.read(cx).language_at(buffer_position);
15097    let language_name = language.as_ref().map(|language| language.lsp_id());
15098    let snippet_store = project.snippets().read(cx);
15099    let snippets = snippet_store.snippets_for(language_name, cx);
15100
15101    if snippets.is_empty() {
15102        return Task::ready(Ok(vec![]));
15103    }
15104    let snapshot = buffer.read(cx).text_snapshot();
15105    let chars: String = snapshot
15106        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15107        .collect();
15108
15109    let scope = language.map(|language| language.default_scope());
15110    let executor = cx.background_executor().clone();
15111
15112    cx.background_executor().spawn(async move {
15113        let classifier = CharClassifier::new(scope).for_completion(true);
15114        let mut last_word = chars
15115            .chars()
15116            .take_while(|c| classifier.is_word(*c))
15117            .collect::<String>();
15118        last_word = last_word.chars().rev().collect();
15119
15120        if last_word.is_empty() {
15121            return Ok(vec![]);
15122        }
15123
15124        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15125        let to_lsp = |point: &text::Anchor| {
15126            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15127            point_to_lsp(end)
15128        };
15129        let lsp_end = to_lsp(&buffer_position);
15130
15131        let candidates = snippets
15132            .iter()
15133            .enumerate()
15134            .flat_map(|(ix, snippet)| {
15135                snippet
15136                    .prefix
15137                    .iter()
15138                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15139            })
15140            .collect::<Vec<StringMatchCandidate>>();
15141
15142        let mut matches = fuzzy::match_strings(
15143            &candidates,
15144            &last_word,
15145            last_word.chars().any(|c| c.is_uppercase()),
15146            100,
15147            &Default::default(),
15148            executor,
15149        )
15150        .await;
15151
15152        // Remove all candidates where the query's start does not match the start of any word in the candidate
15153        if let Some(query_start) = last_word.chars().next() {
15154            matches.retain(|string_match| {
15155                split_words(&string_match.string).any(|word| {
15156                    // Check that the first codepoint of the word as lowercase matches the first
15157                    // codepoint of the query as lowercase
15158                    word.chars()
15159                        .flat_map(|codepoint| codepoint.to_lowercase())
15160                        .zip(query_start.to_lowercase())
15161                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15162                })
15163            });
15164        }
15165
15166        let matched_strings = matches
15167            .into_iter()
15168            .map(|m| m.string)
15169            .collect::<HashSet<_>>();
15170
15171        let result: Vec<Completion> = snippets
15172            .into_iter()
15173            .filter_map(|snippet| {
15174                let matching_prefix = snippet
15175                    .prefix
15176                    .iter()
15177                    .find(|prefix| matched_strings.contains(*prefix))?;
15178                let start = as_offset - last_word.len();
15179                let start = snapshot.anchor_before(start);
15180                let range = start..buffer_position;
15181                let lsp_start = to_lsp(&start);
15182                let lsp_range = lsp::Range {
15183                    start: lsp_start,
15184                    end: lsp_end,
15185                };
15186                Some(Completion {
15187                    old_range: range,
15188                    new_text: snippet.body.clone(),
15189                    resolved: false,
15190                    label: CodeLabel {
15191                        text: matching_prefix.clone(),
15192                        runs: vec![],
15193                        filter_range: 0..matching_prefix.len(),
15194                    },
15195                    server_id: LanguageServerId(usize::MAX),
15196                    documentation: snippet
15197                        .description
15198                        .clone()
15199                        .map(CompletionDocumentation::SingleLine),
15200                    lsp_completion: lsp::CompletionItem {
15201                        label: snippet.prefix.first().unwrap().clone(),
15202                        kind: Some(CompletionItemKind::SNIPPET),
15203                        label_details: snippet.description.as_ref().map(|description| {
15204                            lsp::CompletionItemLabelDetails {
15205                                detail: Some(description.clone()),
15206                                description: None,
15207                            }
15208                        }),
15209                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15210                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15211                            lsp::InsertReplaceEdit {
15212                                new_text: snippet.body.clone(),
15213                                insert: lsp_range,
15214                                replace: lsp_range,
15215                            },
15216                        )),
15217                        filter_text: Some(snippet.body.clone()),
15218                        sort_text: Some(char::MAX.to_string()),
15219                        ..Default::default()
15220                    },
15221                    confirm: None,
15222                })
15223            })
15224            .collect();
15225
15226        Ok(result)
15227    })
15228}
15229
15230impl CompletionProvider for Entity<Project> {
15231    fn completions(
15232        &self,
15233        buffer: &Entity<Buffer>,
15234        buffer_position: text::Anchor,
15235        options: CompletionContext,
15236        _window: &mut Window,
15237        cx: &mut Context<Editor>,
15238    ) -> Task<Result<Vec<Completion>>> {
15239        self.update(cx, |project, cx| {
15240            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15241            let project_completions = project.completions(buffer, buffer_position, options, cx);
15242            cx.background_executor().spawn(async move {
15243                let mut completions = project_completions.await?;
15244                let snippets_completions = snippets.await?;
15245                completions.extend(snippets_completions);
15246                Ok(completions)
15247            })
15248        })
15249    }
15250
15251    fn resolve_completions(
15252        &self,
15253        buffer: Entity<Buffer>,
15254        completion_indices: Vec<usize>,
15255        completions: Rc<RefCell<Box<[Completion]>>>,
15256        cx: &mut Context<Editor>,
15257    ) -> Task<Result<bool>> {
15258        self.update(cx, |project, cx| {
15259            project.lsp_store().update(cx, |lsp_store, cx| {
15260                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15261            })
15262        })
15263    }
15264
15265    fn apply_additional_edits_for_completion(
15266        &self,
15267        buffer: Entity<Buffer>,
15268        completions: Rc<RefCell<Box<[Completion]>>>,
15269        completion_index: usize,
15270        push_to_history: bool,
15271        cx: &mut Context<Editor>,
15272    ) -> Task<Result<Option<language::Transaction>>> {
15273        self.update(cx, |project, cx| {
15274            project.lsp_store().update(cx, |lsp_store, cx| {
15275                lsp_store.apply_additional_edits_for_completion(
15276                    buffer,
15277                    completions,
15278                    completion_index,
15279                    push_to_history,
15280                    cx,
15281                )
15282            })
15283        })
15284    }
15285
15286    fn is_completion_trigger(
15287        &self,
15288        buffer: &Entity<Buffer>,
15289        position: language::Anchor,
15290        text: &str,
15291        trigger_in_words: bool,
15292        cx: &mut Context<Editor>,
15293    ) -> bool {
15294        let mut chars = text.chars();
15295        let char = if let Some(char) = chars.next() {
15296            char
15297        } else {
15298            return false;
15299        };
15300        if chars.next().is_some() {
15301            return false;
15302        }
15303
15304        let buffer = buffer.read(cx);
15305        let snapshot = buffer.snapshot();
15306        if !snapshot.settings_at(position, cx).show_completions_on_input {
15307            return false;
15308        }
15309        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15310        if trigger_in_words && classifier.is_word(char) {
15311            return true;
15312        }
15313
15314        buffer.completion_triggers().contains(text)
15315    }
15316}
15317
15318impl SemanticsProvider for Entity<Project> {
15319    fn hover(
15320        &self,
15321        buffer: &Entity<Buffer>,
15322        position: text::Anchor,
15323        cx: &mut App,
15324    ) -> Option<Task<Vec<project::Hover>>> {
15325        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15326    }
15327
15328    fn document_highlights(
15329        &self,
15330        buffer: &Entity<Buffer>,
15331        position: text::Anchor,
15332        cx: &mut App,
15333    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15334        Some(self.update(cx, |project, cx| {
15335            project.document_highlights(buffer, position, cx)
15336        }))
15337    }
15338
15339    fn definitions(
15340        &self,
15341        buffer: &Entity<Buffer>,
15342        position: text::Anchor,
15343        kind: GotoDefinitionKind,
15344        cx: &mut App,
15345    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15346        Some(self.update(cx, |project, cx| match kind {
15347            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15348            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15349            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15350            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15351        }))
15352    }
15353
15354    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15355        // TODO: make this work for remote projects
15356        self.read(cx)
15357            .language_servers_for_local_buffer(buffer.read(cx), cx)
15358            .any(
15359                |(_, server)| match server.capabilities().inlay_hint_provider {
15360                    Some(lsp::OneOf::Left(enabled)) => enabled,
15361                    Some(lsp::OneOf::Right(_)) => true,
15362                    None => false,
15363                },
15364            )
15365    }
15366
15367    fn inlay_hints(
15368        &self,
15369        buffer_handle: Entity<Buffer>,
15370        range: Range<text::Anchor>,
15371        cx: &mut App,
15372    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15373        Some(self.update(cx, |project, cx| {
15374            project.inlay_hints(buffer_handle, range, cx)
15375        }))
15376    }
15377
15378    fn resolve_inlay_hint(
15379        &self,
15380        hint: InlayHint,
15381        buffer_handle: Entity<Buffer>,
15382        server_id: LanguageServerId,
15383        cx: &mut App,
15384    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15385        Some(self.update(cx, |project, cx| {
15386            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15387        }))
15388    }
15389
15390    fn range_for_rename(
15391        &self,
15392        buffer: &Entity<Buffer>,
15393        position: text::Anchor,
15394        cx: &mut App,
15395    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15396        Some(self.update(cx, |project, cx| {
15397            let buffer = buffer.clone();
15398            let task = project.prepare_rename(buffer.clone(), position, cx);
15399            cx.spawn(|_, mut cx| async move {
15400                Ok(match task.await? {
15401                    PrepareRenameResponse::Success(range) => Some(range),
15402                    PrepareRenameResponse::InvalidPosition => None,
15403                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15404                        // Fallback on using TreeSitter info to determine identifier range
15405                        buffer.update(&mut cx, |buffer, _| {
15406                            let snapshot = buffer.snapshot();
15407                            let (range, kind) = snapshot.surrounding_word(position);
15408                            if kind != Some(CharKind::Word) {
15409                                return None;
15410                            }
15411                            Some(
15412                                snapshot.anchor_before(range.start)
15413                                    ..snapshot.anchor_after(range.end),
15414                            )
15415                        })?
15416                    }
15417                })
15418            })
15419        }))
15420    }
15421
15422    fn perform_rename(
15423        &self,
15424        buffer: &Entity<Buffer>,
15425        position: text::Anchor,
15426        new_name: String,
15427        cx: &mut App,
15428    ) -> Option<Task<Result<ProjectTransaction>>> {
15429        Some(self.update(cx, |project, cx| {
15430            project.perform_rename(buffer.clone(), position, new_name, cx)
15431        }))
15432    }
15433}
15434
15435fn inlay_hint_settings(
15436    location: Anchor,
15437    snapshot: &MultiBufferSnapshot,
15438    cx: &mut Context<Editor>,
15439) -> InlayHintSettings {
15440    let file = snapshot.file_at(location);
15441    let language = snapshot.language_at(location).map(|l| l.name());
15442    language_settings(language, file, cx).inlay_hints
15443}
15444
15445fn consume_contiguous_rows(
15446    contiguous_row_selections: &mut Vec<Selection<Point>>,
15447    selection: &Selection<Point>,
15448    display_map: &DisplaySnapshot,
15449    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15450) -> (MultiBufferRow, MultiBufferRow) {
15451    contiguous_row_selections.push(selection.clone());
15452    let start_row = MultiBufferRow(selection.start.row);
15453    let mut end_row = ending_row(selection, display_map);
15454
15455    while let Some(next_selection) = selections.peek() {
15456        if next_selection.start.row <= end_row.0 {
15457            end_row = ending_row(next_selection, display_map);
15458            contiguous_row_selections.push(selections.next().unwrap().clone());
15459        } else {
15460            break;
15461        }
15462    }
15463    (start_row, end_row)
15464}
15465
15466fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15467    if next_selection.end.column > 0 || next_selection.is_empty() {
15468        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15469    } else {
15470        MultiBufferRow(next_selection.end.row)
15471    }
15472}
15473
15474impl EditorSnapshot {
15475    pub fn remote_selections_in_range<'a>(
15476        &'a self,
15477        range: &'a Range<Anchor>,
15478        collaboration_hub: &dyn CollaborationHub,
15479        cx: &'a App,
15480    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15481        let participant_names = collaboration_hub.user_names(cx);
15482        let participant_indices = collaboration_hub.user_participant_indices(cx);
15483        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15484        let collaborators_by_replica_id = collaborators_by_peer_id
15485            .iter()
15486            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15487            .collect::<HashMap<_, _>>();
15488        self.buffer_snapshot
15489            .selections_in_range(range, false)
15490            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15491                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15492                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15493                let user_name = participant_names.get(&collaborator.user_id).cloned();
15494                Some(RemoteSelection {
15495                    replica_id,
15496                    selection,
15497                    cursor_shape,
15498                    line_mode,
15499                    participant_index,
15500                    peer_id: collaborator.peer_id,
15501                    user_name,
15502                })
15503            })
15504    }
15505
15506    pub fn hunks_for_ranges(
15507        &self,
15508        ranges: impl Iterator<Item = Range<Point>>,
15509    ) -> Vec<MultiBufferDiffHunk> {
15510        let mut hunks = Vec::new();
15511        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15512            HashMap::default();
15513        for query_range in ranges {
15514            let query_rows =
15515                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15516            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15517                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15518            ) {
15519                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15520                // when the caret is just above or just below the deleted hunk.
15521                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15522                let related_to_selection = if allow_adjacent {
15523                    hunk.row_range.overlaps(&query_rows)
15524                        || hunk.row_range.start == query_rows.end
15525                        || hunk.row_range.end == query_rows.start
15526                } else {
15527                    hunk.row_range.overlaps(&query_rows)
15528                };
15529                if related_to_selection {
15530                    if !processed_buffer_rows
15531                        .entry(hunk.buffer_id)
15532                        .or_default()
15533                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15534                    {
15535                        continue;
15536                    }
15537                    hunks.push(hunk);
15538                }
15539            }
15540        }
15541
15542        hunks
15543    }
15544
15545    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15546        self.display_snapshot.buffer_snapshot.language_at(position)
15547    }
15548
15549    pub fn is_focused(&self) -> bool {
15550        self.is_focused
15551    }
15552
15553    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15554        self.placeholder_text.as_ref()
15555    }
15556
15557    pub fn scroll_position(&self) -> gpui::Point<f32> {
15558        self.scroll_anchor.scroll_position(&self.display_snapshot)
15559    }
15560
15561    fn gutter_dimensions(
15562        &self,
15563        font_id: FontId,
15564        font_size: Pixels,
15565        max_line_number_width: Pixels,
15566        cx: &App,
15567    ) -> Option<GutterDimensions> {
15568        if !self.show_gutter {
15569            return None;
15570        }
15571
15572        let descent = cx.text_system().descent(font_id, font_size);
15573        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15574        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15575
15576        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15577            matches!(
15578                ProjectSettings::get_global(cx).git.git_gutter,
15579                Some(GitGutterSetting::TrackedFiles)
15580            )
15581        });
15582        let gutter_settings = EditorSettings::get_global(cx).gutter;
15583        let show_line_numbers = self
15584            .show_line_numbers
15585            .unwrap_or(gutter_settings.line_numbers);
15586        let line_gutter_width = if show_line_numbers {
15587            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15588            let min_width_for_number_on_gutter = em_advance * 4.0;
15589            max_line_number_width.max(min_width_for_number_on_gutter)
15590        } else {
15591            0.0.into()
15592        };
15593
15594        let show_code_actions = self
15595            .show_code_actions
15596            .unwrap_or(gutter_settings.code_actions);
15597
15598        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15599
15600        let git_blame_entries_width =
15601            self.git_blame_gutter_max_author_length
15602                .map(|max_author_length| {
15603                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15604
15605                    /// The number of characters to dedicate to gaps and margins.
15606                    const SPACING_WIDTH: usize = 4;
15607
15608                    let max_char_count = max_author_length
15609                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15610                        + ::git::SHORT_SHA_LENGTH
15611                        + MAX_RELATIVE_TIMESTAMP.len()
15612                        + SPACING_WIDTH;
15613
15614                    em_advance * max_char_count
15615                });
15616
15617        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15618        left_padding += if show_code_actions || show_runnables {
15619            em_width * 3.0
15620        } else if show_git_gutter && show_line_numbers {
15621            em_width * 2.0
15622        } else if show_git_gutter || show_line_numbers {
15623            em_width
15624        } else {
15625            px(0.)
15626        };
15627
15628        let right_padding = if gutter_settings.folds && show_line_numbers {
15629            em_width * 4.0
15630        } else if gutter_settings.folds {
15631            em_width * 3.0
15632        } else if show_line_numbers {
15633            em_width
15634        } else {
15635            px(0.)
15636        };
15637
15638        Some(GutterDimensions {
15639            left_padding,
15640            right_padding,
15641            width: line_gutter_width + left_padding + right_padding,
15642            margin: -descent,
15643            git_blame_entries_width,
15644        })
15645    }
15646
15647    pub fn render_crease_toggle(
15648        &self,
15649        buffer_row: MultiBufferRow,
15650        row_contains_cursor: bool,
15651        editor: Entity<Editor>,
15652        window: &mut Window,
15653        cx: &mut App,
15654    ) -> Option<AnyElement> {
15655        let folded = self.is_line_folded(buffer_row);
15656        let mut is_foldable = false;
15657
15658        if let Some(crease) = self
15659            .crease_snapshot
15660            .query_row(buffer_row, &self.buffer_snapshot)
15661        {
15662            is_foldable = true;
15663            match crease {
15664                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15665                    if let Some(render_toggle) = render_toggle {
15666                        let toggle_callback =
15667                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15668                                if folded {
15669                                    editor.update(cx, |editor, cx| {
15670                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15671                                    });
15672                                } else {
15673                                    editor.update(cx, |editor, cx| {
15674                                        editor.unfold_at(
15675                                            &crate::UnfoldAt { buffer_row },
15676                                            window,
15677                                            cx,
15678                                        )
15679                                    });
15680                                }
15681                            });
15682                        return Some((render_toggle)(
15683                            buffer_row,
15684                            folded,
15685                            toggle_callback,
15686                            window,
15687                            cx,
15688                        ));
15689                    }
15690                }
15691            }
15692        }
15693
15694        is_foldable |= self.starts_indent(buffer_row);
15695
15696        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15697            Some(
15698                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15699                    .toggle_state(folded)
15700                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15701                        if folded {
15702                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15703                        } else {
15704                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15705                        }
15706                    }))
15707                    .into_any_element(),
15708            )
15709        } else {
15710            None
15711        }
15712    }
15713
15714    pub fn render_crease_trailer(
15715        &self,
15716        buffer_row: MultiBufferRow,
15717        window: &mut Window,
15718        cx: &mut App,
15719    ) -> Option<AnyElement> {
15720        let folded = self.is_line_folded(buffer_row);
15721        if let Crease::Inline { render_trailer, .. } = self
15722            .crease_snapshot
15723            .query_row(buffer_row, &self.buffer_snapshot)?
15724        {
15725            let render_trailer = render_trailer.as_ref()?;
15726            Some(render_trailer(buffer_row, folded, window, cx))
15727        } else {
15728            None
15729        }
15730    }
15731}
15732
15733impl Deref for EditorSnapshot {
15734    type Target = DisplaySnapshot;
15735
15736    fn deref(&self) -> &Self::Target {
15737        &self.display_snapshot
15738    }
15739}
15740
15741#[derive(Clone, Debug, PartialEq, Eq)]
15742pub enum EditorEvent {
15743    InputIgnored {
15744        text: Arc<str>,
15745    },
15746    InputHandled {
15747        utf16_range_to_replace: Option<Range<isize>>,
15748        text: Arc<str>,
15749    },
15750    ExcerptsAdded {
15751        buffer: Entity<Buffer>,
15752        predecessor: ExcerptId,
15753        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15754    },
15755    ExcerptsRemoved {
15756        ids: Vec<ExcerptId>,
15757    },
15758    BufferFoldToggled {
15759        ids: Vec<ExcerptId>,
15760        folded: bool,
15761    },
15762    ExcerptsEdited {
15763        ids: Vec<ExcerptId>,
15764    },
15765    ExcerptsExpanded {
15766        ids: Vec<ExcerptId>,
15767    },
15768    BufferEdited,
15769    Edited {
15770        transaction_id: clock::Lamport,
15771    },
15772    Reparsed(BufferId),
15773    Focused,
15774    FocusedIn,
15775    Blurred,
15776    DirtyChanged,
15777    Saved,
15778    TitleChanged,
15779    DiffBaseChanged,
15780    SelectionsChanged {
15781        local: bool,
15782    },
15783    ScrollPositionChanged {
15784        local: bool,
15785        autoscroll: bool,
15786    },
15787    Closed,
15788    TransactionUndone {
15789        transaction_id: clock::Lamport,
15790    },
15791    TransactionBegun {
15792        transaction_id: clock::Lamport,
15793    },
15794    Reloaded,
15795    CursorShapeChanged,
15796}
15797
15798impl EventEmitter<EditorEvent> for Editor {}
15799
15800impl Focusable for Editor {
15801    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15802        self.focus_handle.clone()
15803    }
15804}
15805
15806impl Render for Editor {
15807    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15808        let settings = ThemeSettings::get_global(cx);
15809
15810        let mut text_style = match self.mode {
15811            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15812                color: cx.theme().colors().editor_foreground,
15813                font_family: settings.ui_font.family.clone(),
15814                font_features: settings.ui_font.features.clone(),
15815                font_fallbacks: settings.ui_font.fallbacks.clone(),
15816                font_size: rems(0.875).into(),
15817                font_weight: settings.ui_font.weight,
15818                line_height: relative(settings.buffer_line_height.value()),
15819                ..Default::default()
15820            },
15821            EditorMode::Full => TextStyle {
15822                color: cx.theme().colors().editor_foreground,
15823                font_family: settings.buffer_font.family.clone(),
15824                font_features: settings.buffer_font.features.clone(),
15825                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15826                font_size: settings.buffer_font_size().into(),
15827                font_weight: settings.buffer_font.weight,
15828                line_height: relative(settings.buffer_line_height.value()),
15829                ..Default::default()
15830            },
15831        };
15832        if let Some(text_style_refinement) = &self.text_style_refinement {
15833            text_style.refine(text_style_refinement)
15834        }
15835
15836        let background = match self.mode {
15837            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15838            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15839            EditorMode::Full => cx.theme().colors().editor_background,
15840        };
15841
15842        EditorElement::new(
15843            &cx.entity(),
15844            EditorStyle {
15845                background,
15846                local_player: cx.theme().players().local(),
15847                text: text_style,
15848                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15849                syntax: cx.theme().syntax().clone(),
15850                status: cx.theme().status().clone(),
15851                inlay_hints_style: make_inlay_hints_style(cx),
15852                inline_completion_styles: make_suggestion_styles(cx),
15853                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15854            },
15855        )
15856    }
15857}
15858
15859impl EntityInputHandler for Editor {
15860    fn text_for_range(
15861        &mut self,
15862        range_utf16: Range<usize>,
15863        adjusted_range: &mut Option<Range<usize>>,
15864        _: &mut Window,
15865        cx: &mut Context<Self>,
15866    ) -> Option<String> {
15867        let snapshot = self.buffer.read(cx).read(cx);
15868        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15869        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15870        if (start.0..end.0) != range_utf16 {
15871            adjusted_range.replace(start.0..end.0);
15872        }
15873        Some(snapshot.text_for_range(start..end).collect())
15874    }
15875
15876    fn selected_text_range(
15877        &mut self,
15878        ignore_disabled_input: bool,
15879        _: &mut Window,
15880        cx: &mut Context<Self>,
15881    ) -> Option<UTF16Selection> {
15882        // Prevent the IME menu from appearing when holding down an alphabetic key
15883        // while input is disabled.
15884        if !ignore_disabled_input && !self.input_enabled {
15885            return None;
15886        }
15887
15888        let selection = self.selections.newest::<OffsetUtf16>(cx);
15889        let range = selection.range();
15890
15891        Some(UTF16Selection {
15892            range: range.start.0..range.end.0,
15893            reversed: selection.reversed,
15894        })
15895    }
15896
15897    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15898        let snapshot = self.buffer.read(cx).read(cx);
15899        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15900        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15901    }
15902
15903    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15904        self.clear_highlights::<InputComposition>(cx);
15905        self.ime_transaction.take();
15906    }
15907
15908    fn replace_text_in_range(
15909        &mut self,
15910        range_utf16: Option<Range<usize>>,
15911        text: &str,
15912        window: &mut Window,
15913        cx: &mut Context<Self>,
15914    ) {
15915        if !self.input_enabled {
15916            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15917            return;
15918        }
15919
15920        self.transact(window, cx, |this, window, cx| {
15921            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15922                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15923                Some(this.selection_replacement_ranges(range_utf16, cx))
15924            } else {
15925                this.marked_text_ranges(cx)
15926            };
15927
15928            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15929                let newest_selection_id = this.selections.newest_anchor().id;
15930                this.selections
15931                    .all::<OffsetUtf16>(cx)
15932                    .iter()
15933                    .zip(ranges_to_replace.iter())
15934                    .find_map(|(selection, range)| {
15935                        if selection.id == newest_selection_id {
15936                            Some(
15937                                (range.start.0 as isize - selection.head().0 as isize)
15938                                    ..(range.end.0 as isize - selection.head().0 as isize),
15939                            )
15940                        } else {
15941                            None
15942                        }
15943                    })
15944            });
15945
15946            cx.emit(EditorEvent::InputHandled {
15947                utf16_range_to_replace: range_to_replace,
15948                text: text.into(),
15949            });
15950
15951            if let Some(new_selected_ranges) = new_selected_ranges {
15952                this.change_selections(None, window, cx, |selections| {
15953                    selections.select_ranges(new_selected_ranges)
15954                });
15955                this.backspace(&Default::default(), window, cx);
15956            }
15957
15958            this.handle_input(text, window, cx);
15959        });
15960
15961        if let Some(transaction) = self.ime_transaction {
15962            self.buffer.update(cx, |buffer, cx| {
15963                buffer.group_until_transaction(transaction, cx);
15964            });
15965        }
15966
15967        self.unmark_text(window, cx);
15968    }
15969
15970    fn replace_and_mark_text_in_range(
15971        &mut self,
15972        range_utf16: Option<Range<usize>>,
15973        text: &str,
15974        new_selected_range_utf16: Option<Range<usize>>,
15975        window: &mut Window,
15976        cx: &mut Context<Self>,
15977    ) {
15978        if !self.input_enabled {
15979            return;
15980        }
15981
15982        let transaction = self.transact(window, cx, |this, window, cx| {
15983            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15984                let snapshot = this.buffer.read(cx).read(cx);
15985                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15986                    for marked_range in &mut marked_ranges {
15987                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15988                        marked_range.start.0 += relative_range_utf16.start;
15989                        marked_range.start =
15990                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15991                        marked_range.end =
15992                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15993                    }
15994                }
15995                Some(marked_ranges)
15996            } else if let Some(range_utf16) = range_utf16 {
15997                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15998                Some(this.selection_replacement_ranges(range_utf16, cx))
15999            } else {
16000                None
16001            };
16002
16003            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16004                let newest_selection_id = this.selections.newest_anchor().id;
16005                this.selections
16006                    .all::<OffsetUtf16>(cx)
16007                    .iter()
16008                    .zip(ranges_to_replace.iter())
16009                    .find_map(|(selection, range)| {
16010                        if selection.id == newest_selection_id {
16011                            Some(
16012                                (range.start.0 as isize - selection.head().0 as isize)
16013                                    ..(range.end.0 as isize - selection.head().0 as isize),
16014                            )
16015                        } else {
16016                            None
16017                        }
16018                    })
16019            });
16020
16021            cx.emit(EditorEvent::InputHandled {
16022                utf16_range_to_replace: range_to_replace,
16023                text: text.into(),
16024            });
16025
16026            if let Some(ranges) = ranges_to_replace {
16027                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16028            }
16029
16030            let marked_ranges = {
16031                let snapshot = this.buffer.read(cx).read(cx);
16032                this.selections
16033                    .disjoint_anchors()
16034                    .iter()
16035                    .map(|selection| {
16036                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16037                    })
16038                    .collect::<Vec<_>>()
16039            };
16040
16041            if text.is_empty() {
16042                this.unmark_text(window, cx);
16043            } else {
16044                this.highlight_text::<InputComposition>(
16045                    marked_ranges.clone(),
16046                    HighlightStyle {
16047                        underline: Some(UnderlineStyle {
16048                            thickness: px(1.),
16049                            color: None,
16050                            wavy: false,
16051                        }),
16052                        ..Default::default()
16053                    },
16054                    cx,
16055                );
16056            }
16057
16058            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16059            let use_autoclose = this.use_autoclose;
16060            let use_auto_surround = this.use_auto_surround;
16061            this.set_use_autoclose(false);
16062            this.set_use_auto_surround(false);
16063            this.handle_input(text, window, cx);
16064            this.set_use_autoclose(use_autoclose);
16065            this.set_use_auto_surround(use_auto_surround);
16066
16067            if let Some(new_selected_range) = new_selected_range_utf16 {
16068                let snapshot = this.buffer.read(cx).read(cx);
16069                let new_selected_ranges = marked_ranges
16070                    .into_iter()
16071                    .map(|marked_range| {
16072                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16073                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16074                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16075                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16076                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16077                    })
16078                    .collect::<Vec<_>>();
16079
16080                drop(snapshot);
16081                this.change_selections(None, window, cx, |selections| {
16082                    selections.select_ranges(new_selected_ranges)
16083                });
16084            }
16085        });
16086
16087        self.ime_transaction = self.ime_transaction.or(transaction);
16088        if let Some(transaction) = self.ime_transaction {
16089            self.buffer.update(cx, |buffer, cx| {
16090                buffer.group_until_transaction(transaction, cx);
16091            });
16092        }
16093
16094        if self.text_highlights::<InputComposition>(cx).is_none() {
16095            self.ime_transaction.take();
16096        }
16097    }
16098
16099    fn bounds_for_range(
16100        &mut self,
16101        range_utf16: Range<usize>,
16102        element_bounds: gpui::Bounds<Pixels>,
16103        window: &mut Window,
16104        cx: &mut Context<Self>,
16105    ) -> Option<gpui::Bounds<Pixels>> {
16106        let text_layout_details = self.text_layout_details(window);
16107        let gpui::Size {
16108            width: em_width,
16109            height: line_height,
16110        } = self.character_size(window);
16111
16112        let snapshot = self.snapshot(window, cx);
16113        let scroll_position = snapshot.scroll_position();
16114        let scroll_left = scroll_position.x * em_width;
16115
16116        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16117        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16118            + self.gutter_dimensions.width
16119            + self.gutter_dimensions.margin;
16120        let y = line_height * (start.row().as_f32() - scroll_position.y);
16121
16122        Some(Bounds {
16123            origin: element_bounds.origin + point(x, y),
16124            size: size(em_width, line_height),
16125        })
16126    }
16127
16128    fn character_index_for_point(
16129        &mut self,
16130        point: gpui::Point<Pixels>,
16131        _window: &mut Window,
16132        _cx: &mut Context<Self>,
16133    ) -> Option<usize> {
16134        let position_map = self.last_position_map.as_ref()?;
16135        if !position_map.text_hitbox.contains(&point) {
16136            return None;
16137        }
16138        let display_point = position_map.point_for_position(point).previous_valid;
16139        let anchor = position_map
16140            .snapshot
16141            .display_point_to_anchor(display_point, Bias::Left);
16142        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16143        Some(utf16_offset.0)
16144    }
16145}
16146
16147trait SelectionExt {
16148    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16149    fn spanned_rows(
16150        &self,
16151        include_end_if_at_line_start: bool,
16152        map: &DisplaySnapshot,
16153    ) -> Range<MultiBufferRow>;
16154}
16155
16156impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16157    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16158        let start = self
16159            .start
16160            .to_point(&map.buffer_snapshot)
16161            .to_display_point(map);
16162        let end = self
16163            .end
16164            .to_point(&map.buffer_snapshot)
16165            .to_display_point(map);
16166        if self.reversed {
16167            end..start
16168        } else {
16169            start..end
16170        }
16171    }
16172
16173    fn spanned_rows(
16174        &self,
16175        include_end_if_at_line_start: bool,
16176        map: &DisplaySnapshot,
16177    ) -> Range<MultiBufferRow> {
16178        let start = self.start.to_point(&map.buffer_snapshot);
16179        let mut end = self.end.to_point(&map.buffer_snapshot);
16180        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16181            end.row -= 1;
16182        }
16183
16184        let buffer_start = map.prev_line_boundary(start).0;
16185        let buffer_end = map.next_line_boundary(end).0;
16186        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16187    }
16188}
16189
16190impl<T: InvalidationRegion> InvalidationStack<T> {
16191    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16192    where
16193        S: Clone + ToOffset,
16194    {
16195        while let Some(region) = self.last() {
16196            let all_selections_inside_invalidation_ranges =
16197                if selections.len() == region.ranges().len() {
16198                    selections
16199                        .iter()
16200                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16201                        .all(|(selection, invalidation_range)| {
16202                            let head = selection.head().to_offset(buffer);
16203                            invalidation_range.start <= head && invalidation_range.end >= head
16204                        })
16205                } else {
16206                    false
16207                };
16208
16209            if all_selections_inside_invalidation_ranges {
16210                break;
16211            } else {
16212                self.pop();
16213            }
16214        }
16215    }
16216}
16217
16218impl<T> Default for InvalidationStack<T> {
16219    fn default() -> Self {
16220        Self(Default::default())
16221    }
16222}
16223
16224impl<T> Deref for InvalidationStack<T> {
16225    type Target = Vec<T>;
16226
16227    fn deref(&self) -> &Self::Target {
16228        &self.0
16229    }
16230}
16231
16232impl<T> DerefMut for InvalidationStack<T> {
16233    fn deref_mut(&mut self) -> &mut Self::Target {
16234        &mut self.0
16235    }
16236}
16237
16238impl InvalidationRegion for SnippetState {
16239    fn ranges(&self) -> &[Range<Anchor>] {
16240        &self.ranges[self.active_index]
16241    }
16242}
16243
16244pub fn diagnostic_block_renderer(
16245    diagnostic: Diagnostic,
16246    max_message_rows: Option<u8>,
16247    allow_closing: bool,
16248    _is_valid: bool,
16249) -> RenderBlock {
16250    let (text_without_backticks, code_ranges) =
16251        highlight_diagnostic_message(&diagnostic, max_message_rows);
16252
16253    Arc::new(move |cx: &mut BlockContext| {
16254        let group_id: SharedString = cx.block_id.to_string().into();
16255
16256        let mut text_style = cx.window.text_style().clone();
16257        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16258        let theme_settings = ThemeSettings::get_global(cx);
16259        text_style.font_family = theme_settings.buffer_font.family.clone();
16260        text_style.font_style = theme_settings.buffer_font.style;
16261        text_style.font_features = theme_settings.buffer_font.features.clone();
16262        text_style.font_weight = theme_settings.buffer_font.weight;
16263
16264        let multi_line_diagnostic = diagnostic.message.contains('\n');
16265
16266        let buttons = |diagnostic: &Diagnostic| {
16267            if multi_line_diagnostic {
16268                v_flex()
16269            } else {
16270                h_flex()
16271            }
16272            .when(allow_closing, |div| {
16273                div.children(diagnostic.is_primary.then(|| {
16274                    IconButton::new("close-block", IconName::XCircle)
16275                        .icon_color(Color::Muted)
16276                        .size(ButtonSize::Compact)
16277                        .style(ButtonStyle::Transparent)
16278                        .visible_on_hover(group_id.clone())
16279                        .on_click(move |_click, window, cx| {
16280                            window.dispatch_action(Box::new(Cancel), cx)
16281                        })
16282                        .tooltip(|window, cx| {
16283                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16284                        })
16285                }))
16286            })
16287            .child(
16288                IconButton::new("copy-block", IconName::Copy)
16289                    .icon_color(Color::Muted)
16290                    .size(ButtonSize::Compact)
16291                    .style(ButtonStyle::Transparent)
16292                    .visible_on_hover(group_id.clone())
16293                    .on_click({
16294                        let message = diagnostic.message.clone();
16295                        move |_click, _, cx| {
16296                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16297                        }
16298                    })
16299                    .tooltip(Tooltip::text("Copy diagnostic message")),
16300            )
16301        };
16302
16303        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16304            AvailableSpace::min_size(),
16305            cx.window,
16306            cx.app,
16307        );
16308
16309        h_flex()
16310            .id(cx.block_id)
16311            .group(group_id.clone())
16312            .relative()
16313            .size_full()
16314            .block_mouse_down()
16315            .pl(cx.gutter_dimensions.width)
16316            .w(cx.max_width - cx.gutter_dimensions.full_width())
16317            .child(
16318                div()
16319                    .flex()
16320                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16321                    .flex_shrink(),
16322            )
16323            .child(buttons(&diagnostic))
16324            .child(div().flex().flex_shrink_0().child(
16325                StyledText::new(text_without_backticks.clone()).with_highlights(
16326                    &text_style,
16327                    code_ranges.iter().map(|range| {
16328                        (
16329                            range.clone(),
16330                            HighlightStyle {
16331                                font_weight: Some(FontWeight::BOLD),
16332                                ..Default::default()
16333                            },
16334                        )
16335                    }),
16336                ),
16337            ))
16338            .into_any_element()
16339    })
16340}
16341
16342fn inline_completion_edit_text(
16343    current_snapshot: &BufferSnapshot,
16344    edits: &[(Range<Anchor>, String)],
16345    edit_preview: &EditPreview,
16346    include_deletions: bool,
16347    cx: &App,
16348) -> HighlightedText {
16349    let edits = edits
16350        .iter()
16351        .map(|(anchor, text)| {
16352            (
16353                anchor.start.text_anchor..anchor.end.text_anchor,
16354                text.clone(),
16355            )
16356        })
16357        .collect::<Vec<_>>();
16358
16359    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16360}
16361
16362pub fn highlight_diagnostic_message(
16363    diagnostic: &Diagnostic,
16364    mut max_message_rows: Option<u8>,
16365) -> (SharedString, Vec<Range<usize>>) {
16366    let mut text_without_backticks = String::new();
16367    let mut code_ranges = Vec::new();
16368
16369    if let Some(source) = &diagnostic.source {
16370        text_without_backticks.push_str(source);
16371        code_ranges.push(0..source.len());
16372        text_without_backticks.push_str(": ");
16373    }
16374
16375    let mut prev_offset = 0;
16376    let mut in_code_block = false;
16377    let has_row_limit = max_message_rows.is_some();
16378    let mut newline_indices = diagnostic
16379        .message
16380        .match_indices('\n')
16381        .filter(|_| has_row_limit)
16382        .map(|(ix, _)| ix)
16383        .fuse()
16384        .peekable();
16385
16386    for (quote_ix, _) in diagnostic
16387        .message
16388        .match_indices('`')
16389        .chain([(diagnostic.message.len(), "")])
16390    {
16391        let mut first_newline_ix = None;
16392        let mut last_newline_ix = None;
16393        while let Some(newline_ix) = newline_indices.peek() {
16394            if *newline_ix < quote_ix {
16395                if first_newline_ix.is_none() {
16396                    first_newline_ix = Some(*newline_ix);
16397                }
16398                last_newline_ix = Some(*newline_ix);
16399
16400                if let Some(rows_left) = &mut max_message_rows {
16401                    if *rows_left == 0 {
16402                        break;
16403                    } else {
16404                        *rows_left -= 1;
16405                    }
16406                }
16407                let _ = newline_indices.next();
16408            } else {
16409                break;
16410            }
16411        }
16412        let prev_len = text_without_backticks.len();
16413        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16414        text_without_backticks.push_str(new_text);
16415        if in_code_block {
16416            code_ranges.push(prev_len..text_without_backticks.len());
16417        }
16418        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16419        in_code_block = !in_code_block;
16420        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16421            text_without_backticks.push_str("...");
16422            break;
16423        }
16424    }
16425
16426    (text_without_backticks.into(), code_ranges)
16427}
16428
16429fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16430    match severity {
16431        DiagnosticSeverity::ERROR => colors.error,
16432        DiagnosticSeverity::WARNING => colors.warning,
16433        DiagnosticSeverity::INFORMATION => colors.info,
16434        DiagnosticSeverity::HINT => colors.info,
16435        _ => colors.ignored,
16436    }
16437}
16438
16439pub fn styled_runs_for_code_label<'a>(
16440    label: &'a CodeLabel,
16441    syntax_theme: &'a theme::SyntaxTheme,
16442) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16443    let fade_out = HighlightStyle {
16444        fade_out: Some(0.35),
16445        ..Default::default()
16446    };
16447
16448    let mut prev_end = label.filter_range.end;
16449    label
16450        .runs
16451        .iter()
16452        .enumerate()
16453        .flat_map(move |(ix, (range, highlight_id))| {
16454            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16455                style
16456            } else {
16457                return Default::default();
16458            };
16459            let mut muted_style = style;
16460            muted_style.highlight(fade_out);
16461
16462            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16463            if range.start >= label.filter_range.end {
16464                if range.start > prev_end {
16465                    runs.push((prev_end..range.start, fade_out));
16466                }
16467                runs.push((range.clone(), muted_style));
16468            } else if range.end <= label.filter_range.end {
16469                runs.push((range.clone(), style));
16470            } else {
16471                runs.push((range.start..label.filter_range.end, style));
16472                runs.push((label.filter_range.end..range.end, muted_style));
16473            }
16474            prev_end = cmp::max(prev_end, range.end);
16475
16476            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16477                runs.push((prev_end..label.text.len(), fade_out));
16478            }
16479
16480            runs
16481        })
16482}
16483
16484pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16485    let mut prev_index = 0;
16486    let mut prev_codepoint: Option<char> = None;
16487    text.char_indices()
16488        .chain([(text.len(), '\0')])
16489        .filter_map(move |(index, codepoint)| {
16490            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16491            let is_boundary = index == text.len()
16492                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16493                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16494            if is_boundary {
16495                let chunk = &text[prev_index..index];
16496                prev_index = index;
16497                Some(chunk)
16498            } else {
16499                None
16500            }
16501        })
16502}
16503
16504pub trait RangeToAnchorExt: Sized {
16505    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16506
16507    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16508        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16509        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16510    }
16511}
16512
16513impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16514    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16515        let start_offset = self.start.to_offset(snapshot);
16516        let end_offset = self.end.to_offset(snapshot);
16517        if start_offset == end_offset {
16518            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16519        } else {
16520            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16521        }
16522    }
16523}
16524
16525pub trait RowExt {
16526    fn as_f32(&self) -> f32;
16527
16528    fn next_row(&self) -> Self;
16529
16530    fn previous_row(&self) -> Self;
16531
16532    fn minus(&self, other: Self) -> u32;
16533}
16534
16535impl RowExt for DisplayRow {
16536    fn as_f32(&self) -> f32 {
16537        self.0 as f32
16538    }
16539
16540    fn next_row(&self) -> Self {
16541        Self(self.0 + 1)
16542    }
16543
16544    fn previous_row(&self) -> Self {
16545        Self(self.0.saturating_sub(1))
16546    }
16547
16548    fn minus(&self, other: Self) -> u32 {
16549        self.0 - other.0
16550    }
16551}
16552
16553impl RowExt for MultiBufferRow {
16554    fn as_f32(&self) -> f32 {
16555        self.0 as f32
16556    }
16557
16558    fn next_row(&self) -> Self {
16559        Self(self.0 + 1)
16560    }
16561
16562    fn previous_row(&self) -> Self {
16563        Self(self.0.saturating_sub(1))
16564    }
16565
16566    fn minus(&self, other: Self) -> u32 {
16567        self.0 - other.0
16568    }
16569}
16570
16571trait RowRangeExt {
16572    type Row;
16573
16574    fn len(&self) -> usize;
16575
16576    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16577}
16578
16579impl RowRangeExt for Range<MultiBufferRow> {
16580    type Row = MultiBufferRow;
16581
16582    fn len(&self) -> usize {
16583        (self.end.0 - self.start.0) as usize
16584    }
16585
16586    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16587        (self.start.0..self.end.0).map(MultiBufferRow)
16588    }
16589}
16590
16591impl RowRangeExt for Range<DisplayRow> {
16592    type Row = DisplayRow;
16593
16594    fn len(&self) -> usize {
16595        (self.end.0 - self.start.0) as usize
16596    }
16597
16598    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16599        (self.start.0..self.end.0).map(DisplayRow)
16600    }
16601}
16602
16603/// If select range has more than one line, we
16604/// just point the cursor to range.start.
16605fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16606    if range.start.row == range.end.row {
16607        range
16608    } else {
16609        range.start..range.start
16610    }
16611}
16612pub struct KillRing(ClipboardItem);
16613impl Global for KillRing {}
16614
16615const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16616
16617fn all_edits_insertions_or_deletions(
16618    edits: &Vec<(Range<Anchor>, String)>,
16619    snapshot: &MultiBufferSnapshot,
16620) -> bool {
16621    let mut all_insertions = true;
16622    let mut all_deletions = true;
16623
16624    for (range, new_text) in edits.iter() {
16625        let range_is_empty = range.to_offset(&snapshot).is_empty();
16626        let text_is_empty = new_text.is_empty();
16627
16628        if range_is_empty != text_is_empty {
16629            if range_is_empty {
16630                all_deletions = false;
16631            } else {
16632                all_insertions = false;
16633            }
16634        } else {
16635            return false;
16636        }
16637
16638        if !all_insertions && !all_deletions {
16639            return false;
16640        }
16641    }
16642    all_insertions || all_deletions
16643}