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::{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_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
  194    "edit_prediction_requires_modifier";
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakEntity<Workspace>>,
  201    cx: &mut App,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(
  246        link_ranges,
  247        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace
  253                            .open_abs_path(path.clone(), false, window, cx)
  254                            .detach();
  255                    });
  256                }
  257            }
  258        },
  259    )
  260}
  261
  262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  263pub enum InlayId {
  264    InlineCompletion(usize),
  265    Hint(usize),
  266}
  267
  268impl InlayId {
  269    fn id(&self) -> usize {
  270        match self {
  271            Self::InlineCompletion(id) => *id,
  272            Self::Hint(id) => *id,
  273        }
  274    }
  275}
  276
  277enum DocumentHighlightRead {}
  278enum DocumentHighlightWrite {}
  279enum InputComposition {}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut App) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut App) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new(
  309        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313            workspace.register_action(Editor::cancel_language_server_work);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(
  322                Default::default(),
  323                app_state,
  324                cx,
  325                |workspace, window, cx| {
  326                    Editor::new_file(workspace, &Default::default(), window, cx)
  327                },
  328            )
  329            .detach();
  330        }
  331    });
  332    cx.on_action(move |_: &workspace::NewWindow, cx| {
  333        let app_state = workspace::AppState::global(cx);
  334        if let Some(app_state) = app_state.upgrade() {
  335            workspace::open_new(
  336                Default::default(),
  337                app_state,
  338                cx,
  339                |workspace, window, cx| {
  340                    cx.activate(true);
  341                    Editor::new_file(workspace, &Default::default(), window, cx)
  342                },
  343            )
  344            .detach();
  345        }
  346    });
  347}
  348
  349pub struct SearchWithinRange;
  350
  351trait InvalidationRegion {
  352    fn ranges(&self) -> &[Range<Anchor>];
  353}
  354
  355#[derive(Clone, Debug, PartialEq)]
  356pub enum SelectPhase {
  357    Begin {
  358        position: DisplayPoint,
  359        add: bool,
  360        click_count: usize,
  361    },
  362    BeginColumnar {
  363        position: DisplayPoint,
  364        reset: bool,
  365        goal_column: u32,
  366    },
  367    Extend {
  368        position: DisplayPoint,
  369        click_count: usize,
  370    },
  371    Update {
  372        position: DisplayPoint,
  373        goal_column: u32,
  374        scroll_delta: gpui::Point<f32>,
  375    },
  376    End,
  377}
  378
  379#[derive(Clone, Debug)]
  380pub enum SelectMode {
  381    Character,
  382    Word(Range<Anchor>),
  383    Line(Range<Anchor>),
  384    All,
  385}
  386
  387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  388pub enum EditorMode {
  389    SingleLine { auto_width: bool },
  390    AutoHeight { max_lines: usize },
  391    Full,
  392}
  393
  394#[derive(Copy, Clone, Debug)]
  395pub enum SoftWrap {
  396    /// Prefer not to wrap at all.
  397    ///
  398    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  399    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  400    GitDiff,
  401    /// Prefer a single line generally, unless an overly long line is encountered.
  402    None,
  403    /// Soft wrap lines that exceed the editor width.
  404    EditorWidth,
  405    /// Soft wrap lines at the preferred line length.
  406    Column(u32),
  407    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  408    Bounded(u32),
  409}
  410
  411#[derive(Clone)]
  412pub struct EditorStyle {
  413    pub background: Hsla,
  414    pub local_player: PlayerColor,
  415    pub text: TextStyle,
  416    pub scrollbar_width: Pixels,
  417    pub syntax: Arc<SyntaxTheme>,
  418    pub status: StatusColors,
  419    pub inlay_hints_style: HighlightStyle,
  420    pub inline_completion_styles: InlineCompletionStyles,
  421    pub unnecessary_code_fade: f32,
  422}
  423
  424impl Default for EditorStyle {
  425    fn default() -> Self {
  426        Self {
  427            background: Hsla::default(),
  428            local_player: PlayerColor::default(),
  429            text: TextStyle::default(),
  430            scrollbar_width: Pixels::default(),
  431            syntax: Default::default(),
  432            // HACK: Status colors don't have a real default.
  433            // We should look into removing the status colors from the editor
  434            // style and retrieve them directly from the theme.
  435            status: StatusColors::dark(),
  436            inlay_hints_style: HighlightStyle::default(),
  437            inline_completion_styles: InlineCompletionStyles {
  438                insertion: HighlightStyle::default(),
  439                whitespace: HighlightStyle::default(),
  440            },
  441            unnecessary_code_fade: Default::default(),
  442        }
  443    }
  444}
  445
  446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  447    let show_background = language_settings::language_settings(None, None, cx)
  448        .inlay_hints
  449        .show_background;
  450
  451    HighlightStyle {
  452        color: Some(cx.theme().status().hint),
  453        background_color: show_background.then(|| cx.theme().status().hint_background),
  454        ..HighlightStyle::default()
  455    }
  456}
  457
  458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  459    InlineCompletionStyles {
  460        insertion: HighlightStyle {
  461            color: Some(cx.theme().status().predictive),
  462            ..HighlightStyle::default()
  463        },
  464        whitespace: HighlightStyle {
  465            background_color: Some(cx.theme().status().created_background),
  466            ..HighlightStyle::default()
  467        },
  468    }
  469}
  470
  471type CompletionId = usize;
  472
  473pub(crate) enum EditDisplayMode {
  474    TabAccept,
  475    DiffPopover,
  476    Inline,
  477}
  478
  479enum InlineCompletion {
  480    Edit {
  481        edits: Vec<(Range<Anchor>, String)>,
  482        edit_preview: Option<EditPreview>,
  483        display_mode: EditDisplayMode,
  484        snapshot: BufferSnapshot,
  485    },
  486    Move {
  487        target: Anchor,
  488        range_around_target: Range<text::Anchor>,
  489        snapshot: BufferSnapshot,
  490    },
  491}
  492
  493struct InlineCompletionState {
  494    inlay_ids: Vec<InlayId>,
  495    completion: InlineCompletion,
  496    completion_id: Option<SharedString>,
  497    invalidation_range: Range<Anchor>,
  498}
  499
  500enum InlineCompletionHighlight {}
  501
  502pub enum MenuInlineCompletionsPolicy {
  503    Never,
  504    ByProvider,
  505}
  506
  507#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  508struct EditorActionId(usize);
  509
  510impl EditorActionId {
  511    pub fn post_inc(&mut self) -> Self {
  512        let answer = self.0;
  513
  514        *self = Self(answer + 1);
  515
  516        Self(answer)
  517    }
  518}
  519
  520// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  521// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  522
  523type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  524type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  525
  526#[derive(Default)]
  527struct ScrollbarMarkerState {
  528    scrollbar_size: Size<Pixels>,
  529    dirty: bool,
  530    markers: Arc<[PaintQuad]>,
  531    pending_refresh: Option<Task<Result<()>>>,
  532}
  533
  534impl ScrollbarMarkerState {
  535    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  536        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  537    }
  538}
  539
  540#[derive(Clone, Debug)]
  541struct RunnableTasks {
  542    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  543    offset: MultiBufferOffset,
  544    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  545    column: u32,
  546    // Values of all named captures, including those starting with '_'
  547    extra_variables: HashMap<String, String>,
  548    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  549    context_range: Range<BufferOffset>,
  550}
  551
  552impl RunnableTasks {
  553    fn resolve<'a>(
  554        &'a self,
  555        cx: &'a task::TaskContext,
  556    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  557        self.templates.iter().filter_map(|(kind, template)| {
  558            template
  559                .resolve_task(&kind.to_id_base(), cx)
  560                .map(|task| (kind.clone(), task))
  561        })
  562    }
  563}
  564
  565#[derive(Clone)]
  566struct ResolvedTasks {
  567    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  568    position: Anchor,
  569}
  570#[derive(Copy, Clone, Debug)]
  571struct MultiBufferOffset(usize);
  572#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  573struct BufferOffset(usize);
  574
  575// Addons allow storing per-editor state in other crates (e.g. Vim)
  576pub trait Addon: 'static {
  577    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  578
  579    fn render_buffer_header_controls(
  580        &self,
  581        _: &ExcerptInfo,
  582        _: &Window,
  583        _: &App,
  584    ) -> Option<AnyElement> {
  585        None
  586    }
  587
  588    fn to_any(&self) -> &dyn std::any::Any;
  589}
  590
  591#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  592pub enum IsVimMode {
  593    Yes,
  594    No,
  595}
  596
  597/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  598///
  599/// See the [module level documentation](self) for more information.
  600pub struct Editor {
  601    focus_handle: FocusHandle,
  602    last_focused_descendant: Option<WeakFocusHandle>,
  603    /// The text buffer being edited
  604    buffer: Entity<MultiBuffer>,
  605    /// Map of how text in the buffer should be displayed.
  606    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  607    pub display_map: Entity<DisplayMap>,
  608    pub selections: SelectionsCollection,
  609    pub scroll_manager: ScrollManager,
  610    /// When inline assist editors are linked, they all render cursors because
  611    /// typing enters text into each of them, even the ones that aren't focused.
  612    pub(crate) show_cursor_when_unfocused: bool,
  613    columnar_selection_tail: Option<Anchor>,
  614    add_selections_state: Option<AddSelectionsState>,
  615    select_next_state: Option<SelectNextState>,
  616    select_prev_state: Option<SelectNextState>,
  617    selection_history: SelectionHistory,
  618    autoclose_regions: Vec<AutocloseRegion>,
  619    snippet_stack: InvalidationStack<SnippetState>,
  620    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  621    ime_transaction: Option<TransactionId>,
  622    active_diagnostics: Option<ActiveDiagnosticGroup>,
  623    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  624
  625    // TODO: make this a access method
  626    pub project: Option<Entity<Project>>,
  627    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  628    completion_provider: Option<Box<dyn CompletionProvider>>,
  629    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  630    blink_manager: Entity<BlinkManager>,
  631    show_cursor_names: bool,
  632    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  633    pub show_local_selections: bool,
  634    mode: EditorMode,
  635    show_breadcrumbs: bool,
  636    show_gutter: bool,
  637    show_scrollbars: bool,
  638    show_line_numbers: Option<bool>,
  639    use_relative_line_numbers: Option<bool>,
  640    show_git_diff_gutter: Option<bool>,
  641    show_code_actions: Option<bool>,
  642    show_runnables: Option<bool>,
  643    show_wrap_guides: Option<bool>,
  644    show_indent_guides: Option<bool>,
  645    placeholder_text: Option<Arc<str>>,
  646    highlight_order: usize,
  647    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  648    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  649    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  650    scrollbar_marker_state: ScrollbarMarkerState,
  651    active_indent_guides_state: ActiveIndentGuidesState,
  652    nav_history: Option<ItemNavHistory>,
  653    context_menu: RefCell<Option<CodeContextMenu>>,
  654    mouse_context_menu: Option<MouseContextMenu>,
  655    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  656    signature_help_state: SignatureHelpState,
  657    auto_signature_help: Option<bool>,
  658    find_all_references_task_sources: Vec<Anchor>,
  659    next_completion_id: CompletionId,
  660    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  661    code_actions_task: Option<Task<Result<()>>>,
  662    document_highlights_task: Option<Task<()>>,
  663    linked_editing_range_task: Option<Task<Option<()>>>,
  664    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  665    pending_rename: Option<RenameState>,
  666    searchable: bool,
  667    cursor_shape: CursorShape,
  668    current_line_highlight: Option<CurrentLineHighlight>,
  669    collapse_matches: bool,
  670    autoindent_mode: Option<AutoindentMode>,
  671    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  672    input_enabled: bool,
  673    use_modal_editing: bool,
  674    read_only: bool,
  675    leader_peer_id: Option<PeerId>,
  676    remote_id: Option<ViewId>,
  677    hover_state: HoverState,
  678    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  679    gutter_hovered: bool,
  680    hovered_link_state: Option<HoveredLinkState>,
  681    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  682    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  683    active_inline_completion: Option<InlineCompletionState>,
  684    /// Used to prevent flickering as the user types while the menu is open
  685    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  686    inline_completions_hidden_for_vim_mode: bool,
  687    show_inline_completions_override: Option<bool>,
  688    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  689    previewing_inline_completion: bool,
  690    inlay_hint_cache: InlayHintCache,
  691    next_inlay_id: usize,
  692    _subscriptions: Vec<Subscription>,
  693    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  694    gutter_dimensions: GutterDimensions,
  695    style: Option<EditorStyle>,
  696    text_style_refinement: Option<TextStyleRefinement>,
  697    next_editor_action_id: EditorActionId,
  698    editor_actions:
  699        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  700    use_autoclose: bool,
  701    use_auto_surround: bool,
  702    auto_replace_emoji_shortcode: bool,
  703    show_git_blame_gutter: bool,
  704    show_git_blame_inline: bool,
  705    show_git_blame_inline_delay_task: Option<Task<()>>,
  706    git_blame_inline_enabled: bool,
  707    serialize_dirty_buffers: bool,
  708    show_selection_menu: Option<bool>,
  709    blame: Option<Entity<GitBlame>>,
  710    blame_subscription: Option<Subscription>,
  711    custom_context_menu: Option<
  712        Box<
  713            dyn 'static
  714                + Fn(
  715                    &mut Self,
  716                    DisplayPoint,
  717                    &mut Window,
  718                    &mut Context<Self>,
  719                ) -> Option<Entity<ui::ContextMenu>>,
  720        >,
  721    >,
  722    last_bounds: Option<Bounds<Pixels>>,
  723    last_position_map: Option<Rc<PositionMap>>,
  724    expect_bounds_change: Option<Bounds<Pixels>>,
  725    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  726    tasks_update_task: Option<Task<()>>,
  727    in_project_search: bool,
  728    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  729    breadcrumb_header: Option<String>,
  730    focused_block: Option<FocusedBlock>,
  731    next_scroll_position: NextScrollCursorCenterTopBottom,
  732    addons: HashMap<TypeId, Box<dyn Addon>>,
  733    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  734    selection_mark_mode: bool,
  735    toggle_fold_multiple_buffers: Task<()>,
  736    _scroll_cursor_center_top_bottom_task: Task<()>,
  737}
  738
  739#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  740enum NextScrollCursorCenterTopBottom {
  741    #[default]
  742    Center,
  743    Top,
  744    Bottom,
  745}
  746
  747impl NextScrollCursorCenterTopBottom {
  748    fn next(&self) -> Self {
  749        match self {
  750            Self::Center => Self::Top,
  751            Self::Top => Self::Bottom,
  752            Self::Bottom => Self::Center,
  753        }
  754    }
  755}
  756
  757#[derive(Clone)]
  758pub struct EditorSnapshot {
  759    pub mode: EditorMode,
  760    show_gutter: bool,
  761    show_line_numbers: Option<bool>,
  762    show_git_diff_gutter: Option<bool>,
  763    show_code_actions: Option<bool>,
  764    show_runnables: Option<bool>,
  765    git_blame_gutter_max_author_length: Option<usize>,
  766    pub display_snapshot: DisplaySnapshot,
  767    pub placeholder_text: Option<Arc<str>>,
  768    is_focused: bool,
  769    scroll_anchor: ScrollAnchor,
  770    ongoing_scroll: OngoingScroll,
  771    current_line_highlight: CurrentLineHighlight,
  772    gutter_hovered: bool,
  773}
  774
  775const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  776
  777#[derive(Default, Debug, Clone, Copy)]
  778pub struct GutterDimensions {
  779    pub left_padding: Pixels,
  780    pub right_padding: Pixels,
  781    pub width: Pixels,
  782    pub margin: Pixels,
  783    pub git_blame_entries_width: Option<Pixels>,
  784}
  785
  786impl GutterDimensions {
  787    /// The full width of the space taken up by the gutter.
  788    pub fn full_width(&self) -> Pixels {
  789        self.margin + self.width
  790    }
  791
  792    /// The width of the space reserved for the fold indicators,
  793    /// use alongside 'justify_end' and `gutter_width` to
  794    /// right align content with the line numbers
  795    pub fn fold_area_width(&self) -> Pixels {
  796        self.margin + self.right_padding
  797    }
  798}
  799
  800#[derive(Debug)]
  801pub struct RemoteSelection {
  802    pub replica_id: ReplicaId,
  803    pub selection: Selection<Anchor>,
  804    pub cursor_shape: CursorShape,
  805    pub peer_id: PeerId,
  806    pub line_mode: bool,
  807    pub participant_index: Option<ParticipantIndex>,
  808    pub user_name: Option<SharedString>,
  809}
  810
  811#[derive(Clone, Debug)]
  812struct SelectionHistoryEntry {
  813    selections: Arc<[Selection<Anchor>]>,
  814    select_next_state: Option<SelectNextState>,
  815    select_prev_state: Option<SelectNextState>,
  816    add_selections_state: Option<AddSelectionsState>,
  817}
  818
  819enum SelectionHistoryMode {
  820    Normal,
  821    Undoing,
  822    Redoing,
  823}
  824
  825#[derive(Clone, PartialEq, Eq, Hash)]
  826struct HoveredCursor {
  827    replica_id: u16,
  828    selection_id: usize,
  829}
  830
  831impl Default for SelectionHistoryMode {
  832    fn default() -> Self {
  833        Self::Normal
  834    }
  835}
  836
  837#[derive(Default)]
  838struct SelectionHistory {
  839    #[allow(clippy::type_complexity)]
  840    selections_by_transaction:
  841        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  842    mode: SelectionHistoryMode,
  843    undo_stack: VecDeque<SelectionHistoryEntry>,
  844    redo_stack: VecDeque<SelectionHistoryEntry>,
  845}
  846
  847impl SelectionHistory {
  848    fn insert_transaction(
  849        &mut self,
  850        transaction_id: TransactionId,
  851        selections: Arc<[Selection<Anchor>]>,
  852    ) {
  853        self.selections_by_transaction
  854            .insert(transaction_id, (selections, None));
  855    }
  856
  857    #[allow(clippy::type_complexity)]
  858    fn transaction(
  859        &self,
  860        transaction_id: TransactionId,
  861    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  862        self.selections_by_transaction.get(&transaction_id)
  863    }
  864
  865    #[allow(clippy::type_complexity)]
  866    fn transaction_mut(
  867        &mut self,
  868        transaction_id: TransactionId,
  869    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  870        self.selections_by_transaction.get_mut(&transaction_id)
  871    }
  872
  873    fn push(&mut self, entry: SelectionHistoryEntry) {
  874        if !entry.selections.is_empty() {
  875            match self.mode {
  876                SelectionHistoryMode::Normal => {
  877                    self.push_undo(entry);
  878                    self.redo_stack.clear();
  879                }
  880                SelectionHistoryMode::Undoing => self.push_redo(entry),
  881                SelectionHistoryMode::Redoing => self.push_undo(entry),
  882            }
  883        }
  884    }
  885
  886    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  887        if self
  888            .undo_stack
  889            .back()
  890            .map_or(true, |e| e.selections != entry.selections)
  891        {
  892            self.undo_stack.push_back(entry);
  893            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  894                self.undo_stack.pop_front();
  895            }
  896        }
  897    }
  898
  899    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  900        if self
  901            .redo_stack
  902            .back()
  903            .map_or(true, |e| e.selections != entry.selections)
  904        {
  905            self.redo_stack.push_back(entry);
  906            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  907                self.redo_stack.pop_front();
  908            }
  909        }
  910    }
  911}
  912
  913struct RowHighlight {
  914    index: usize,
  915    range: Range<Anchor>,
  916    color: Hsla,
  917    should_autoscroll: bool,
  918}
  919
  920#[derive(Clone, Debug)]
  921struct AddSelectionsState {
  922    above: bool,
  923    stack: Vec<usize>,
  924}
  925
  926#[derive(Clone)]
  927struct SelectNextState {
  928    query: AhoCorasick,
  929    wordwise: bool,
  930    done: bool,
  931}
  932
  933impl std::fmt::Debug for SelectNextState {
  934    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  935        f.debug_struct(std::any::type_name::<Self>())
  936            .field("wordwise", &self.wordwise)
  937            .field("done", &self.done)
  938            .finish()
  939    }
  940}
  941
  942#[derive(Debug)]
  943struct AutocloseRegion {
  944    selection_id: usize,
  945    range: Range<Anchor>,
  946    pair: BracketPair,
  947}
  948
  949#[derive(Debug)]
  950struct SnippetState {
  951    ranges: Vec<Vec<Range<Anchor>>>,
  952    active_index: usize,
  953    choices: Vec<Option<Vec<String>>>,
  954}
  955
  956#[doc(hidden)]
  957pub struct RenameState {
  958    pub range: Range<Anchor>,
  959    pub old_name: Arc<str>,
  960    pub editor: Entity<Editor>,
  961    block_id: CustomBlockId,
  962}
  963
  964struct InvalidationStack<T>(Vec<T>);
  965
  966struct RegisteredInlineCompletionProvider {
  967    provider: Arc<dyn InlineCompletionProviderHandle>,
  968    _subscription: Subscription,
  969}
  970
  971#[derive(Debug)]
  972struct ActiveDiagnosticGroup {
  973    primary_range: Range<Anchor>,
  974    primary_message: String,
  975    group_id: usize,
  976    blocks: HashMap<CustomBlockId, Diagnostic>,
  977    is_valid: bool,
  978}
  979
  980#[derive(Serialize, Deserialize, Clone, Debug)]
  981pub struct ClipboardSelection {
  982    pub len: usize,
  983    pub is_entire_line: bool,
  984    pub first_line_indent: u32,
  985}
  986
  987#[derive(Debug)]
  988pub(crate) struct NavigationData {
  989    cursor_anchor: Anchor,
  990    cursor_position: Point,
  991    scroll_anchor: ScrollAnchor,
  992    scroll_top_row: u32,
  993}
  994
  995#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  996pub enum GotoDefinitionKind {
  997    Symbol,
  998    Declaration,
  999    Type,
 1000    Implementation,
 1001}
 1002
 1003#[derive(Debug, Clone)]
 1004enum InlayHintRefreshReason {
 1005    Toggle(bool),
 1006    SettingsChange(InlayHintSettings),
 1007    NewLinesShown,
 1008    BufferEdited(HashSet<Arc<Language>>),
 1009    RefreshRequested,
 1010    ExcerptsRemoved(Vec<ExcerptId>),
 1011}
 1012
 1013impl InlayHintRefreshReason {
 1014    fn description(&self) -> &'static str {
 1015        match self {
 1016            Self::Toggle(_) => "toggle",
 1017            Self::SettingsChange(_) => "settings change",
 1018            Self::NewLinesShown => "new lines shown",
 1019            Self::BufferEdited(_) => "buffer edited",
 1020            Self::RefreshRequested => "refresh requested",
 1021            Self::ExcerptsRemoved(_) => "excerpts removed",
 1022        }
 1023    }
 1024}
 1025
 1026pub enum FormatTarget {
 1027    Buffers,
 1028    Ranges(Vec<Range<MultiBufferPoint>>),
 1029}
 1030
 1031pub(crate) struct FocusedBlock {
 1032    id: BlockId,
 1033    focus_handle: WeakFocusHandle,
 1034}
 1035
 1036#[derive(Clone)]
 1037enum JumpData {
 1038    MultiBufferRow {
 1039        row: MultiBufferRow,
 1040        line_offset_from_top: u32,
 1041    },
 1042    MultiBufferPoint {
 1043        excerpt_id: ExcerptId,
 1044        position: Point,
 1045        anchor: text::Anchor,
 1046        line_offset_from_top: u32,
 1047    },
 1048}
 1049
 1050pub enum MultibufferSelectionMode {
 1051    First,
 1052    All,
 1053}
 1054
 1055impl Editor {
 1056    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1057        let buffer = cx.new(|cx| Buffer::local("", cx));
 1058        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1059        Self::new(
 1060            EditorMode::SingleLine { auto_width: false },
 1061            buffer,
 1062            None,
 1063            false,
 1064            window,
 1065            cx,
 1066        )
 1067    }
 1068
 1069    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1070        let buffer = cx.new(|cx| Buffer::local("", cx));
 1071        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1072        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1073    }
 1074
 1075    pub fn auto_width(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: true },
 1080            buffer,
 1081            None,
 1082            false,
 1083            window,
 1084            cx,
 1085        )
 1086    }
 1087
 1088    pub fn auto_height(max_lines: usize, 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(
 1092            EditorMode::AutoHeight { max_lines },
 1093            buffer,
 1094            None,
 1095            false,
 1096            window,
 1097            cx,
 1098        )
 1099    }
 1100
 1101    pub fn for_buffer(
 1102        buffer: Entity<Buffer>,
 1103        project: Option<Entity<Project>>,
 1104        window: &mut Window,
 1105        cx: &mut Context<Self>,
 1106    ) -> Self {
 1107        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1108        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1109    }
 1110
 1111    pub fn for_multibuffer(
 1112        buffer: Entity<MultiBuffer>,
 1113        project: Option<Entity<Project>>,
 1114        show_excerpt_controls: bool,
 1115        window: &mut Window,
 1116        cx: &mut Context<Self>,
 1117    ) -> Self {
 1118        Self::new(
 1119            EditorMode::Full,
 1120            buffer,
 1121            project,
 1122            show_excerpt_controls,
 1123            window,
 1124            cx,
 1125        )
 1126    }
 1127
 1128    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1129        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1130        let mut clone = Self::new(
 1131            self.mode,
 1132            self.buffer.clone(),
 1133            self.project.clone(),
 1134            show_excerpt_controls,
 1135            window,
 1136            cx,
 1137        );
 1138        self.display_map.update(cx, |display_map, cx| {
 1139            let snapshot = display_map.snapshot(cx);
 1140            clone.display_map.update(cx, |display_map, cx| {
 1141                display_map.set_state(&snapshot, cx);
 1142            });
 1143        });
 1144        clone.selections.clone_state(&self.selections);
 1145        clone.scroll_manager.clone_state(&self.scroll_manager);
 1146        clone.searchable = self.searchable;
 1147        clone
 1148    }
 1149
 1150    pub fn new(
 1151        mode: EditorMode,
 1152        buffer: Entity<MultiBuffer>,
 1153        project: Option<Entity<Project>>,
 1154        show_excerpt_controls: bool,
 1155        window: &mut Window,
 1156        cx: &mut Context<Self>,
 1157    ) -> Self {
 1158        let style = window.text_style();
 1159        let font_size = style.font_size.to_pixels(window.rem_size());
 1160        let editor = cx.entity().downgrade();
 1161        let fold_placeholder = FoldPlaceholder {
 1162            constrain_width: true,
 1163            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1164                let editor = editor.clone();
 1165                div()
 1166                    .id(fold_id)
 1167                    .bg(cx.theme().colors().ghost_element_background)
 1168                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1169                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1170                    .rounded_sm()
 1171                    .size_full()
 1172                    .cursor_pointer()
 1173                    .child("")
 1174                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1175                    .on_click(move |_, _window, cx| {
 1176                        editor
 1177                            .update(cx, |editor, cx| {
 1178                                editor.unfold_ranges(
 1179                                    &[fold_range.start..fold_range.end],
 1180                                    true,
 1181                                    false,
 1182                                    cx,
 1183                                );
 1184                                cx.stop_propagation();
 1185                            })
 1186                            .ok();
 1187                    })
 1188                    .into_any()
 1189            }),
 1190            merge_adjacent: true,
 1191            ..Default::default()
 1192        };
 1193        let display_map = cx.new(|cx| {
 1194            DisplayMap::new(
 1195                buffer.clone(),
 1196                style.font(),
 1197                font_size,
 1198                None,
 1199                show_excerpt_controls,
 1200                FILE_HEADER_HEIGHT,
 1201                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1202                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1203                fold_placeholder,
 1204                cx,
 1205            )
 1206        });
 1207
 1208        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1209
 1210        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1211
 1212        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1213            .then(|| language_settings::SoftWrap::None);
 1214
 1215        let mut project_subscriptions = Vec::new();
 1216        if mode == EditorMode::Full {
 1217            if let Some(project) = project.as_ref() {
 1218                if buffer.read(cx).is_singleton() {
 1219                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1220                        cx.emit(EditorEvent::TitleChanged);
 1221                    }));
 1222                }
 1223                project_subscriptions.push(cx.subscribe_in(
 1224                    project,
 1225                    window,
 1226                    |editor, _, event, window, cx| {
 1227                        if let project::Event::RefreshInlayHints = event {
 1228                            editor
 1229                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1230                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1231                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1232                                let focus_handle = editor.focus_handle(cx);
 1233                                if focus_handle.is_focused(window) {
 1234                                    let snapshot = buffer.read(cx).snapshot();
 1235                                    for (range, snippet) in snippet_edits {
 1236                                        let editor_range =
 1237                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1238                                        editor
 1239                                            .insert_snippet(
 1240                                                &[editor_range],
 1241                                                snippet.clone(),
 1242                                                window,
 1243                                                cx,
 1244                                            )
 1245                                            .ok();
 1246                                    }
 1247                                }
 1248                            }
 1249                        }
 1250                    },
 1251                ));
 1252                if let Some(task_inventory) = project
 1253                    .read(cx)
 1254                    .task_store()
 1255                    .read(cx)
 1256                    .task_inventory()
 1257                    .cloned()
 1258                {
 1259                    project_subscriptions.push(cx.observe_in(
 1260                        &task_inventory,
 1261                        window,
 1262                        |editor, _, window, cx| {
 1263                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1264                        },
 1265                    ));
 1266                }
 1267            }
 1268        }
 1269
 1270        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1271
 1272        let inlay_hint_settings =
 1273            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1274        let focus_handle = cx.focus_handle();
 1275        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1276            .detach();
 1277        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1278            .detach();
 1279        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1280            .detach();
 1281        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1282            .detach();
 1283
 1284        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1285            Some(false)
 1286        } else {
 1287            None
 1288        };
 1289
 1290        let mut code_action_providers = Vec::new();
 1291        if let Some(project) = project.clone() {
 1292            get_uncommitted_diff_for_buffer(
 1293                &project,
 1294                buffer.read(cx).all_buffers(),
 1295                buffer.clone(),
 1296                cx,
 1297            );
 1298            code_action_providers.push(Rc::new(project) as Rc<_>);
 1299        }
 1300
 1301        let mut this = Self {
 1302            focus_handle,
 1303            show_cursor_when_unfocused: false,
 1304            last_focused_descendant: None,
 1305            buffer: buffer.clone(),
 1306            display_map: display_map.clone(),
 1307            selections,
 1308            scroll_manager: ScrollManager::new(cx),
 1309            columnar_selection_tail: None,
 1310            add_selections_state: None,
 1311            select_next_state: None,
 1312            select_prev_state: None,
 1313            selection_history: Default::default(),
 1314            autoclose_regions: Default::default(),
 1315            snippet_stack: Default::default(),
 1316            select_larger_syntax_node_stack: Vec::new(),
 1317            ime_transaction: Default::default(),
 1318            active_diagnostics: None,
 1319            soft_wrap_mode_override,
 1320            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1321            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1322            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1323            project,
 1324            blink_manager: blink_manager.clone(),
 1325            show_local_selections: true,
 1326            show_scrollbars: true,
 1327            mode,
 1328            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1329            show_gutter: mode == EditorMode::Full,
 1330            show_line_numbers: None,
 1331            use_relative_line_numbers: None,
 1332            show_git_diff_gutter: None,
 1333            show_code_actions: None,
 1334            show_runnables: None,
 1335            show_wrap_guides: None,
 1336            show_indent_guides,
 1337            placeholder_text: None,
 1338            highlight_order: 0,
 1339            highlighted_rows: HashMap::default(),
 1340            background_highlights: Default::default(),
 1341            gutter_highlights: TreeMap::default(),
 1342            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1343            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1344            nav_history: None,
 1345            context_menu: RefCell::new(None),
 1346            mouse_context_menu: None,
 1347            completion_tasks: Default::default(),
 1348            signature_help_state: SignatureHelpState::default(),
 1349            auto_signature_help: None,
 1350            find_all_references_task_sources: Vec::new(),
 1351            next_completion_id: 0,
 1352            next_inlay_id: 0,
 1353            code_action_providers,
 1354            available_code_actions: Default::default(),
 1355            code_actions_task: Default::default(),
 1356            document_highlights_task: Default::default(),
 1357            linked_editing_range_task: Default::default(),
 1358            pending_rename: Default::default(),
 1359            searchable: true,
 1360            cursor_shape: EditorSettings::get_global(cx)
 1361                .cursor_shape
 1362                .unwrap_or_default(),
 1363            current_line_highlight: None,
 1364            autoindent_mode: Some(AutoindentMode::EachLine),
 1365            collapse_matches: false,
 1366            workspace: None,
 1367            input_enabled: true,
 1368            use_modal_editing: mode == EditorMode::Full,
 1369            read_only: false,
 1370            use_autoclose: true,
 1371            use_auto_surround: true,
 1372            auto_replace_emoji_shortcode: false,
 1373            leader_peer_id: None,
 1374            remote_id: None,
 1375            hover_state: Default::default(),
 1376            pending_mouse_down: None,
 1377            hovered_link_state: Default::default(),
 1378            edit_prediction_provider: None,
 1379            active_inline_completion: None,
 1380            stale_inline_completion_in_menu: None,
 1381            previewing_inline_completion: false,
 1382            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1383
 1384            gutter_hovered: false,
 1385            pixel_position_of_newest_cursor: None,
 1386            last_bounds: None,
 1387            last_position_map: None,
 1388            expect_bounds_change: None,
 1389            gutter_dimensions: GutterDimensions::default(),
 1390            style: None,
 1391            show_cursor_names: false,
 1392            hovered_cursors: Default::default(),
 1393            next_editor_action_id: EditorActionId::default(),
 1394            editor_actions: Rc::default(),
 1395            inline_completions_hidden_for_vim_mode: false,
 1396            show_inline_completions_override: None,
 1397            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1398            custom_context_menu: None,
 1399            show_git_blame_gutter: false,
 1400            show_git_blame_inline: false,
 1401            show_selection_menu: None,
 1402            show_git_blame_inline_delay_task: None,
 1403            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1404            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1405                .session
 1406                .restore_unsaved_buffers,
 1407            blame: None,
 1408            blame_subscription: None,
 1409            tasks: Default::default(),
 1410            _subscriptions: vec![
 1411                cx.observe(&buffer, Self::on_buffer_changed),
 1412                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1413                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1414                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1415                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1416                cx.observe_window_activation(window, |editor, window, cx| {
 1417                    let active = window.is_window_active();
 1418                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1419                        if active {
 1420                            blink_manager.enable(cx);
 1421                        } else {
 1422                            blink_manager.disable(cx);
 1423                        }
 1424                    });
 1425                }),
 1426            ],
 1427            tasks_update_task: None,
 1428            linked_edit_ranges: Default::default(),
 1429            in_project_search: false,
 1430            previous_search_ranges: None,
 1431            breadcrumb_header: None,
 1432            focused_block: None,
 1433            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1434            addons: HashMap::default(),
 1435            registered_buffers: HashMap::default(),
 1436            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1437            selection_mark_mode: false,
 1438            toggle_fold_multiple_buffers: Task::ready(()),
 1439            text_style_refinement: None,
 1440        };
 1441        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1442        this._subscriptions.extend(project_subscriptions);
 1443
 1444        this.end_selection(window, cx);
 1445        this.scroll_manager.show_scrollbar(window, cx);
 1446
 1447        if mode == EditorMode::Full {
 1448            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1449            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1450
 1451            if this.git_blame_inline_enabled {
 1452                this.git_blame_inline_enabled = true;
 1453                this.start_git_blame_inline(false, window, cx);
 1454            }
 1455
 1456            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1457                if let Some(project) = this.project.as_ref() {
 1458                    let lsp_store = project.read(cx).lsp_store();
 1459                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1460                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1461                    });
 1462                    this.registered_buffers
 1463                        .insert(buffer.read(cx).remote_id(), handle);
 1464                }
 1465            }
 1466        }
 1467
 1468        this.report_editor_event("Editor Opened", None, cx);
 1469        this
 1470    }
 1471
 1472    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1473        self.mouse_context_menu
 1474            .as_ref()
 1475            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1476    }
 1477
 1478    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1479        let mut key_context = KeyContext::new_with_defaults();
 1480        key_context.add("Editor");
 1481        let mode = match self.mode {
 1482            EditorMode::SingleLine { .. } => "single_line",
 1483            EditorMode::AutoHeight { .. } => "auto_height",
 1484            EditorMode::Full => "full",
 1485        };
 1486
 1487        if EditorSettings::jupyter_enabled(cx) {
 1488            key_context.add("jupyter");
 1489        }
 1490
 1491        key_context.set("mode", mode);
 1492        if self.pending_rename.is_some() {
 1493            key_context.add("renaming");
 1494        }
 1495
 1496        let mut showing_completions = false;
 1497
 1498        match self.context_menu.borrow().as_ref() {
 1499            Some(CodeContextMenu::Completions(_)) => {
 1500                key_context.add("menu");
 1501                key_context.add("showing_completions");
 1502                showing_completions = true;
 1503            }
 1504            Some(CodeContextMenu::CodeActions(_)) => {
 1505                key_context.add("menu");
 1506                key_context.add("showing_code_actions")
 1507            }
 1508            None => {}
 1509        }
 1510
 1511        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1512        if !self.focus_handle(cx).contains_focused(window, cx)
 1513            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1514        {
 1515            for addon in self.addons.values() {
 1516                addon.extend_key_context(&mut key_context, cx)
 1517            }
 1518        }
 1519
 1520        if let Some(extension) = self
 1521            .buffer
 1522            .read(cx)
 1523            .as_singleton()
 1524            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1525        {
 1526            key_context.set("extension", extension.to_string());
 1527        }
 1528
 1529        if self.has_active_inline_completion() {
 1530            key_context.add("copilot_suggestion");
 1531            key_context.add("edit_prediction");
 1532
 1533            if showing_completions || self.edit_prediction_requires_modifier(cx) {
 1534                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1535            }
 1536        }
 1537
 1538        if self.selection_mark_mode {
 1539            key_context.add("selection_mode");
 1540        }
 1541
 1542        key_context
 1543    }
 1544
 1545    pub fn new_file(
 1546        workspace: &mut Workspace,
 1547        _: &workspace::NewFile,
 1548        window: &mut Window,
 1549        cx: &mut Context<Workspace>,
 1550    ) {
 1551        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1552            "Failed to create buffer",
 1553            window,
 1554            cx,
 1555            |e, _, _| match e.error_code() {
 1556                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1557                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1558                e.error_tag("required").unwrap_or("the latest version")
 1559            )),
 1560                _ => None,
 1561            },
 1562        );
 1563    }
 1564
 1565    pub fn new_in_workspace(
 1566        workspace: &mut Workspace,
 1567        window: &mut Window,
 1568        cx: &mut Context<Workspace>,
 1569    ) -> Task<Result<Entity<Editor>>> {
 1570        let project = workspace.project().clone();
 1571        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1572
 1573        cx.spawn_in(window, |workspace, mut cx| async move {
 1574            let buffer = create.await?;
 1575            workspace.update_in(&mut cx, |workspace, window, cx| {
 1576                let editor =
 1577                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1578                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1579                editor
 1580            })
 1581        })
 1582    }
 1583
 1584    fn new_file_vertical(
 1585        workspace: &mut Workspace,
 1586        _: &workspace::NewFileSplitVertical,
 1587        window: &mut Window,
 1588        cx: &mut Context<Workspace>,
 1589    ) {
 1590        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1591    }
 1592
 1593    fn new_file_horizontal(
 1594        workspace: &mut Workspace,
 1595        _: &workspace::NewFileSplitHorizontal,
 1596        window: &mut Window,
 1597        cx: &mut Context<Workspace>,
 1598    ) {
 1599        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1600    }
 1601
 1602    fn new_file_in_direction(
 1603        workspace: &mut Workspace,
 1604        direction: SplitDirection,
 1605        window: &mut Window,
 1606        cx: &mut Context<Workspace>,
 1607    ) {
 1608        let project = workspace.project().clone();
 1609        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1610
 1611        cx.spawn_in(window, |workspace, mut cx| async move {
 1612            let buffer = create.await?;
 1613            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1614                workspace.split_item(
 1615                    direction,
 1616                    Box::new(
 1617                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1618                    ),
 1619                    window,
 1620                    cx,
 1621                )
 1622            })?;
 1623            anyhow::Ok(())
 1624        })
 1625        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1626            match e.error_code() {
 1627                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1628                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1629                e.error_tag("required").unwrap_or("the latest version")
 1630            )),
 1631                _ => None,
 1632            }
 1633        });
 1634    }
 1635
 1636    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1637        self.leader_peer_id
 1638    }
 1639
 1640    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1641        &self.buffer
 1642    }
 1643
 1644    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1645        self.workspace.as_ref()?.0.upgrade()
 1646    }
 1647
 1648    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1649        self.buffer().read(cx).title(cx)
 1650    }
 1651
 1652    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1653        let git_blame_gutter_max_author_length = self
 1654            .render_git_blame_gutter(cx)
 1655            .then(|| {
 1656                if let Some(blame) = self.blame.as_ref() {
 1657                    let max_author_length =
 1658                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1659                    Some(max_author_length)
 1660                } else {
 1661                    None
 1662                }
 1663            })
 1664            .flatten();
 1665
 1666        EditorSnapshot {
 1667            mode: self.mode,
 1668            show_gutter: self.show_gutter,
 1669            show_line_numbers: self.show_line_numbers,
 1670            show_git_diff_gutter: self.show_git_diff_gutter,
 1671            show_code_actions: self.show_code_actions,
 1672            show_runnables: self.show_runnables,
 1673            git_blame_gutter_max_author_length,
 1674            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1675            scroll_anchor: self.scroll_manager.anchor(),
 1676            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1677            placeholder_text: self.placeholder_text.clone(),
 1678            is_focused: self.focus_handle.is_focused(window),
 1679            current_line_highlight: self
 1680                .current_line_highlight
 1681                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1682            gutter_hovered: self.gutter_hovered,
 1683        }
 1684    }
 1685
 1686    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1687        self.buffer.read(cx).language_at(point, cx)
 1688    }
 1689
 1690    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1691        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1692    }
 1693
 1694    pub fn active_excerpt(
 1695        &self,
 1696        cx: &App,
 1697    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1698        self.buffer
 1699            .read(cx)
 1700            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1701    }
 1702
 1703    pub fn mode(&self) -> EditorMode {
 1704        self.mode
 1705    }
 1706
 1707    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1708        self.collaboration_hub.as_deref()
 1709    }
 1710
 1711    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1712        self.collaboration_hub = Some(hub);
 1713    }
 1714
 1715    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1716        self.in_project_search = in_project_search;
 1717    }
 1718
 1719    pub fn set_custom_context_menu(
 1720        &mut self,
 1721        f: impl 'static
 1722            + Fn(
 1723                &mut Self,
 1724                DisplayPoint,
 1725                &mut Window,
 1726                &mut Context<Self>,
 1727            ) -> Option<Entity<ui::ContextMenu>>,
 1728    ) {
 1729        self.custom_context_menu = Some(Box::new(f))
 1730    }
 1731
 1732    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1733        self.completion_provider = provider;
 1734    }
 1735
 1736    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1737        self.semantics_provider.clone()
 1738    }
 1739
 1740    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1741        self.semantics_provider = provider;
 1742    }
 1743
 1744    pub fn set_edit_prediction_provider<T>(
 1745        &mut self,
 1746        provider: Option<Entity<T>>,
 1747        window: &mut Window,
 1748        cx: &mut Context<Self>,
 1749    ) where
 1750        T: EditPredictionProvider,
 1751    {
 1752        self.edit_prediction_provider =
 1753            provider.map(|provider| RegisteredInlineCompletionProvider {
 1754                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1755                    if this.focus_handle.is_focused(window) {
 1756                        this.update_visible_inline_completion(window, cx);
 1757                    }
 1758                }),
 1759                provider: Arc::new(provider),
 1760            });
 1761        self.refresh_inline_completion(false, false, window, cx);
 1762    }
 1763
 1764    pub fn placeholder_text(&self) -> Option<&str> {
 1765        self.placeholder_text.as_deref()
 1766    }
 1767
 1768    pub fn set_placeholder_text(
 1769        &mut self,
 1770        placeholder_text: impl Into<Arc<str>>,
 1771        cx: &mut Context<Self>,
 1772    ) {
 1773        let placeholder_text = Some(placeholder_text.into());
 1774        if self.placeholder_text != placeholder_text {
 1775            self.placeholder_text = placeholder_text;
 1776            cx.notify();
 1777        }
 1778    }
 1779
 1780    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1781        self.cursor_shape = cursor_shape;
 1782
 1783        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1784        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1785
 1786        cx.notify();
 1787    }
 1788
 1789    pub fn set_current_line_highlight(
 1790        &mut self,
 1791        current_line_highlight: Option<CurrentLineHighlight>,
 1792    ) {
 1793        self.current_line_highlight = current_line_highlight;
 1794    }
 1795
 1796    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1797        self.collapse_matches = collapse_matches;
 1798    }
 1799
 1800    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1801        let buffers = self.buffer.read(cx).all_buffers();
 1802        let Some(lsp_store) = self.lsp_store(cx) else {
 1803            return;
 1804        };
 1805        lsp_store.update(cx, |lsp_store, cx| {
 1806            for buffer in buffers {
 1807                self.registered_buffers
 1808                    .entry(buffer.read(cx).remote_id())
 1809                    .or_insert_with(|| {
 1810                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1811                    });
 1812            }
 1813        })
 1814    }
 1815
 1816    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1817        if self.collapse_matches {
 1818            return range.start..range.start;
 1819        }
 1820        range.clone()
 1821    }
 1822
 1823    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1824        if self.display_map.read(cx).clip_at_line_ends != clip {
 1825            self.display_map
 1826                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1827        }
 1828    }
 1829
 1830    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1831        self.input_enabled = input_enabled;
 1832    }
 1833
 1834    pub fn set_inline_completions_hidden_for_vim_mode(
 1835        &mut self,
 1836        hidden: bool,
 1837        window: &mut Window,
 1838        cx: &mut Context<Self>,
 1839    ) {
 1840        if hidden != self.inline_completions_hidden_for_vim_mode {
 1841            self.inline_completions_hidden_for_vim_mode = hidden;
 1842            if hidden {
 1843                self.update_visible_inline_completion(window, cx);
 1844            } else {
 1845                self.refresh_inline_completion(true, false, window, cx);
 1846            }
 1847        }
 1848    }
 1849
 1850    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1851        self.menu_inline_completions_policy = value;
 1852    }
 1853
 1854    pub fn set_autoindent(&mut self, autoindent: bool) {
 1855        if autoindent {
 1856            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1857        } else {
 1858            self.autoindent_mode = None;
 1859        }
 1860    }
 1861
 1862    pub fn read_only(&self, cx: &App) -> bool {
 1863        self.read_only || self.buffer.read(cx).read_only()
 1864    }
 1865
 1866    pub fn set_read_only(&mut self, read_only: bool) {
 1867        self.read_only = read_only;
 1868    }
 1869
 1870    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1871        self.use_autoclose = autoclose;
 1872    }
 1873
 1874    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1875        self.use_auto_surround = auto_surround;
 1876    }
 1877
 1878    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1879        self.auto_replace_emoji_shortcode = auto_replace;
 1880    }
 1881
 1882    pub fn toggle_inline_completions(
 1883        &mut self,
 1884        _: &ToggleEditPrediction,
 1885        window: &mut Window,
 1886        cx: &mut Context<Self>,
 1887    ) {
 1888        if self.show_inline_completions_override.is_some() {
 1889            self.set_show_inline_completions(None, window, cx);
 1890        } else {
 1891            let cursor = self.selections.newest_anchor().head();
 1892            if let Some((buffer, cursor_buffer_position)) =
 1893                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1894            {
 1895                let show_inline_completions = !self.should_show_inline_completions_in_buffer(
 1896                    &buffer,
 1897                    cursor_buffer_position,
 1898                    cx,
 1899                );
 1900                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1901            }
 1902        }
 1903    }
 1904
 1905    pub fn set_show_inline_completions(
 1906        &mut self,
 1907        show_edit_predictions: Option<bool>,
 1908        window: &mut Window,
 1909        cx: &mut Context<Self>,
 1910    ) {
 1911        self.show_inline_completions_override = show_edit_predictions;
 1912        self.refresh_inline_completion(false, true, window, cx);
 1913    }
 1914
 1915    pub fn inline_completion_start_anchor(&self) -> Option<Anchor> {
 1916        let active_completion = self.active_inline_completion.as_ref()?;
 1917        let result = match &active_completion.completion {
 1918            InlineCompletion::Edit { edits, .. } => edits.first()?.0.start,
 1919            InlineCompletion::Move { target, .. } => *target,
 1920        };
 1921        Some(result)
 1922    }
 1923
 1924    fn inline_completions_disabled_in_scope(
 1925        &self,
 1926        buffer: &Entity<Buffer>,
 1927        buffer_position: language::Anchor,
 1928        cx: &App,
 1929    ) -> bool {
 1930        let snapshot = buffer.read(cx).snapshot();
 1931        let settings = snapshot.settings_at(buffer_position, cx);
 1932
 1933        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1934            return false;
 1935        };
 1936
 1937        scope.override_name().map_or(false, |scope_name| {
 1938            settings
 1939                .edit_predictions_disabled_in
 1940                .iter()
 1941                .any(|s| s == scope_name)
 1942        })
 1943    }
 1944
 1945    pub fn set_use_modal_editing(&mut self, to: bool) {
 1946        self.use_modal_editing = to;
 1947    }
 1948
 1949    pub fn use_modal_editing(&self) -> bool {
 1950        self.use_modal_editing
 1951    }
 1952
 1953    fn selections_did_change(
 1954        &mut self,
 1955        local: bool,
 1956        old_cursor_position: &Anchor,
 1957        show_completions: bool,
 1958        window: &mut Window,
 1959        cx: &mut Context<Self>,
 1960    ) {
 1961        window.invalidate_character_coordinates();
 1962
 1963        // Copy selections to primary selection buffer
 1964        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1965        if local {
 1966            let selections = self.selections.all::<usize>(cx);
 1967            let buffer_handle = self.buffer.read(cx).read(cx);
 1968
 1969            let mut text = String::new();
 1970            for (index, selection) in selections.iter().enumerate() {
 1971                let text_for_selection = buffer_handle
 1972                    .text_for_range(selection.start..selection.end)
 1973                    .collect::<String>();
 1974
 1975                text.push_str(&text_for_selection);
 1976                if index != selections.len() - 1 {
 1977                    text.push('\n');
 1978                }
 1979            }
 1980
 1981            if !text.is_empty() {
 1982                cx.write_to_primary(ClipboardItem::new_string(text));
 1983            }
 1984        }
 1985
 1986        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1987            self.buffer.update(cx, |buffer, cx| {
 1988                buffer.set_active_selections(
 1989                    &self.selections.disjoint_anchors(),
 1990                    self.selections.line_mode,
 1991                    self.cursor_shape,
 1992                    cx,
 1993                )
 1994            });
 1995        }
 1996        let display_map = self
 1997            .display_map
 1998            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1999        let buffer = &display_map.buffer_snapshot;
 2000        self.add_selections_state = None;
 2001        self.select_next_state = None;
 2002        self.select_prev_state = None;
 2003        self.select_larger_syntax_node_stack.clear();
 2004        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2005        self.snippet_stack
 2006            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2007        self.take_rename(false, window, cx);
 2008
 2009        let new_cursor_position = self.selections.newest_anchor().head();
 2010
 2011        self.push_to_nav_history(
 2012            *old_cursor_position,
 2013            Some(new_cursor_position.to_point(buffer)),
 2014            cx,
 2015        );
 2016
 2017        if local {
 2018            let new_cursor_position = self.selections.newest_anchor().head();
 2019            let mut context_menu = self.context_menu.borrow_mut();
 2020            let completion_menu = match context_menu.as_ref() {
 2021                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2022                _ => {
 2023                    *context_menu = None;
 2024                    None
 2025                }
 2026            };
 2027            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2028                if !self.registered_buffers.contains_key(&buffer_id) {
 2029                    if let Some(lsp_store) = self.lsp_store(cx) {
 2030                        lsp_store.update(cx, |lsp_store, cx| {
 2031                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2032                                return;
 2033                            };
 2034                            self.registered_buffers.insert(
 2035                                buffer_id,
 2036                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2037                            );
 2038                        })
 2039                    }
 2040                }
 2041            }
 2042
 2043            if let Some(completion_menu) = completion_menu {
 2044                let cursor_position = new_cursor_position.to_offset(buffer);
 2045                let (word_range, kind) =
 2046                    buffer.surrounding_word(completion_menu.initial_position, true);
 2047                if kind == Some(CharKind::Word)
 2048                    && word_range.to_inclusive().contains(&cursor_position)
 2049                {
 2050                    let mut completion_menu = completion_menu.clone();
 2051                    drop(context_menu);
 2052
 2053                    let query = Self::completion_query(buffer, cursor_position);
 2054                    cx.spawn(move |this, mut cx| async move {
 2055                        completion_menu
 2056                            .filter(query.as_deref(), cx.background_executor().clone())
 2057                            .await;
 2058
 2059                        this.update(&mut cx, |this, cx| {
 2060                            let mut context_menu = this.context_menu.borrow_mut();
 2061                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2062                            else {
 2063                                return;
 2064                            };
 2065
 2066                            if menu.id > completion_menu.id {
 2067                                return;
 2068                            }
 2069
 2070                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2071                            drop(context_menu);
 2072                            cx.notify();
 2073                        })
 2074                    })
 2075                    .detach();
 2076
 2077                    if show_completions {
 2078                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2079                    }
 2080                } else {
 2081                    drop(context_menu);
 2082                    self.hide_context_menu(window, cx);
 2083                }
 2084            } else {
 2085                drop(context_menu);
 2086            }
 2087
 2088            hide_hover(self, cx);
 2089
 2090            if old_cursor_position.to_display_point(&display_map).row()
 2091                != new_cursor_position.to_display_point(&display_map).row()
 2092            {
 2093                self.available_code_actions.take();
 2094            }
 2095            self.refresh_code_actions(window, cx);
 2096            self.refresh_document_highlights(cx);
 2097            refresh_matching_bracket_highlights(self, window, cx);
 2098            self.update_visible_inline_completion(window, cx);
 2099            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2100            if self.git_blame_inline_enabled {
 2101                self.start_inline_blame_timer(window, cx);
 2102            }
 2103        }
 2104
 2105        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2106        cx.emit(EditorEvent::SelectionsChanged { local });
 2107
 2108        if self.selections.disjoint_anchors().len() == 1 {
 2109            cx.emit(SearchEvent::ActiveMatchChanged)
 2110        }
 2111        cx.notify();
 2112    }
 2113
 2114    pub fn change_selections<R>(
 2115        &mut self,
 2116        autoscroll: Option<Autoscroll>,
 2117        window: &mut Window,
 2118        cx: &mut Context<Self>,
 2119        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2120    ) -> R {
 2121        self.change_selections_inner(autoscroll, true, window, cx, change)
 2122    }
 2123
 2124    pub fn change_selections_inner<R>(
 2125        &mut self,
 2126        autoscroll: Option<Autoscroll>,
 2127        request_completions: bool,
 2128        window: &mut Window,
 2129        cx: &mut Context<Self>,
 2130        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2131    ) -> R {
 2132        let old_cursor_position = self.selections.newest_anchor().head();
 2133        self.push_to_selection_history();
 2134
 2135        let (changed, result) = self.selections.change_with(cx, change);
 2136
 2137        if changed {
 2138            if let Some(autoscroll) = autoscroll {
 2139                self.request_autoscroll(autoscroll, cx);
 2140            }
 2141            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2142
 2143            if self.should_open_signature_help_automatically(
 2144                &old_cursor_position,
 2145                self.signature_help_state.backspace_pressed(),
 2146                cx,
 2147            ) {
 2148                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2149            }
 2150            self.signature_help_state.set_backspace_pressed(false);
 2151        }
 2152
 2153        result
 2154    }
 2155
 2156    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2157    where
 2158        I: IntoIterator<Item = (Range<S>, T)>,
 2159        S: ToOffset,
 2160        T: Into<Arc<str>>,
 2161    {
 2162        if self.read_only(cx) {
 2163            return;
 2164        }
 2165
 2166        self.buffer
 2167            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2168    }
 2169
 2170    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2171    where
 2172        I: IntoIterator<Item = (Range<S>, T)>,
 2173        S: ToOffset,
 2174        T: Into<Arc<str>>,
 2175    {
 2176        if self.read_only(cx) {
 2177            return;
 2178        }
 2179
 2180        self.buffer.update(cx, |buffer, cx| {
 2181            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2182        });
 2183    }
 2184
 2185    pub fn edit_with_block_indent<I, S, T>(
 2186        &mut self,
 2187        edits: I,
 2188        original_indent_columns: Vec<u32>,
 2189        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(
 2201                edits,
 2202                Some(AutoindentMode::Block {
 2203                    original_indent_columns,
 2204                }),
 2205                cx,
 2206            )
 2207        });
 2208    }
 2209
 2210    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2211        self.hide_context_menu(window, cx);
 2212
 2213        match phase {
 2214            SelectPhase::Begin {
 2215                position,
 2216                add,
 2217                click_count,
 2218            } => self.begin_selection(position, add, click_count, window, cx),
 2219            SelectPhase::BeginColumnar {
 2220                position,
 2221                goal_column,
 2222                reset,
 2223            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2224            SelectPhase::Extend {
 2225                position,
 2226                click_count,
 2227            } => self.extend_selection(position, click_count, window, cx),
 2228            SelectPhase::Update {
 2229                position,
 2230                goal_column,
 2231                scroll_delta,
 2232            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2233            SelectPhase::End => self.end_selection(window, cx),
 2234        }
 2235    }
 2236
 2237    fn extend_selection(
 2238        &mut self,
 2239        position: DisplayPoint,
 2240        click_count: usize,
 2241        window: &mut Window,
 2242        cx: &mut Context<Self>,
 2243    ) {
 2244        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2245        let tail = self.selections.newest::<usize>(cx).tail();
 2246        self.begin_selection(position, false, click_count, window, cx);
 2247
 2248        let position = position.to_offset(&display_map, Bias::Left);
 2249        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2250
 2251        let mut pending_selection = self
 2252            .selections
 2253            .pending_anchor()
 2254            .expect("extend_selection not called with pending selection");
 2255        if position >= tail {
 2256            pending_selection.start = tail_anchor;
 2257        } else {
 2258            pending_selection.end = tail_anchor;
 2259            pending_selection.reversed = true;
 2260        }
 2261
 2262        let mut pending_mode = self.selections.pending_mode().unwrap();
 2263        match &mut pending_mode {
 2264            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2265            _ => {}
 2266        }
 2267
 2268        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2269            s.set_pending(pending_selection, pending_mode)
 2270        });
 2271    }
 2272
 2273    fn begin_selection(
 2274        &mut self,
 2275        position: DisplayPoint,
 2276        add: bool,
 2277        click_count: usize,
 2278        window: &mut Window,
 2279        cx: &mut Context<Self>,
 2280    ) {
 2281        if !self.focus_handle.is_focused(window) {
 2282            self.last_focused_descendant = None;
 2283            window.focus(&self.focus_handle);
 2284        }
 2285
 2286        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2287        let buffer = &display_map.buffer_snapshot;
 2288        let newest_selection = self.selections.newest_anchor().clone();
 2289        let position = display_map.clip_point(position, Bias::Left);
 2290
 2291        let start;
 2292        let end;
 2293        let mode;
 2294        let mut auto_scroll;
 2295        match click_count {
 2296            1 => {
 2297                start = buffer.anchor_before(position.to_point(&display_map));
 2298                end = start;
 2299                mode = SelectMode::Character;
 2300                auto_scroll = true;
 2301            }
 2302            2 => {
 2303                let range = movement::surrounding_word(&display_map, position);
 2304                start = buffer.anchor_before(range.start.to_point(&display_map));
 2305                end = buffer.anchor_before(range.end.to_point(&display_map));
 2306                mode = SelectMode::Word(start..end);
 2307                auto_scroll = true;
 2308            }
 2309            3 => {
 2310                let position = display_map
 2311                    .clip_point(position, Bias::Left)
 2312                    .to_point(&display_map);
 2313                let line_start = display_map.prev_line_boundary(position).0;
 2314                let next_line_start = buffer.clip_point(
 2315                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2316                    Bias::Left,
 2317                );
 2318                start = buffer.anchor_before(line_start);
 2319                end = buffer.anchor_before(next_line_start);
 2320                mode = SelectMode::Line(start..end);
 2321                auto_scroll = true;
 2322            }
 2323            _ => {
 2324                start = buffer.anchor_before(0);
 2325                end = buffer.anchor_before(buffer.len());
 2326                mode = SelectMode::All;
 2327                auto_scroll = false;
 2328            }
 2329        }
 2330        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2331
 2332        let point_to_delete: Option<usize> = {
 2333            let selected_points: Vec<Selection<Point>> =
 2334                self.selections.disjoint_in_range(start..end, cx);
 2335
 2336            if !add || click_count > 1 {
 2337                None
 2338            } else if !selected_points.is_empty() {
 2339                Some(selected_points[0].id)
 2340            } else {
 2341                let clicked_point_already_selected =
 2342                    self.selections.disjoint.iter().find(|selection| {
 2343                        selection.start.to_point(buffer) == start.to_point(buffer)
 2344                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2345                    });
 2346
 2347                clicked_point_already_selected.map(|selection| selection.id)
 2348            }
 2349        };
 2350
 2351        let selections_count = self.selections.count();
 2352
 2353        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2354            if let Some(point_to_delete) = point_to_delete {
 2355                s.delete(point_to_delete);
 2356
 2357                if selections_count == 1 {
 2358                    s.set_pending_anchor_range(start..end, mode);
 2359                }
 2360            } else {
 2361                if !add {
 2362                    s.clear_disjoint();
 2363                } else if click_count > 1 {
 2364                    s.delete(newest_selection.id)
 2365                }
 2366
 2367                s.set_pending_anchor_range(start..end, mode);
 2368            }
 2369        });
 2370    }
 2371
 2372    fn begin_columnar_selection(
 2373        &mut self,
 2374        position: DisplayPoint,
 2375        goal_column: u32,
 2376        reset: bool,
 2377        window: &mut Window,
 2378        cx: &mut Context<Self>,
 2379    ) {
 2380        if !self.focus_handle.is_focused(window) {
 2381            self.last_focused_descendant = None;
 2382            window.focus(&self.focus_handle);
 2383        }
 2384
 2385        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2386
 2387        if reset {
 2388            let pointer_position = display_map
 2389                .buffer_snapshot
 2390                .anchor_before(position.to_point(&display_map));
 2391
 2392            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2393                s.clear_disjoint();
 2394                s.set_pending_anchor_range(
 2395                    pointer_position..pointer_position,
 2396                    SelectMode::Character,
 2397                );
 2398            });
 2399        }
 2400
 2401        let tail = self.selections.newest::<Point>(cx).tail();
 2402        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2403
 2404        if !reset {
 2405            self.select_columns(
 2406                tail.to_display_point(&display_map),
 2407                position,
 2408                goal_column,
 2409                &display_map,
 2410                window,
 2411                cx,
 2412            );
 2413        }
 2414    }
 2415
 2416    fn update_selection(
 2417        &mut self,
 2418        position: DisplayPoint,
 2419        goal_column: u32,
 2420        scroll_delta: gpui::Point<f32>,
 2421        window: &mut Window,
 2422        cx: &mut Context<Self>,
 2423    ) {
 2424        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2425
 2426        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2427            let tail = tail.to_display_point(&display_map);
 2428            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2429        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2430            let buffer = self.buffer.read(cx).snapshot(cx);
 2431            let head;
 2432            let tail;
 2433            let mode = self.selections.pending_mode().unwrap();
 2434            match &mode {
 2435                SelectMode::Character => {
 2436                    head = position.to_point(&display_map);
 2437                    tail = pending.tail().to_point(&buffer);
 2438                }
 2439                SelectMode::Word(original_range) => {
 2440                    let original_display_range = original_range.start.to_display_point(&display_map)
 2441                        ..original_range.end.to_display_point(&display_map);
 2442                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2443                        ..original_display_range.end.to_point(&display_map);
 2444                    if movement::is_inside_word(&display_map, position)
 2445                        || original_display_range.contains(&position)
 2446                    {
 2447                        let word_range = movement::surrounding_word(&display_map, position);
 2448                        if word_range.start < original_display_range.start {
 2449                            head = word_range.start.to_point(&display_map);
 2450                        } else {
 2451                            head = word_range.end.to_point(&display_map);
 2452                        }
 2453                    } else {
 2454                        head = position.to_point(&display_map);
 2455                    }
 2456
 2457                    if head <= original_buffer_range.start {
 2458                        tail = original_buffer_range.end;
 2459                    } else {
 2460                        tail = original_buffer_range.start;
 2461                    }
 2462                }
 2463                SelectMode::Line(original_range) => {
 2464                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2465
 2466                    let position = display_map
 2467                        .clip_point(position, Bias::Left)
 2468                        .to_point(&display_map);
 2469                    let line_start = display_map.prev_line_boundary(position).0;
 2470                    let next_line_start = buffer.clip_point(
 2471                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2472                        Bias::Left,
 2473                    );
 2474
 2475                    if line_start < original_range.start {
 2476                        head = line_start
 2477                    } else {
 2478                        head = next_line_start
 2479                    }
 2480
 2481                    if head <= original_range.start {
 2482                        tail = original_range.end;
 2483                    } else {
 2484                        tail = original_range.start;
 2485                    }
 2486                }
 2487                SelectMode::All => {
 2488                    return;
 2489                }
 2490            };
 2491
 2492            if head < tail {
 2493                pending.start = buffer.anchor_before(head);
 2494                pending.end = buffer.anchor_before(tail);
 2495                pending.reversed = true;
 2496            } else {
 2497                pending.start = buffer.anchor_before(tail);
 2498                pending.end = buffer.anchor_before(head);
 2499                pending.reversed = false;
 2500            }
 2501
 2502            self.change_selections(None, window, cx, |s| {
 2503                s.set_pending(pending, mode);
 2504            });
 2505        } else {
 2506            log::error!("update_selection dispatched with no pending selection");
 2507            return;
 2508        }
 2509
 2510        self.apply_scroll_delta(scroll_delta, window, cx);
 2511        cx.notify();
 2512    }
 2513
 2514    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2515        self.columnar_selection_tail.take();
 2516        if self.selections.pending_anchor().is_some() {
 2517            let selections = self.selections.all::<usize>(cx);
 2518            self.change_selections(None, window, cx, |s| {
 2519                s.select(selections);
 2520                s.clear_pending();
 2521            });
 2522        }
 2523    }
 2524
 2525    fn select_columns(
 2526        &mut self,
 2527        tail: DisplayPoint,
 2528        head: DisplayPoint,
 2529        goal_column: u32,
 2530        display_map: &DisplaySnapshot,
 2531        window: &mut Window,
 2532        cx: &mut Context<Self>,
 2533    ) {
 2534        let start_row = cmp::min(tail.row(), head.row());
 2535        let end_row = cmp::max(tail.row(), head.row());
 2536        let start_column = cmp::min(tail.column(), goal_column);
 2537        let end_column = cmp::max(tail.column(), goal_column);
 2538        let reversed = start_column < tail.column();
 2539
 2540        let selection_ranges = (start_row.0..=end_row.0)
 2541            .map(DisplayRow)
 2542            .filter_map(|row| {
 2543                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2544                    let start = display_map
 2545                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2546                        .to_point(display_map);
 2547                    let end = display_map
 2548                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2549                        .to_point(display_map);
 2550                    if reversed {
 2551                        Some(end..start)
 2552                    } else {
 2553                        Some(start..end)
 2554                    }
 2555                } else {
 2556                    None
 2557                }
 2558            })
 2559            .collect::<Vec<_>>();
 2560
 2561        self.change_selections(None, window, cx, |s| {
 2562            s.select_ranges(selection_ranges);
 2563        });
 2564        cx.notify();
 2565    }
 2566
 2567    pub fn has_pending_nonempty_selection(&self) -> bool {
 2568        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2569            Some(Selection { start, end, .. }) => start != end,
 2570            None => false,
 2571        };
 2572
 2573        pending_nonempty_selection
 2574            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2575    }
 2576
 2577    pub fn has_pending_selection(&self) -> bool {
 2578        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2579    }
 2580
 2581    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2582        self.selection_mark_mode = false;
 2583
 2584        if self.clear_expanded_diff_hunks(cx) {
 2585            cx.notify();
 2586            return;
 2587        }
 2588        if self.dismiss_menus_and_popups(true, window, cx) {
 2589            return;
 2590        }
 2591
 2592        if self.mode == EditorMode::Full
 2593            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2594        {
 2595            return;
 2596        }
 2597
 2598        cx.propagate();
 2599    }
 2600
 2601    pub fn dismiss_menus_and_popups(
 2602        &mut self,
 2603        is_user_requested: bool,
 2604        window: &mut Window,
 2605        cx: &mut Context<Self>,
 2606    ) -> bool {
 2607        if self.take_rename(false, window, cx).is_some() {
 2608            return true;
 2609        }
 2610
 2611        if hide_hover(self, cx) {
 2612            return true;
 2613        }
 2614
 2615        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2616            return true;
 2617        }
 2618
 2619        if self.hide_context_menu(window, cx).is_some() {
 2620            return true;
 2621        }
 2622
 2623        if self.mouse_context_menu.take().is_some() {
 2624            return true;
 2625        }
 2626
 2627        if is_user_requested && self.discard_inline_completion(true, cx) {
 2628            return true;
 2629        }
 2630
 2631        if self.snippet_stack.pop().is_some() {
 2632            return true;
 2633        }
 2634
 2635        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2636            self.dismiss_diagnostics(cx);
 2637            return true;
 2638        }
 2639
 2640        false
 2641    }
 2642
 2643    fn linked_editing_ranges_for(
 2644        &self,
 2645        selection: Range<text::Anchor>,
 2646        cx: &App,
 2647    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2648        if self.linked_edit_ranges.is_empty() {
 2649            return None;
 2650        }
 2651        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2652            selection.end.buffer_id.and_then(|end_buffer_id| {
 2653                if selection.start.buffer_id != Some(end_buffer_id) {
 2654                    return None;
 2655                }
 2656                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2657                let snapshot = buffer.read(cx).snapshot();
 2658                self.linked_edit_ranges
 2659                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2660                    .map(|ranges| (ranges, snapshot, buffer))
 2661            })?;
 2662        use text::ToOffset as TO;
 2663        // find offset from the start of current range to current cursor position
 2664        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2665
 2666        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2667        let start_difference = start_offset - start_byte_offset;
 2668        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2669        let end_difference = end_offset - start_byte_offset;
 2670        // Current range has associated linked ranges.
 2671        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2672        for range in linked_ranges.iter() {
 2673            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2674            let end_offset = start_offset + end_difference;
 2675            let start_offset = start_offset + start_difference;
 2676            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2677                continue;
 2678            }
 2679            if self.selections.disjoint_anchor_ranges().any(|s| {
 2680                if s.start.buffer_id != selection.start.buffer_id
 2681                    || s.end.buffer_id != selection.end.buffer_id
 2682                {
 2683                    return false;
 2684                }
 2685                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2686                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2687            }) {
 2688                continue;
 2689            }
 2690            let start = buffer_snapshot.anchor_after(start_offset);
 2691            let end = buffer_snapshot.anchor_after(end_offset);
 2692            linked_edits
 2693                .entry(buffer.clone())
 2694                .or_default()
 2695                .push(start..end);
 2696        }
 2697        Some(linked_edits)
 2698    }
 2699
 2700    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2701        let text: Arc<str> = text.into();
 2702
 2703        if self.read_only(cx) {
 2704            return;
 2705        }
 2706
 2707        let selections = self.selections.all_adjusted(cx);
 2708        let mut bracket_inserted = false;
 2709        let mut edits = Vec::new();
 2710        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2711        let mut new_selections = Vec::with_capacity(selections.len());
 2712        let mut new_autoclose_regions = Vec::new();
 2713        let snapshot = self.buffer.read(cx).read(cx);
 2714
 2715        for (selection, autoclose_region) in
 2716            self.selections_with_autoclose_regions(selections, &snapshot)
 2717        {
 2718            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2719                // Determine if the inserted text matches the opening or closing
 2720                // bracket of any of this language's bracket pairs.
 2721                let mut bracket_pair = None;
 2722                let mut is_bracket_pair_start = false;
 2723                let mut is_bracket_pair_end = false;
 2724                if !text.is_empty() {
 2725                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2726                    //  and they are removing the character that triggered IME popup.
 2727                    for (pair, enabled) in scope.brackets() {
 2728                        if !pair.close && !pair.surround {
 2729                            continue;
 2730                        }
 2731
 2732                        if enabled && pair.start.ends_with(text.as_ref()) {
 2733                            let prefix_len = pair.start.len() - text.len();
 2734                            let preceding_text_matches_prefix = prefix_len == 0
 2735                                || (selection.start.column >= (prefix_len as u32)
 2736                                    && snapshot.contains_str_at(
 2737                                        Point::new(
 2738                                            selection.start.row,
 2739                                            selection.start.column - (prefix_len as u32),
 2740                                        ),
 2741                                        &pair.start[..prefix_len],
 2742                                    ));
 2743                            if preceding_text_matches_prefix {
 2744                                bracket_pair = Some(pair.clone());
 2745                                is_bracket_pair_start = true;
 2746                                break;
 2747                            }
 2748                        }
 2749                        if pair.end.as_str() == text.as_ref() {
 2750                            bracket_pair = Some(pair.clone());
 2751                            is_bracket_pair_end = true;
 2752                            break;
 2753                        }
 2754                    }
 2755                }
 2756
 2757                if let Some(bracket_pair) = bracket_pair {
 2758                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2759                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2760                    let auto_surround =
 2761                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2762                    if selection.is_empty() {
 2763                        if is_bracket_pair_start {
 2764                            // If the inserted text is a suffix of an opening bracket and the
 2765                            // selection is preceded by the rest of the opening bracket, then
 2766                            // insert the closing bracket.
 2767                            let following_text_allows_autoclose = snapshot
 2768                                .chars_at(selection.start)
 2769                                .next()
 2770                                .map_or(true, |c| scope.should_autoclose_before(c));
 2771
 2772                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2773                                && bracket_pair.start.len() == 1
 2774                            {
 2775                                let target = bracket_pair.start.chars().next().unwrap();
 2776                                let current_line_count = snapshot
 2777                                    .reversed_chars_at(selection.start)
 2778                                    .take_while(|&c| c != '\n')
 2779                                    .filter(|&c| c == target)
 2780                                    .count();
 2781                                current_line_count % 2 == 1
 2782                            } else {
 2783                                false
 2784                            };
 2785
 2786                            if autoclose
 2787                                && bracket_pair.close
 2788                                && following_text_allows_autoclose
 2789                                && !is_closing_quote
 2790                            {
 2791                                let anchor = snapshot.anchor_before(selection.end);
 2792                                new_selections.push((selection.map(|_| anchor), text.len()));
 2793                                new_autoclose_regions.push((
 2794                                    anchor,
 2795                                    text.len(),
 2796                                    selection.id,
 2797                                    bracket_pair.clone(),
 2798                                ));
 2799                                edits.push((
 2800                                    selection.range(),
 2801                                    format!("{}{}", text, bracket_pair.end).into(),
 2802                                ));
 2803                                bracket_inserted = true;
 2804                                continue;
 2805                            }
 2806                        }
 2807
 2808                        if let Some(region) = autoclose_region {
 2809                            // If the selection is followed by an auto-inserted closing bracket,
 2810                            // then don't insert that closing bracket again; just move the selection
 2811                            // past the closing bracket.
 2812                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2813                                && text.as_ref() == region.pair.end.as_str();
 2814                            if should_skip {
 2815                                let anchor = snapshot.anchor_after(selection.end);
 2816                                new_selections
 2817                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2818                                continue;
 2819                            }
 2820                        }
 2821
 2822                        let always_treat_brackets_as_autoclosed = snapshot
 2823                            .settings_at(selection.start, cx)
 2824                            .always_treat_brackets_as_autoclosed;
 2825                        if always_treat_brackets_as_autoclosed
 2826                            && is_bracket_pair_end
 2827                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2828                        {
 2829                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2830                            // and the inserted text is a closing bracket and the selection is followed
 2831                            // by the closing bracket then move the selection past the closing bracket.
 2832                            let anchor = snapshot.anchor_after(selection.end);
 2833                            new_selections.push((selection.map(|_| anchor), text.len()));
 2834                            continue;
 2835                        }
 2836                    }
 2837                    // If an opening bracket is 1 character long and is typed while
 2838                    // text is selected, then surround that text with the bracket pair.
 2839                    else if auto_surround
 2840                        && bracket_pair.surround
 2841                        && is_bracket_pair_start
 2842                        && bracket_pair.start.chars().count() == 1
 2843                    {
 2844                        edits.push((selection.start..selection.start, text.clone()));
 2845                        edits.push((
 2846                            selection.end..selection.end,
 2847                            bracket_pair.end.as_str().into(),
 2848                        ));
 2849                        bracket_inserted = true;
 2850                        new_selections.push((
 2851                            Selection {
 2852                                id: selection.id,
 2853                                start: snapshot.anchor_after(selection.start),
 2854                                end: snapshot.anchor_before(selection.end),
 2855                                reversed: selection.reversed,
 2856                                goal: selection.goal,
 2857                            },
 2858                            0,
 2859                        ));
 2860                        continue;
 2861                    }
 2862                }
 2863            }
 2864
 2865            if self.auto_replace_emoji_shortcode
 2866                && selection.is_empty()
 2867                && text.as_ref().ends_with(':')
 2868            {
 2869                if let Some(possible_emoji_short_code) =
 2870                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2871                {
 2872                    if !possible_emoji_short_code.is_empty() {
 2873                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2874                            let emoji_shortcode_start = Point::new(
 2875                                selection.start.row,
 2876                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2877                            );
 2878
 2879                            // Remove shortcode from buffer
 2880                            edits.push((
 2881                                emoji_shortcode_start..selection.start,
 2882                                "".to_string().into(),
 2883                            ));
 2884                            new_selections.push((
 2885                                Selection {
 2886                                    id: selection.id,
 2887                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2888                                    end: snapshot.anchor_before(selection.start),
 2889                                    reversed: selection.reversed,
 2890                                    goal: selection.goal,
 2891                                },
 2892                                0,
 2893                            ));
 2894
 2895                            // Insert emoji
 2896                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2897                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2898                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2899
 2900                            continue;
 2901                        }
 2902                    }
 2903                }
 2904            }
 2905
 2906            // If not handling any auto-close operation, then just replace the selected
 2907            // text with the given input and move the selection to the end of the
 2908            // newly inserted text.
 2909            let anchor = snapshot.anchor_after(selection.end);
 2910            if !self.linked_edit_ranges.is_empty() {
 2911                let start_anchor = snapshot.anchor_before(selection.start);
 2912
 2913                let is_word_char = text.chars().next().map_or(true, |char| {
 2914                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2915                    classifier.is_word(char)
 2916                });
 2917
 2918                if is_word_char {
 2919                    if let Some(ranges) = self
 2920                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2921                    {
 2922                        for (buffer, edits) in ranges {
 2923                            linked_edits
 2924                                .entry(buffer.clone())
 2925                                .or_default()
 2926                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2927                        }
 2928                    }
 2929                }
 2930            }
 2931
 2932            new_selections.push((selection.map(|_| anchor), 0));
 2933            edits.push((selection.start..selection.end, text.clone()));
 2934        }
 2935
 2936        drop(snapshot);
 2937
 2938        self.transact(window, cx, |this, window, cx| {
 2939            this.buffer.update(cx, |buffer, cx| {
 2940                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2941            });
 2942            for (buffer, edits) in linked_edits {
 2943                buffer.update(cx, |buffer, cx| {
 2944                    let snapshot = buffer.snapshot();
 2945                    let edits = edits
 2946                        .into_iter()
 2947                        .map(|(range, text)| {
 2948                            use text::ToPoint as TP;
 2949                            let end_point = TP::to_point(&range.end, &snapshot);
 2950                            let start_point = TP::to_point(&range.start, &snapshot);
 2951                            (start_point..end_point, text)
 2952                        })
 2953                        .sorted_by_key(|(range, _)| range.start)
 2954                        .collect::<Vec<_>>();
 2955                    buffer.edit(edits, None, cx);
 2956                })
 2957            }
 2958            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2959            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2960            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2961            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2962                .zip(new_selection_deltas)
 2963                .map(|(selection, delta)| Selection {
 2964                    id: selection.id,
 2965                    start: selection.start + delta,
 2966                    end: selection.end + delta,
 2967                    reversed: selection.reversed,
 2968                    goal: SelectionGoal::None,
 2969                })
 2970                .collect::<Vec<_>>();
 2971
 2972            let mut i = 0;
 2973            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2974                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2975                let start = map.buffer_snapshot.anchor_before(position);
 2976                let end = map.buffer_snapshot.anchor_after(position);
 2977                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2978                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2979                        Ordering::Less => i += 1,
 2980                        Ordering::Greater => break,
 2981                        Ordering::Equal => {
 2982                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2983                                Ordering::Less => i += 1,
 2984                                Ordering::Equal => break,
 2985                                Ordering::Greater => break,
 2986                            }
 2987                        }
 2988                    }
 2989                }
 2990                this.autoclose_regions.insert(
 2991                    i,
 2992                    AutocloseRegion {
 2993                        selection_id,
 2994                        range: start..end,
 2995                        pair,
 2996                    },
 2997                );
 2998            }
 2999
 3000            let had_active_inline_completion = this.has_active_inline_completion();
 3001            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3002                s.select(new_selections)
 3003            });
 3004
 3005            if !bracket_inserted {
 3006                if let Some(on_type_format_task) =
 3007                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3008                {
 3009                    on_type_format_task.detach_and_log_err(cx);
 3010                }
 3011            }
 3012
 3013            let editor_settings = EditorSettings::get_global(cx);
 3014            if bracket_inserted
 3015                && (editor_settings.auto_signature_help
 3016                    || editor_settings.show_signature_help_after_edits)
 3017            {
 3018                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3019            }
 3020
 3021            let trigger_in_words =
 3022                this.show_edit_predictions_in_menu(cx) || !had_active_inline_completion;
 3023            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3024            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3025            this.refresh_inline_completion(true, false, window, cx);
 3026        });
 3027    }
 3028
 3029    fn find_possible_emoji_shortcode_at_position(
 3030        snapshot: &MultiBufferSnapshot,
 3031        position: Point,
 3032    ) -> Option<String> {
 3033        let mut chars = Vec::new();
 3034        let mut found_colon = false;
 3035        for char in snapshot.reversed_chars_at(position).take(100) {
 3036            // Found a possible emoji shortcode in the middle of the buffer
 3037            if found_colon {
 3038                if char.is_whitespace() {
 3039                    chars.reverse();
 3040                    return Some(chars.iter().collect());
 3041                }
 3042                // If the previous character is not a whitespace, we are in the middle of a word
 3043                // and we only want to complete the shortcode if the word is made up of other emojis
 3044                let mut containing_word = String::new();
 3045                for ch in snapshot
 3046                    .reversed_chars_at(position)
 3047                    .skip(chars.len() + 1)
 3048                    .take(100)
 3049                {
 3050                    if ch.is_whitespace() {
 3051                        break;
 3052                    }
 3053                    containing_word.push(ch);
 3054                }
 3055                let containing_word = containing_word.chars().rev().collect::<String>();
 3056                if util::word_consists_of_emojis(containing_word.as_str()) {
 3057                    chars.reverse();
 3058                    return Some(chars.iter().collect());
 3059                }
 3060            }
 3061
 3062            if char.is_whitespace() || !char.is_ascii() {
 3063                return None;
 3064            }
 3065            if char == ':' {
 3066                found_colon = true;
 3067            } else {
 3068                chars.push(char);
 3069            }
 3070        }
 3071        // Found a possible emoji shortcode at the beginning of the buffer
 3072        chars.reverse();
 3073        Some(chars.iter().collect())
 3074    }
 3075
 3076    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3077        self.transact(window, cx, |this, window, cx| {
 3078            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3079                let selections = this.selections.all::<usize>(cx);
 3080                let multi_buffer = this.buffer.read(cx);
 3081                let buffer = multi_buffer.snapshot(cx);
 3082                selections
 3083                    .iter()
 3084                    .map(|selection| {
 3085                        let start_point = selection.start.to_point(&buffer);
 3086                        let mut indent =
 3087                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3088                        indent.len = cmp::min(indent.len, start_point.column);
 3089                        let start = selection.start;
 3090                        let end = selection.end;
 3091                        let selection_is_empty = start == end;
 3092                        let language_scope = buffer.language_scope_at(start);
 3093                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3094                            &language_scope
 3095                        {
 3096                            let leading_whitespace_len = buffer
 3097                                .reversed_chars_at(start)
 3098                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3099                                .map(|c| c.len_utf8())
 3100                                .sum::<usize>();
 3101
 3102                            let trailing_whitespace_len = buffer
 3103                                .chars_at(end)
 3104                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3105                                .map(|c| c.len_utf8())
 3106                                .sum::<usize>();
 3107
 3108                            let insert_extra_newline =
 3109                                language.brackets().any(|(pair, enabled)| {
 3110                                    let pair_start = pair.start.trim_end();
 3111                                    let pair_end = pair.end.trim_start();
 3112
 3113                                    enabled
 3114                                        && pair.newline
 3115                                        && buffer.contains_str_at(
 3116                                            end + trailing_whitespace_len,
 3117                                            pair_end,
 3118                                        )
 3119                                        && buffer.contains_str_at(
 3120                                            (start - leading_whitespace_len)
 3121                                                .saturating_sub(pair_start.len()),
 3122                                            pair_start,
 3123                                        )
 3124                                });
 3125
 3126                            // Comment extension on newline is allowed only for cursor selections
 3127                            let comment_delimiter = maybe!({
 3128                                if !selection_is_empty {
 3129                                    return None;
 3130                                }
 3131
 3132                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3133                                    return None;
 3134                                }
 3135
 3136                                let delimiters = language.line_comment_prefixes();
 3137                                let max_len_of_delimiter =
 3138                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3139                                let (snapshot, range) =
 3140                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3141
 3142                                let mut index_of_first_non_whitespace = 0;
 3143                                let comment_candidate = snapshot
 3144                                    .chars_for_range(range)
 3145                                    .skip_while(|c| {
 3146                                        let should_skip = c.is_whitespace();
 3147                                        if should_skip {
 3148                                            index_of_first_non_whitespace += 1;
 3149                                        }
 3150                                        should_skip
 3151                                    })
 3152                                    .take(max_len_of_delimiter)
 3153                                    .collect::<String>();
 3154                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3155                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3156                                })?;
 3157                                let cursor_is_placed_after_comment_marker =
 3158                                    index_of_first_non_whitespace + comment_prefix.len()
 3159                                        <= start_point.column as usize;
 3160                                if cursor_is_placed_after_comment_marker {
 3161                                    Some(comment_prefix.clone())
 3162                                } else {
 3163                                    None
 3164                                }
 3165                            });
 3166                            (comment_delimiter, insert_extra_newline)
 3167                        } else {
 3168                            (None, false)
 3169                        };
 3170
 3171                        let capacity_for_delimiter = comment_delimiter
 3172                            .as_deref()
 3173                            .map(str::len)
 3174                            .unwrap_or_default();
 3175                        let mut new_text =
 3176                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3177                        new_text.push('\n');
 3178                        new_text.extend(indent.chars());
 3179                        if let Some(delimiter) = &comment_delimiter {
 3180                            new_text.push_str(delimiter);
 3181                        }
 3182                        if insert_extra_newline {
 3183                            new_text = new_text.repeat(2);
 3184                        }
 3185
 3186                        let anchor = buffer.anchor_after(end);
 3187                        let new_selection = selection.map(|_| anchor);
 3188                        (
 3189                            (start..end, new_text),
 3190                            (insert_extra_newline, new_selection),
 3191                        )
 3192                    })
 3193                    .unzip()
 3194            };
 3195
 3196            this.edit_with_autoindent(edits, cx);
 3197            let buffer = this.buffer.read(cx).snapshot(cx);
 3198            let new_selections = selection_fixup_info
 3199                .into_iter()
 3200                .map(|(extra_newline_inserted, new_selection)| {
 3201                    let mut cursor = new_selection.end.to_point(&buffer);
 3202                    if extra_newline_inserted {
 3203                        cursor.row -= 1;
 3204                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3205                    }
 3206                    new_selection.map(|_| cursor)
 3207                })
 3208                .collect();
 3209
 3210            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3211                s.select(new_selections)
 3212            });
 3213            this.refresh_inline_completion(true, false, window, cx);
 3214        });
 3215    }
 3216
 3217    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3218        let buffer = self.buffer.read(cx);
 3219        let snapshot = buffer.snapshot(cx);
 3220
 3221        let mut edits = Vec::new();
 3222        let mut rows = Vec::new();
 3223
 3224        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3225            let cursor = selection.head();
 3226            let row = cursor.row;
 3227
 3228            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3229
 3230            let newline = "\n".to_string();
 3231            edits.push((start_of_line..start_of_line, newline));
 3232
 3233            rows.push(row + rows_inserted as u32);
 3234        }
 3235
 3236        self.transact(window, cx, |editor, window, cx| {
 3237            editor.edit(edits, cx);
 3238
 3239            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3240                let mut index = 0;
 3241                s.move_cursors_with(|map, _, _| {
 3242                    let row = rows[index];
 3243                    index += 1;
 3244
 3245                    let point = Point::new(row, 0);
 3246                    let boundary = map.next_line_boundary(point).1;
 3247                    let clipped = map.clip_point(boundary, Bias::Left);
 3248
 3249                    (clipped, SelectionGoal::None)
 3250                });
 3251            });
 3252
 3253            let mut indent_edits = Vec::new();
 3254            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3255            for row in rows {
 3256                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3257                for (row, indent) in indents {
 3258                    if indent.len == 0 {
 3259                        continue;
 3260                    }
 3261
 3262                    let text = match indent.kind {
 3263                        IndentKind::Space => " ".repeat(indent.len as usize),
 3264                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3265                    };
 3266                    let point = Point::new(row.0, 0);
 3267                    indent_edits.push((point..point, text));
 3268                }
 3269            }
 3270            editor.edit(indent_edits, cx);
 3271        });
 3272    }
 3273
 3274    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3275        let buffer = self.buffer.read(cx);
 3276        let snapshot = buffer.snapshot(cx);
 3277
 3278        let mut edits = Vec::new();
 3279        let mut rows = Vec::new();
 3280        let mut rows_inserted = 0;
 3281
 3282        for selection in self.selections.all_adjusted(cx) {
 3283            let cursor = selection.head();
 3284            let row = cursor.row;
 3285
 3286            let point = Point::new(row + 1, 0);
 3287            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3288
 3289            let newline = "\n".to_string();
 3290            edits.push((start_of_line..start_of_line, newline));
 3291
 3292            rows_inserted += 1;
 3293            rows.push(row + rows_inserted);
 3294        }
 3295
 3296        self.transact(window, cx, |editor, window, cx| {
 3297            editor.edit(edits, cx);
 3298
 3299            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3300                let mut index = 0;
 3301                s.move_cursors_with(|map, _, _| {
 3302                    let row = rows[index];
 3303                    index += 1;
 3304
 3305                    let point = Point::new(row, 0);
 3306                    let boundary = map.next_line_boundary(point).1;
 3307                    let clipped = map.clip_point(boundary, Bias::Left);
 3308
 3309                    (clipped, SelectionGoal::None)
 3310                });
 3311            });
 3312
 3313            let mut indent_edits = Vec::new();
 3314            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3315            for row in rows {
 3316                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3317                for (row, indent) in indents {
 3318                    if indent.len == 0 {
 3319                        continue;
 3320                    }
 3321
 3322                    let text = match indent.kind {
 3323                        IndentKind::Space => " ".repeat(indent.len as usize),
 3324                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3325                    };
 3326                    let point = Point::new(row.0, 0);
 3327                    indent_edits.push((point..point, text));
 3328                }
 3329            }
 3330            editor.edit(indent_edits, cx);
 3331        });
 3332    }
 3333
 3334    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3335        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3336            original_indent_columns: Vec::new(),
 3337        });
 3338        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3339    }
 3340
 3341    fn insert_with_autoindent_mode(
 3342        &mut self,
 3343        text: &str,
 3344        autoindent_mode: Option<AutoindentMode>,
 3345        window: &mut Window,
 3346        cx: &mut Context<Self>,
 3347    ) {
 3348        if self.read_only(cx) {
 3349            return;
 3350        }
 3351
 3352        let text: Arc<str> = text.into();
 3353        self.transact(window, cx, |this, window, cx| {
 3354            let old_selections = this.selections.all_adjusted(cx);
 3355            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3356                let anchors = {
 3357                    let snapshot = buffer.read(cx);
 3358                    old_selections
 3359                        .iter()
 3360                        .map(|s| {
 3361                            let anchor = snapshot.anchor_after(s.head());
 3362                            s.map(|_| anchor)
 3363                        })
 3364                        .collect::<Vec<_>>()
 3365                };
 3366                buffer.edit(
 3367                    old_selections
 3368                        .iter()
 3369                        .map(|s| (s.start..s.end, text.clone())),
 3370                    autoindent_mode,
 3371                    cx,
 3372                );
 3373                anchors
 3374            });
 3375
 3376            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3377                s.select_anchors(selection_anchors);
 3378            });
 3379
 3380            cx.notify();
 3381        });
 3382    }
 3383
 3384    fn trigger_completion_on_input(
 3385        &mut self,
 3386        text: &str,
 3387        trigger_in_words: bool,
 3388        window: &mut Window,
 3389        cx: &mut Context<Self>,
 3390    ) {
 3391        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3392            self.show_completions(
 3393                &ShowCompletions {
 3394                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3395                },
 3396                window,
 3397                cx,
 3398            );
 3399        } else {
 3400            self.hide_context_menu(window, cx);
 3401        }
 3402    }
 3403
 3404    fn is_completion_trigger(
 3405        &self,
 3406        text: &str,
 3407        trigger_in_words: bool,
 3408        cx: &mut Context<Self>,
 3409    ) -> bool {
 3410        let position = self.selections.newest_anchor().head();
 3411        let multibuffer = self.buffer.read(cx);
 3412        let Some(buffer) = position
 3413            .buffer_id
 3414            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3415        else {
 3416            return false;
 3417        };
 3418
 3419        if let Some(completion_provider) = &self.completion_provider {
 3420            completion_provider.is_completion_trigger(
 3421                &buffer,
 3422                position.text_anchor,
 3423                text,
 3424                trigger_in_words,
 3425                cx,
 3426            )
 3427        } else {
 3428            false
 3429        }
 3430    }
 3431
 3432    /// If any empty selections is touching the start of its innermost containing autoclose
 3433    /// region, expand it to select the brackets.
 3434    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3435        let selections = self.selections.all::<usize>(cx);
 3436        let buffer = self.buffer.read(cx).read(cx);
 3437        let new_selections = self
 3438            .selections_with_autoclose_regions(selections, &buffer)
 3439            .map(|(mut selection, region)| {
 3440                if !selection.is_empty() {
 3441                    return selection;
 3442                }
 3443
 3444                if let Some(region) = region {
 3445                    let mut range = region.range.to_offset(&buffer);
 3446                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3447                        range.start -= region.pair.start.len();
 3448                        if buffer.contains_str_at(range.start, &region.pair.start)
 3449                            && buffer.contains_str_at(range.end, &region.pair.end)
 3450                        {
 3451                            range.end += region.pair.end.len();
 3452                            selection.start = range.start;
 3453                            selection.end = range.end;
 3454
 3455                            return selection;
 3456                        }
 3457                    }
 3458                }
 3459
 3460                let always_treat_brackets_as_autoclosed = buffer
 3461                    .settings_at(selection.start, cx)
 3462                    .always_treat_brackets_as_autoclosed;
 3463
 3464                if !always_treat_brackets_as_autoclosed {
 3465                    return selection;
 3466                }
 3467
 3468                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3469                    for (pair, enabled) in scope.brackets() {
 3470                        if !enabled || !pair.close {
 3471                            continue;
 3472                        }
 3473
 3474                        if buffer.contains_str_at(selection.start, &pair.end) {
 3475                            let pair_start_len = pair.start.len();
 3476                            if buffer.contains_str_at(
 3477                                selection.start.saturating_sub(pair_start_len),
 3478                                &pair.start,
 3479                            ) {
 3480                                selection.start -= pair_start_len;
 3481                                selection.end += pair.end.len();
 3482
 3483                                return selection;
 3484                            }
 3485                        }
 3486                    }
 3487                }
 3488
 3489                selection
 3490            })
 3491            .collect();
 3492
 3493        drop(buffer);
 3494        self.change_selections(None, window, cx, |selections| {
 3495            selections.select(new_selections)
 3496        });
 3497    }
 3498
 3499    /// Iterate the given selections, and for each one, find the smallest surrounding
 3500    /// autoclose region. This uses the ordering of the selections and the autoclose
 3501    /// regions to avoid repeated comparisons.
 3502    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3503        &'a self,
 3504        selections: impl IntoIterator<Item = Selection<D>>,
 3505        buffer: &'a MultiBufferSnapshot,
 3506    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3507        let mut i = 0;
 3508        let mut regions = self.autoclose_regions.as_slice();
 3509        selections.into_iter().map(move |selection| {
 3510            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3511
 3512            let mut enclosing = None;
 3513            while let Some(pair_state) = regions.get(i) {
 3514                if pair_state.range.end.to_offset(buffer) < range.start {
 3515                    regions = &regions[i + 1..];
 3516                    i = 0;
 3517                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3518                    break;
 3519                } else {
 3520                    if pair_state.selection_id == selection.id {
 3521                        enclosing = Some(pair_state);
 3522                    }
 3523                    i += 1;
 3524                }
 3525            }
 3526
 3527            (selection, enclosing)
 3528        })
 3529    }
 3530
 3531    /// Remove any autoclose regions that no longer contain their selection.
 3532    fn invalidate_autoclose_regions(
 3533        &mut self,
 3534        mut selections: &[Selection<Anchor>],
 3535        buffer: &MultiBufferSnapshot,
 3536    ) {
 3537        self.autoclose_regions.retain(|state| {
 3538            let mut i = 0;
 3539            while let Some(selection) = selections.get(i) {
 3540                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3541                    selections = &selections[1..];
 3542                    continue;
 3543                }
 3544                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3545                    break;
 3546                }
 3547                if selection.id == state.selection_id {
 3548                    return true;
 3549                } else {
 3550                    i += 1;
 3551                }
 3552            }
 3553            false
 3554        });
 3555    }
 3556
 3557    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3558        let offset = position.to_offset(buffer);
 3559        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3560        if offset > word_range.start && kind == Some(CharKind::Word) {
 3561            Some(
 3562                buffer
 3563                    .text_for_range(word_range.start..offset)
 3564                    .collect::<String>(),
 3565            )
 3566        } else {
 3567            None
 3568        }
 3569    }
 3570
 3571    pub fn toggle_inlay_hints(
 3572        &mut self,
 3573        _: &ToggleInlayHints,
 3574        _: &mut Window,
 3575        cx: &mut Context<Self>,
 3576    ) {
 3577        self.refresh_inlay_hints(
 3578            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3579            cx,
 3580        );
 3581    }
 3582
 3583    pub fn inlay_hints_enabled(&self) -> bool {
 3584        self.inlay_hint_cache.enabled
 3585    }
 3586
 3587    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3588        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3589            return;
 3590        }
 3591
 3592        let reason_description = reason.description();
 3593        let ignore_debounce = matches!(
 3594            reason,
 3595            InlayHintRefreshReason::SettingsChange(_)
 3596                | InlayHintRefreshReason::Toggle(_)
 3597                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3598        );
 3599        let (invalidate_cache, required_languages) = match reason {
 3600            InlayHintRefreshReason::Toggle(enabled) => {
 3601                self.inlay_hint_cache.enabled = enabled;
 3602                if enabled {
 3603                    (InvalidationStrategy::RefreshRequested, None)
 3604                } else {
 3605                    self.inlay_hint_cache.clear();
 3606                    self.splice_inlays(
 3607                        &self
 3608                            .visible_inlay_hints(cx)
 3609                            .iter()
 3610                            .map(|inlay| inlay.id)
 3611                            .collect::<Vec<InlayId>>(),
 3612                        Vec::new(),
 3613                        cx,
 3614                    );
 3615                    return;
 3616                }
 3617            }
 3618            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3619                match self.inlay_hint_cache.update_settings(
 3620                    &self.buffer,
 3621                    new_settings,
 3622                    self.visible_inlay_hints(cx),
 3623                    cx,
 3624                ) {
 3625                    ControlFlow::Break(Some(InlaySplice {
 3626                        to_remove,
 3627                        to_insert,
 3628                    })) => {
 3629                        self.splice_inlays(&to_remove, to_insert, cx);
 3630                        return;
 3631                    }
 3632                    ControlFlow::Break(None) => return,
 3633                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3634                }
 3635            }
 3636            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3637                if let Some(InlaySplice {
 3638                    to_remove,
 3639                    to_insert,
 3640                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3641                {
 3642                    self.splice_inlays(&to_remove, to_insert, cx);
 3643                }
 3644                return;
 3645            }
 3646            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3647            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3648                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3649            }
 3650            InlayHintRefreshReason::RefreshRequested => {
 3651                (InvalidationStrategy::RefreshRequested, None)
 3652            }
 3653        };
 3654
 3655        if let Some(InlaySplice {
 3656            to_remove,
 3657            to_insert,
 3658        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3659            reason_description,
 3660            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3661            invalidate_cache,
 3662            ignore_debounce,
 3663            cx,
 3664        ) {
 3665            self.splice_inlays(&to_remove, to_insert, cx);
 3666        }
 3667    }
 3668
 3669    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3670        self.display_map
 3671            .read(cx)
 3672            .current_inlays()
 3673            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3674            .cloned()
 3675            .collect()
 3676    }
 3677
 3678    pub fn excerpts_for_inlay_hints_query(
 3679        &self,
 3680        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3681        cx: &mut Context<Editor>,
 3682    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3683        let Some(project) = self.project.as_ref() else {
 3684            return HashMap::default();
 3685        };
 3686        let project = project.read(cx);
 3687        let multi_buffer = self.buffer().read(cx);
 3688        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3689        let multi_buffer_visible_start = self
 3690            .scroll_manager
 3691            .anchor()
 3692            .anchor
 3693            .to_point(&multi_buffer_snapshot);
 3694        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3695            multi_buffer_visible_start
 3696                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3697            Bias::Left,
 3698        );
 3699        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3700        multi_buffer_snapshot
 3701            .range_to_buffer_ranges(multi_buffer_visible_range)
 3702            .into_iter()
 3703            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3704            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3705                let buffer_file = project::File::from_dyn(buffer.file())?;
 3706                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3707                let worktree_entry = buffer_worktree
 3708                    .read(cx)
 3709                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3710                if worktree_entry.is_ignored {
 3711                    return None;
 3712                }
 3713
 3714                let language = buffer.language()?;
 3715                if let Some(restrict_to_languages) = restrict_to_languages {
 3716                    if !restrict_to_languages.contains(language) {
 3717                        return None;
 3718                    }
 3719                }
 3720                Some((
 3721                    excerpt_id,
 3722                    (
 3723                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3724                        buffer.version().clone(),
 3725                        excerpt_visible_range,
 3726                    ),
 3727                ))
 3728            })
 3729            .collect()
 3730    }
 3731
 3732    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3733        TextLayoutDetails {
 3734            text_system: window.text_system().clone(),
 3735            editor_style: self.style.clone().unwrap(),
 3736            rem_size: window.rem_size(),
 3737            scroll_anchor: self.scroll_manager.anchor(),
 3738            visible_rows: self.visible_line_count(),
 3739            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3740        }
 3741    }
 3742
 3743    pub fn splice_inlays(
 3744        &self,
 3745        to_remove: &[InlayId],
 3746        to_insert: Vec<Inlay>,
 3747        cx: &mut Context<Self>,
 3748    ) {
 3749        self.display_map.update(cx, |display_map, cx| {
 3750            display_map.splice_inlays(to_remove, to_insert, cx)
 3751        });
 3752        cx.notify();
 3753    }
 3754
 3755    fn trigger_on_type_formatting(
 3756        &self,
 3757        input: String,
 3758        window: &mut Window,
 3759        cx: &mut Context<Self>,
 3760    ) -> Option<Task<Result<()>>> {
 3761        if input.len() != 1 {
 3762            return None;
 3763        }
 3764
 3765        let project = self.project.as_ref()?;
 3766        let position = self.selections.newest_anchor().head();
 3767        let (buffer, buffer_position) = self
 3768            .buffer
 3769            .read(cx)
 3770            .text_anchor_for_position(position, cx)?;
 3771
 3772        let settings = language_settings::language_settings(
 3773            buffer
 3774                .read(cx)
 3775                .language_at(buffer_position)
 3776                .map(|l| l.name()),
 3777            buffer.read(cx).file(),
 3778            cx,
 3779        );
 3780        if !settings.use_on_type_format {
 3781            return None;
 3782        }
 3783
 3784        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3785        // hence we do LSP request & edit on host side only — add formats to host's history.
 3786        let push_to_lsp_host_history = true;
 3787        // If this is not the host, append its history with new edits.
 3788        let push_to_client_history = project.read(cx).is_via_collab();
 3789
 3790        let on_type_formatting = project.update(cx, |project, cx| {
 3791            project.on_type_format(
 3792                buffer.clone(),
 3793                buffer_position,
 3794                input,
 3795                push_to_lsp_host_history,
 3796                cx,
 3797            )
 3798        });
 3799        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3800            if let Some(transaction) = on_type_formatting.await? {
 3801                if push_to_client_history {
 3802                    buffer
 3803                        .update(&mut cx, |buffer, _| {
 3804                            buffer.push_transaction(transaction, Instant::now());
 3805                        })
 3806                        .ok();
 3807                }
 3808                editor.update(&mut cx, |editor, cx| {
 3809                    editor.refresh_document_highlights(cx);
 3810                })?;
 3811            }
 3812            Ok(())
 3813        }))
 3814    }
 3815
 3816    pub fn show_completions(
 3817        &mut self,
 3818        options: &ShowCompletions,
 3819        window: &mut Window,
 3820        cx: &mut Context<Self>,
 3821    ) {
 3822        if self.pending_rename.is_some() {
 3823            return;
 3824        }
 3825
 3826        let Some(provider) = self.completion_provider.as_ref() else {
 3827            return;
 3828        };
 3829
 3830        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3831            return;
 3832        }
 3833
 3834        let position = self.selections.newest_anchor().head();
 3835        if position.diff_base_anchor.is_some() {
 3836            return;
 3837        }
 3838        let (buffer, buffer_position) =
 3839            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3840                output
 3841            } else {
 3842                return;
 3843            };
 3844        let show_completion_documentation = buffer
 3845            .read(cx)
 3846            .snapshot()
 3847            .settings_at(buffer_position, cx)
 3848            .show_completion_documentation;
 3849
 3850        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3851
 3852        let trigger_kind = match &options.trigger {
 3853            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3854                CompletionTriggerKind::TRIGGER_CHARACTER
 3855            }
 3856            _ => CompletionTriggerKind::INVOKED,
 3857        };
 3858        let completion_context = CompletionContext {
 3859            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3860                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3861                    Some(String::from(trigger))
 3862                } else {
 3863                    None
 3864                }
 3865            }),
 3866            trigger_kind,
 3867        };
 3868        let completions =
 3869            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3870        let sort_completions = provider.sort_completions();
 3871
 3872        let id = post_inc(&mut self.next_completion_id);
 3873        let task = cx.spawn_in(window, |editor, mut cx| {
 3874            async move {
 3875                editor.update(&mut cx, |this, _| {
 3876                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3877                })?;
 3878                let completions = completions.await.log_err();
 3879                let menu = if let Some(completions) = completions {
 3880                    let mut menu = CompletionsMenu::new(
 3881                        id,
 3882                        sort_completions,
 3883                        show_completion_documentation,
 3884                        position,
 3885                        buffer.clone(),
 3886                        completions.into(),
 3887                    );
 3888
 3889                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3890                        .await;
 3891
 3892                    menu.visible().then_some(menu)
 3893                } else {
 3894                    None
 3895                };
 3896
 3897                editor.update_in(&mut cx, |editor, window, cx| {
 3898                    match editor.context_menu.borrow().as_ref() {
 3899                        None => {}
 3900                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3901                            if prev_menu.id > id {
 3902                                return;
 3903                            }
 3904                        }
 3905                        _ => return,
 3906                    }
 3907
 3908                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3909                        let mut menu = menu.unwrap();
 3910                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3911
 3912                        *editor.context_menu.borrow_mut() =
 3913                            Some(CodeContextMenu::Completions(menu));
 3914
 3915                        if editor.show_edit_predictions_in_menu(cx) {
 3916                            editor.update_visible_inline_completion(window, cx);
 3917                        } else {
 3918                            editor.discard_inline_completion(false, cx);
 3919                        }
 3920
 3921                        cx.notify();
 3922                    } else if editor.completion_tasks.len() <= 1 {
 3923                        // If there are no more completion tasks and the last menu was
 3924                        // empty, we should hide it.
 3925                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3926                        // If it was already hidden and we don't show inline
 3927                        // completions in the menu, we should also show the
 3928                        // inline-completion when available.
 3929                        if was_hidden && editor.show_edit_predictions_in_menu(cx) {
 3930                            editor.update_visible_inline_completion(window, cx);
 3931                        }
 3932                    }
 3933                })?;
 3934
 3935                Ok::<_, anyhow::Error>(())
 3936            }
 3937            .log_err()
 3938        });
 3939
 3940        self.completion_tasks.push((id, task));
 3941    }
 3942
 3943    pub fn confirm_completion(
 3944        &mut self,
 3945        action: &ConfirmCompletion,
 3946        window: &mut Window,
 3947        cx: &mut Context<Self>,
 3948    ) -> Option<Task<Result<()>>> {
 3949        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3950    }
 3951
 3952    pub fn compose_completion(
 3953        &mut self,
 3954        action: &ComposeCompletion,
 3955        window: &mut Window,
 3956        cx: &mut Context<Self>,
 3957    ) -> Option<Task<Result<()>>> {
 3958        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3959    }
 3960
 3961    fn do_completion(
 3962        &mut self,
 3963        item_ix: Option<usize>,
 3964        intent: CompletionIntent,
 3965        window: &mut Window,
 3966        cx: &mut Context<Editor>,
 3967    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3968        use language::ToOffset as _;
 3969
 3970        let completions_menu =
 3971            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3972                menu
 3973            } else {
 3974                return None;
 3975            };
 3976
 3977        let entries = completions_menu.entries.borrow();
 3978        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3979        if self.show_edit_predictions_in_menu(cx) {
 3980            self.discard_inline_completion(true, cx);
 3981        }
 3982        let candidate_id = mat.candidate_id;
 3983        drop(entries);
 3984
 3985        let buffer_handle = completions_menu.buffer;
 3986        let completion = completions_menu
 3987            .completions
 3988            .borrow()
 3989            .get(candidate_id)?
 3990            .clone();
 3991        cx.stop_propagation();
 3992
 3993        let snippet;
 3994        let text;
 3995
 3996        if completion.is_snippet() {
 3997            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3998            text = snippet.as_ref().unwrap().text.clone();
 3999        } else {
 4000            snippet = None;
 4001            text = completion.new_text.clone();
 4002        };
 4003        let selections = self.selections.all::<usize>(cx);
 4004        let buffer = buffer_handle.read(cx);
 4005        let old_range = completion.old_range.to_offset(buffer);
 4006        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4007
 4008        let newest_selection = self.selections.newest_anchor();
 4009        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4010            return None;
 4011        }
 4012
 4013        let lookbehind = newest_selection
 4014            .start
 4015            .text_anchor
 4016            .to_offset(buffer)
 4017            .saturating_sub(old_range.start);
 4018        let lookahead = old_range
 4019            .end
 4020            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4021        let mut common_prefix_len = old_text
 4022            .bytes()
 4023            .zip(text.bytes())
 4024            .take_while(|(a, b)| a == b)
 4025            .count();
 4026
 4027        let snapshot = self.buffer.read(cx).snapshot(cx);
 4028        let mut range_to_replace: Option<Range<isize>> = None;
 4029        let mut ranges = Vec::new();
 4030        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4031        for selection in &selections {
 4032            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4033                let start = selection.start.saturating_sub(lookbehind);
 4034                let end = selection.end + lookahead;
 4035                if selection.id == newest_selection.id {
 4036                    range_to_replace = Some(
 4037                        ((start + common_prefix_len) as isize - selection.start as isize)
 4038                            ..(end as isize - selection.start as isize),
 4039                    );
 4040                }
 4041                ranges.push(start + common_prefix_len..end);
 4042            } else {
 4043                common_prefix_len = 0;
 4044                ranges.clear();
 4045                ranges.extend(selections.iter().map(|s| {
 4046                    if s.id == newest_selection.id {
 4047                        range_to_replace = Some(
 4048                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4049                                - selection.start as isize
 4050                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4051                                    - selection.start as isize,
 4052                        );
 4053                        old_range.clone()
 4054                    } else {
 4055                        s.start..s.end
 4056                    }
 4057                }));
 4058                break;
 4059            }
 4060            if !self.linked_edit_ranges.is_empty() {
 4061                let start_anchor = snapshot.anchor_before(selection.head());
 4062                let end_anchor = snapshot.anchor_after(selection.tail());
 4063                if let Some(ranges) = self
 4064                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4065                {
 4066                    for (buffer, edits) in ranges {
 4067                        linked_edits.entry(buffer.clone()).or_default().extend(
 4068                            edits
 4069                                .into_iter()
 4070                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4071                        );
 4072                    }
 4073                }
 4074            }
 4075        }
 4076        let text = &text[common_prefix_len..];
 4077
 4078        cx.emit(EditorEvent::InputHandled {
 4079            utf16_range_to_replace: range_to_replace,
 4080            text: text.into(),
 4081        });
 4082
 4083        self.transact(window, cx, |this, window, cx| {
 4084            if let Some(mut snippet) = snippet {
 4085                snippet.text = text.to_string();
 4086                for tabstop in snippet
 4087                    .tabstops
 4088                    .iter_mut()
 4089                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4090                {
 4091                    tabstop.start -= common_prefix_len as isize;
 4092                    tabstop.end -= common_prefix_len as isize;
 4093                }
 4094
 4095                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4096            } else {
 4097                this.buffer.update(cx, |buffer, cx| {
 4098                    buffer.edit(
 4099                        ranges.iter().map(|range| (range.clone(), text)),
 4100                        this.autoindent_mode.clone(),
 4101                        cx,
 4102                    );
 4103                });
 4104            }
 4105            for (buffer, edits) in linked_edits {
 4106                buffer.update(cx, |buffer, cx| {
 4107                    let snapshot = buffer.snapshot();
 4108                    let edits = edits
 4109                        .into_iter()
 4110                        .map(|(range, text)| {
 4111                            use text::ToPoint as TP;
 4112                            let end_point = TP::to_point(&range.end, &snapshot);
 4113                            let start_point = TP::to_point(&range.start, &snapshot);
 4114                            (start_point..end_point, text)
 4115                        })
 4116                        .sorted_by_key(|(range, _)| range.start)
 4117                        .collect::<Vec<_>>();
 4118                    buffer.edit(edits, None, cx);
 4119                })
 4120            }
 4121
 4122            this.refresh_inline_completion(true, false, window, cx);
 4123        });
 4124
 4125        let show_new_completions_on_confirm = completion
 4126            .confirm
 4127            .as_ref()
 4128            .map_or(false, |confirm| confirm(intent, window, cx));
 4129        if show_new_completions_on_confirm {
 4130            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4131        }
 4132
 4133        let provider = self.completion_provider.as_ref()?;
 4134        drop(completion);
 4135        let apply_edits = provider.apply_additional_edits_for_completion(
 4136            buffer_handle,
 4137            completions_menu.completions.clone(),
 4138            candidate_id,
 4139            true,
 4140            cx,
 4141        );
 4142
 4143        let editor_settings = EditorSettings::get_global(cx);
 4144        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4145            // After the code completion is finished, users often want to know what signatures are needed.
 4146            // so we should automatically call signature_help
 4147            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4148        }
 4149
 4150        Some(cx.foreground_executor().spawn(async move {
 4151            apply_edits.await?;
 4152            Ok(())
 4153        }))
 4154    }
 4155
 4156    pub fn toggle_code_actions(
 4157        &mut self,
 4158        action: &ToggleCodeActions,
 4159        window: &mut Window,
 4160        cx: &mut Context<Self>,
 4161    ) {
 4162        let mut context_menu = self.context_menu.borrow_mut();
 4163        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4164            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4165                // Toggle if we're selecting the same one
 4166                *context_menu = None;
 4167                cx.notify();
 4168                return;
 4169            } else {
 4170                // Otherwise, clear it and start a new one
 4171                *context_menu = None;
 4172                cx.notify();
 4173            }
 4174        }
 4175        drop(context_menu);
 4176        let snapshot = self.snapshot(window, cx);
 4177        let deployed_from_indicator = action.deployed_from_indicator;
 4178        let mut task = self.code_actions_task.take();
 4179        let action = action.clone();
 4180        cx.spawn_in(window, |editor, mut cx| async move {
 4181            while let Some(prev_task) = task {
 4182                prev_task.await.log_err();
 4183                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4184            }
 4185
 4186            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4187                if editor.focus_handle.is_focused(window) {
 4188                    let multibuffer_point = action
 4189                        .deployed_from_indicator
 4190                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4191                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4192                    let (buffer, buffer_row) = snapshot
 4193                        .buffer_snapshot
 4194                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4195                        .and_then(|(buffer_snapshot, range)| {
 4196                            editor
 4197                                .buffer
 4198                                .read(cx)
 4199                                .buffer(buffer_snapshot.remote_id())
 4200                                .map(|buffer| (buffer, range.start.row))
 4201                        })?;
 4202                    let (_, code_actions) = editor
 4203                        .available_code_actions
 4204                        .clone()
 4205                        .and_then(|(location, code_actions)| {
 4206                            let snapshot = location.buffer.read(cx).snapshot();
 4207                            let point_range = location.range.to_point(&snapshot);
 4208                            let point_range = point_range.start.row..=point_range.end.row;
 4209                            if point_range.contains(&buffer_row) {
 4210                                Some((location, code_actions))
 4211                            } else {
 4212                                None
 4213                            }
 4214                        })
 4215                        .unzip();
 4216                    let buffer_id = buffer.read(cx).remote_id();
 4217                    let tasks = editor
 4218                        .tasks
 4219                        .get(&(buffer_id, buffer_row))
 4220                        .map(|t| Arc::new(t.to_owned()));
 4221                    if tasks.is_none() && code_actions.is_none() {
 4222                        return None;
 4223                    }
 4224
 4225                    editor.completion_tasks.clear();
 4226                    editor.discard_inline_completion(false, cx);
 4227                    let task_context =
 4228                        tasks
 4229                            .as_ref()
 4230                            .zip(editor.project.clone())
 4231                            .map(|(tasks, project)| {
 4232                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4233                            });
 4234
 4235                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4236                        let task_context = match task_context {
 4237                            Some(task_context) => task_context.await,
 4238                            None => None,
 4239                        };
 4240                        let resolved_tasks =
 4241                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4242                                Rc::new(ResolvedTasks {
 4243                                    templates: tasks.resolve(&task_context).collect(),
 4244                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4245                                        multibuffer_point.row,
 4246                                        tasks.column,
 4247                                    )),
 4248                                })
 4249                            });
 4250                        let spawn_straight_away = resolved_tasks
 4251                            .as_ref()
 4252                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4253                            && code_actions
 4254                                .as_ref()
 4255                                .map_or(true, |actions| actions.is_empty());
 4256                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4257                            *editor.context_menu.borrow_mut() =
 4258                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4259                                    buffer,
 4260                                    actions: CodeActionContents {
 4261                                        tasks: resolved_tasks,
 4262                                        actions: code_actions,
 4263                                    },
 4264                                    selected_item: Default::default(),
 4265                                    scroll_handle: UniformListScrollHandle::default(),
 4266                                    deployed_from_indicator,
 4267                                }));
 4268                            if spawn_straight_away {
 4269                                if let Some(task) = editor.confirm_code_action(
 4270                                    &ConfirmCodeAction { item_ix: Some(0) },
 4271                                    window,
 4272                                    cx,
 4273                                ) {
 4274                                    cx.notify();
 4275                                    return task;
 4276                                }
 4277                            }
 4278                            cx.notify();
 4279                            Task::ready(Ok(()))
 4280                        }) {
 4281                            task.await
 4282                        } else {
 4283                            Ok(())
 4284                        }
 4285                    }))
 4286                } else {
 4287                    Some(Task::ready(Ok(())))
 4288                }
 4289            })?;
 4290            if let Some(task) = spawned_test_task {
 4291                task.await?;
 4292            }
 4293
 4294            Ok::<_, anyhow::Error>(())
 4295        })
 4296        .detach_and_log_err(cx);
 4297    }
 4298
 4299    pub fn confirm_code_action(
 4300        &mut self,
 4301        action: &ConfirmCodeAction,
 4302        window: &mut Window,
 4303        cx: &mut Context<Self>,
 4304    ) -> Option<Task<Result<()>>> {
 4305        let actions_menu =
 4306            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4307                menu
 4308            } else {
 4309                return None;
 4310            };
 4311        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4312        let action = actions_menu.actions.get(action_ix)?;
 4313        let title = action.label();
 4314        let buffer = actions_menu.buffer;
 4315        let workspace = self.workspace()?;
 4316
 4317        match action {
 4318            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4319                workspace.update(cx, |workspace, cx| {
 4320                    workspace::tasks::schedule_resolved_task(
 4321                        workspace,
 4322                        task_source_kind,
 4323                        resolved_task,
 4324                        false,
 4325                        cx,
 4326                    );
 4327
 4328                    Some(Task::ready(Ok(())))
 4329                })
 4330            }
 4331            CodeActionsItem::CodeAction {
 4332                excerpt_id,
 4333                action,
 4334                provider,
 4335            } => {
 4336                let apply_code_action =
 4337                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4338                let workspace = workspace.downgrade();
 4339                Some(cx.spawn_in(window, |editor, cx| async move {
 4340                    let project_transaction = apply_code_action.await?;
 4341                    Self::open_project_transaction(
 4342                        &editor,
 4343                        workspace,
 4344                        project_transaction,
 4345                        title,
 4346                        cx,
 4347                    )
 4348                    .await
 4349                }))
 4350            }
 4351        }
 4352    }
 4353
 4354    pub async fn open_project_transaction(
 4355        this: &WeakEntity<Editor>,
 4356        workspace: WeakEntity<Workspace>,
 4357        transaction: ProjectTransaction,
 4358        title: String,
 4359        mut cx: AsyncWindowContext,
 4360    ) -> Result<()> {
 4361        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4362        cx.update(|_, cx| {
 4363            entries.sort_unstable_by_key(|(buffer, _)| {
 4364                buffer.read(cx).file().map(|f| f.path().clone())
 4365            });
 4366        })?;
 4367
 4368        // If the project transaction's edits are all contained within this editor, then
 4369        // avoid opening a new editor to display them.
 4370
 4371        if let Some((buffer, transaction)) = entries.first() {
 4372            if entries.len() == 1 {
 4373                let excerpt = this.update(&mut cx, |editor, cx| {
 4374                    editor
 4375                        .buffer()
 4376                        .read(cx)
 4377                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4378                })?;
 4379                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4380                    if excerpted_buffer == *buffer {
 4381                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4382                            let excerpt_range = excerpt_range.to_offset(buffer);
 4383                            buffer
 4384                                .edited_ranges_for_transaction::<usize>(transaction)
 4385                                .all(|range| {
 4386                                    excerpt_range.start <= range.start
 4387                                        && excerpt_range.end >= range.end
 4388                                })
 4389                        })?;
 4390
 4391                        if all_edits_within_excerpt {
 4392                            return Ok(());
 4393                        }
 4394                    }
 4395                }
 4396            }
 4397        } else {
 4398            return Ok(());
 4399        }
 4400
 4401        let mut ranges_to_highlight = Vec::new();
 4402        let excerpt_buffer = cx.new(|cx| {
 4403            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4404            for (buffer_handle, transaction) in &entries {
 4405                let buffer = buffer_handle.read(cx);
 4406                ranges_to_highlight.extend(
 4407                    multibuffer.push_excerpts_with_context_lines(
 4408                        buffer_handle.clone(),
 4409                        buffer
 4410                            .edited_ranges_for_transaction::<usize>(transaction)
 4411                            .collect(),
 4412                        DEFAULT_MULTIBUFFER_CONTEXT,
 4413                        cx,
 4414                    ),
 4415                );
 4416            }
 4417            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4418            multibuffer
 4419        })?;
 4420
 4421        workspace.update_in(&mut cx, |workspace, window, cx| {
 4422            let project = workspace.project().clone();
 4423            let editor = cx
 4424                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4425            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4426            editor.update(cx, |editor, cx| {
 4427                editor.highlight_background::<Self>(
 4428                    &ranges_to_highlight,
 4429                    |theme| theme.editor_highlighted_line_background,
 4430                    cx,
 4431                );
 4432            });
 4433        })?;
 4434
 4435        Ok(())
 4436    }
 4437
 4438    pub fn clear_code_action_providers(&mut self) {
 4439        self.code_action_providers.clear();
 4440        self.available_code_actions.take();
 4441    }
 4442
 4443    pub fn add_code_action_provider(
 4444        &mut self,
 4445        provider: Rc<dyn CodeActionProvider>,
 4446        window: &mut Window,
 4447        cx: &mut Context<Self>,
 4448    ) {
 4449        if self
 4450            .code_action_providers
 4451            .iter()
 4452            .any(|existing_provider| existing_provider.id() == provider.id())
 4453        {
 4454            return;
 4455        }
 4456
 4457        self.code_action_providers.push(provider);
 4458        self.refresh_code_actions(window, cx);
 4459    }
 4460
 4461    pub fn remove_code_action_provider(
 4462        &mut self,
 4463        id: Arc<str>,
 4464        window: &mut Window,
 4465        cx: &mut Context<Self>,
 4466    ) {
 4467        self.code_action_providers
 4468            .retain(|provider| provider.id() != id);
 4469        self.refresh_code_actions(window, cx);
 4470    }
 4471
 4472    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4473        let buffer = self.buffer.read(cx);
 4474        let newest_selection = self.selections.newest_anchor().clone();
 4475        if newest_selection.head().diff_base_anchor.is_some() {
 4476            return None;
 4477        }
 4478        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4479        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4480        if start_buffer != end_buffer {
 4481            return None;
 4482        }
 4483
 4484        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4485            cx.background_executor()
 4486                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4487                .await;
 4488
 4489            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4490                let providers = this.code_action_providers.clone();
 4491                let tasks = this
 4492                    .code_action_providers
 4493                    .iter()
 4494                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4495                    .collect::<Vec<_>>();
 4496                (providers, tasks)
 4497            })?;
 4498
 4499            let mut actions = Vec::new();
 4500            for (provider, provider_actions) in
 4501                providers.into_iter().zip(future::join_all(tasks).await)
 4502            {
 4503                if let Some(provider_actions) = provider_actions.log_err() {
 4504                    actions.extend(provider_actions.into_iter().map(|action| {
 4505                        AvailableCodeAction {
 4506                            excerpt_id: newest_selection.start.excerpt_id,
 4507                            action,
 4508                            provider: provider.clone(),
 4509                        }
 4510                    }));
 4511                }
 4512            }
 4513
 4514            this.update(&mut cx, |this, cx| {
 4515                this.available_code_actions = if actions.is_empty() {
 4516                    None
 4517                } else {
 4518                    Some((
 4519                        Location {
 4520                            buffer: start_buffer,
 4521                            range: start..end,
 4522                        },
 4523                        actions.into(),
 4524                    ))
 4525                };
 4526                cx.notify();
 4527            })
 4528        }));
 4529        None
 4530    }
 4531
 4532    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4533        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4534            self.show_git_blame_inline = false;
 4535
 4536            self.show_git_blame_inline_delay_task =
 4537                Some(cx.spawn_in(window, |this, mut cx| async move {
 4538                    cx.background_executor().timer(delay).await;
 4539
 4540                    this.update(&mut cx, |this, cx| {
 4541                        this.show_git_blame_inline = true;
 4542                        cx.notify();
 4543                    })
 4544                    .log_err();
 4545                }));
 4546        }
 4547    }
 4548
 4549    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4550        if self.pending_rename.is_some() {
 4551            return None;
 4552        }
 4553
 4554        let provider = self.semantics_provider.clone()?;
 4555        let buffer = self.buffer.read(cx);
 4556        let newest_selection = self.selections.newest_anchor().clone();
 4557        let cursor_position = newest_selection.head();
 4558        let (cursor_buffer, cursor_buffer_position) =
 4559            buffer.text_anchor_for_position(cursor_position, cx)?;
 4560        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4561        if cursor_buffer != tail_buffer {
 4562            return None;
 4563        }
 4564        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4565        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4566            cx.background_executor()
 4567                .timer(Duration::from_millis(debounce))
 4568                .await;
 4569
 4570            let highlights = if let Some(highlights) = cx
 4571                .update(|cx| {
 4572                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4573                })
 4574                .ok()
 4575                .flatten()
 4576            {
 4577                highlights.await.log_err()
 4578            } else {
 4579                None
 4580            };
 4581
 4582            if let Some(highlights) = highlights {
 4583                this.update(&mut cx, |this, cx| {
 4584                    if this.pending_rename.is_some() {
 4585                        return;
 4586                    }
 4587
 4588                    let buffer_id = cursor_position.buffer_id;
 4589                    let buffer = this.buffer.read(cx);
 4590                    if !buffer
 4591                        .text_anchor_for_position(cursor_position, cx)
 4592                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4593                    {
 4594                        return;
 4595                    }
 4596
 4597                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4598                    let mut write_ranges = Vec::new();
 4599                    let mut read_ranges = Vec::new();
 4600                    for highlight in highlights {
 4601                        for (excerpt_id, excerpt_range) in
 4602                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4603                        {
 4604                            let start = highlight
 4605                                .range
 4606                                .start
 4607                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4608                            let end = highlight
 4609                                .range
 4610                                .end
 4611                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4612                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4613                                continue;
 4614                            }
 4615
 4616                            let range = Anchor {
 4617                                buffer_id,
 4618                                excerpt_id,
 4619                                text_anchor: start,
 4620                                diff_base_anchor: None,
 4621                            }..Anchor {
 4622                                buffer_id,
 4623                                excerpt_id,
 4624                                text_anchor: end,
 4625                                diff_base_anchor: None,
 4626                            };
 4627                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4628                                write_ranges.push(range);
 4629                            } else {
 4630                                read_ranges.push(range);
 4631                            }
 4632                        }
 4633                    }
 4634
 4635                    this.highlight_background::<DocumentHighlightRead>(
 4636                        &read_ranges,
 4637                        |theme| theme.editor_document_highlight_read_background,
 4638                        cx,
 4639                    );
 4640                    this.highlight_background::<DocumentHighlightWrite>(
 4641                        &write_ranges,
 4642                        |theme| theme.editor_document_highlight_write_background,
 4643                        cx,
 4644                    );
 4645                    cx.notify();
 4646                })
 4647                .log_err();
 4648            }
 4649        }));
 4650        None
 4651    }
 4652
 4653    pub fn refresh_inline_completion(
 4654        &mut self,
 4655        debounce: bool,
 4656        user_requested: bool,
 4657        window: &mut Window,
 4658        cx: &mut Context<Self>,
 4659    ) -> Option<()> {
 4660        let provider = self.edit_prediction_provider()?;
 4661        let cursor = self.selections.newest_anchor().head();
 4662        let (buffer, cursor_buffer_position) =
 4663            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4664
 4665        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4666            self.discard_inline_completion(false, cx);
 4667            return None;
 4668        }
 4669
 4670        if !user_requested
 4671            && (!self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4672                || !self.is_focused(window)
 4673                || buffer.read(cx).is_empty())
 4674        {
 4675            self.discard_inline_completion(false, cx);
 4676            return None;
 4677        }
 4678
 4679        self.update_visible_inline_completion(window, cx);
 4680        provider.refresh(
 4681            self.project.clone(),
 4682            buffer,
 4683            cursor_buffer_position,
 4684            debounce,
 4685            cx,
 4686        );
 4687        Some(())
 4688    }
 4689
 4690    pub fn should_show_inline_completions(&self, cx: &App) -> bool {
 4691        let cursor = self.selections.newest_anchor().head();
 4692        if let Some((buffer, cursor_position)) =
 4693            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4694        {
 4695            self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
 4696        } else {
 4697            false
 4698        }
 4699    }
 4700
 4701    fn edit_prediction_requires_modifier(&self, cx: &App) -> bool {
 4702        let cursor = self.selections.newest_anchor().head();
 4703
 4704        self.buffer
 4705            .read(cx)
 4706            .text_anchor_for_position(cursor, cx)
 4707            .map(|(buffer, _)| {
 4708                all_language_settings(buffer.read(cx).file(), cx).inline_completions_preview_mode()
 4709                    == InlineCompletionPreviewMode::WhenHoldingModifier
 4710            })
 4711            .unwrap_or(false)
 4712    }
 4713
 4714    fn should_show_inline_completions_in_buffer(
 4715        &self,
 4716        buffer: &Entity<Buffer>,
 4717        buffer_position: language::Anchor,
 4718        cx: &App,
 4719    ) -> bool {
 4720        if !self.snippet_stack.is_empty() {
 4721            return false;
 4722        }
 4723
 4724        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 4725            return false;
 4726        }
 4727
 4728        if let Some(show_inline_completions) = self.show_inline_completions_override {
 4729            show_inline_completions
 4730        } else {
 4731            let buffer = buffer.read(cx);
 4732            self.mode == EditorMode::Full
 4733                && language_settings(
 4734                    buffer.language_at(buffer_position).map(|l| l.name()),
 4735                    buffer.file(),
 4736                    cx,
 4737                )
 4738                .show_edit_predictions
 4739        }
 4740    }
 4741
 4742    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4743        let cursor = self.selections.newest_anchor().head();
 4744        if let Some((buffer, cursor_position)) =
 4745            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4746        {
 4747            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4748        } else {
 4749            false
 4750        }
 4751    }
 4752
 4753    fn inline_completions_enabled_in_buffer(
 4754        &self,
 4755        buffer: &Entity<Buffer>,
 4756        buffer_position: language::Anchor,
 4757        cx: &App,
 4758    ) -> bool {
 4759        maybe!({
 4760            let provider = self.edit_prediction_provider()?;
 4761            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4762                return Some(false);
 4763            }
 4764            let buffer = buffer.read(cx);
 4765            let Some(file) = buffer.file() else {
 4766                return Some(true);
 4767            };
 4768            let settings = all_language_settings(Some(file), cx);
 4769            Some(settings.inline_completions_enabled_for_path(file.path()))
 4770        })
 4771        .unwrap_or(false)
 4772    }
 4773
 4774    fn cycle_inline_completion(
 4775        &mut self,
 4776        direction: Direction,
 4777        window: &mut Window,
 4778        cx: &mut Context<Self>,
 4779    ) -> Option<()> {
 4780        let provider = self.edit_prediction_provider()?;
 4781        let cursor = self.selections.newest_anchor().head();
 4782        let (buffer, cursor_buffer_position) =
 4783            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4784        if self.inline_completions_hidden_for_vim_mode
 4785            || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4786        {
 4787            return None;
 4788        }
 4789
 4790        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4791        self.update_visible_inline_completion(window, cx);
 4792
 4793        Some(())
 4794    }
 4795
 4796    pub fn show_inline_completion(
 4797        &mut self,
 4798        _: &ShowEditPrediction,
 4799        window: &mut Window,
 4800        cx: &mut Context<Self>,
 4801    ) {
 4802        if !self.has_active_inline_completion() {
 4803            self.refresh_inline_completion(false, true, window, cx);
 4804            return;
 4805        }
 4806
 4807        self.update_visible_inline_completion(window, cx);
 4808    }
 4809
 4810    pub fn display_cursor_names(
 4811        &mut self,
 4812        _: &DisplayCursorNames,
 4813        window: &mut Window,
 4814        cx: &mut Context<Self>,
 4815    ) {
 4816        self.show_cursor_names(window, cx);
 4817    }
 4818
 4819    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4820        self.show_cursor_names = true;
 4821        cx.notify();
 4822        cx.spawn_in(window, |this, mut cx| async move {
 4823            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4824            this.update(&mut cx, |this, cx| {
 4825                this.show_cursor_names = false;
 4826                cx.notify()
 4827            })
 4828            .ok()
 4829        })
 4830        .detach();
 4831    }
 4832
 4833    pub fn next_edit_prediction(
 4834        &mut self,
 4835        _: &NextEditPrediction,
 4836        window: &mut Window,
 4837        cx: &mut Context<Self>,
 4838    ) {
 4839        if self.has_active_inline_completion() {
 4840            self.cycle_inline_completion(Direction::Next, window, cx);
 4841        } else {
 4842            let is_copilot_disabled = self
 4843                .refresh_inline_completion(false, true, window, cx)
 4844                .is_none();
 4845            if is_copilot_disabled {
 4846                cx.propagate();
 4847            }
 4848        }
 4849    }
 4850
 4851    pub fn previous_edit_prediction(
 4852        &mut self,
 4853        _: &PreviousEditPrediction,
 4854        window: &mut Window,
 4855        cx: &mut Context<Self>,
 4856    ) {
 4857        if self.has_active_inline_completion() {
 4858            self.cycle_inline_completion(Direction::Prev, window, cx);
 4859        } else {
 4860            let is_copilot_disabled = self
 4861                .refresh_inline_completion(false, true, window, cx)
 4862                .is_none();
 4863            if is_copilot_disabled {
 4864                cx.propagate();
 4865            }
 4866        }
 4867    }
 4868
 4869    pub fn accept_edit_prediction(
 4870        &mut self,
 4871        _: &AcceptEditPrediction,
 4872        window: &mut Window,
 4873        cx: &mut Context<Self>,
 4874    ) {
 4875        let buffer = self.buffer.read(cx);
 4876        let snapshot = buffer.snapshot(cx);
 4877        let selection = self.selections.newest_adjusted(cx);
 4878        let cursor = selection.head();
 4879        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4880        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4881        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4882        {
 4883            if cursor.column < suggested_indent.len
 4884                && cursor.column <= current_indent.len
 4885                && current_indent.len <= suggested_indent.len
 4886            {
 4887                self.tab(&Default::default(), window, cx);
 4888                return;
 4889            }
 4890        }
 4891
 4892        if self.show_edit_predictions_in_menu(cx) {
 4893            self.hide_context_menu(window, cx);
 4894        }
 4895
 4896        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4897            return;
 4898        };
 4899
 4900        self.report_inline_completion_event(
 4901            active_inline_completion.completion_id.clone(),
 4902            true,
 4903            cx,
 4904        );
 4905
 4906        match &active_inline_completion.completion {
 4907            InlineCompletion::Move { target, .. } => {
 4908                let target = *target;
 4909                // Note that this is also done in vim's handler of the Tab action.
 4910                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4911                    selections.select_anchor_ranges([target..target]);
 4912                });
 4913            }
 4914            InlineCompletion::Edit { edits, .. } => {
 4915                if let Some(provider) = self.edit_prediction_provider() {
 4916                    provider.accept(cx);
 4917                }
 4918
 4919                let snapshot = self.buffer.read(cx).snapshot(cx);
 4920                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4921
 4922                self.buffer.update(cx, |buffer, cx| {
 4923                    buffer.edit(edits.iter().cloned(), None, cx)
 4924                });
 4925
 4926                self.change_selections(None, window, cx, |s| {
 4927                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4928                });
 4929
 4930                self.update_visible_inline_completion(window, cx);
 4931                if self.active_inline_completion.is_none() {
 4932                    self.refresh_inline_completion(true, true, window, cx);
 4933                }
 4934
 4935                cx.notify();
 4936            }
 4937        }
 4938    }
 4939
 4940    pub fn accept_partial_inline_completion(
 4941        &mut self,
 4942        _: &AcceptPartialEditPrediction,
 4943        window: &mut Window,
 4944        cx: &mut Context<Self>,
 4945    ) {
 4946        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4947            return;
 4948        };
 4949        if self.selections.count() != 1 {
 4950            return;
 4951        }
 4952
 4953        self.report_inline_completion_event(
 4954            active_inline_completion.completion_id.clone(),
 4955            true,
 4956            cx,
 4957        );
 4958
 4959        match &active_inline_completion.completion {
 4960            InlineCompletion::Move { target, .. } => {
 4961                let target = *target;
 4962                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4963                    selections.select_anchor_ranges([target..target]);
 4964                });
 4965            }
 4966            InlineCompletion::Edit { edits, .. } => {
 4967                // Find an insertion that starts at the cursor position.
 4968                let snapshot = self.buffer.read(cx).snapshot(cx);
 4969                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4970                let insertion = edits.iter().find_map(|(range, text)| {
 4971                    let range = range.to_offset(&snapshot);
 4972                    if range.is_empty() && range.start == cursor_offset {
 4973                        Some(text)
 4974                    } else {
 4975                        None
 4976                    }
 4977                });
 4978
 4979                if let Some(text) = insertion {
 4980                    let mut partial_completion = text
 4981                        .chars()
 4982                        .by_ref()
 4983                        .take_while(|c| c.is_alphabetic())
 4984                        .collect::<String>();
 4985                    if partial_completion.is_empty() {
 4986                        partial_completion = text
 4987                            .chars()
 4988                            .by_ref()
 4989                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4990                            .collect::<String>();
 4991                    }
 4992
 4993                    cx.emit(EditorEvent::InputHandled {
 4994                        utf16_range_to_replace: None,
 4995                        text: partial_completion.clone().into(),
 4996                    });
 4997
 4998                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4999
 5000                    self.refresh_inline_completion(true, true, window, cx);
 5001                    cx.notify();
 5002                } else {
 5003                    self.accept_edit_prediction(&Default::default(), window, cx);
 5004                }
 5005            }
 5006        }
 5007    }
 5008
 5009    fn discard_inline_completion(
 5010        &mut self,
 5011        should_report_inline_completion_event: bool,
 5012        cx: &mut Context<Self>,
 5013    ) -> bool {
 5014        if should_report_inline_completion_event {
 5015            let completion_id = self
 5016                .active_inline_completion
 5017                .as_ref()
 5018                .and_then(|active_completion| active_completion.completion_id.clone());
 5019
 5020            self.report_inline_completion_event(completion_id, false, cx);
 5021        }
 5022
 5023        if let Some(provider) = self.edit_prediction_provider() {
 5024            provider.discard(cx);
 5025        }
 5026
 5027        self.take_active_inline_completion(cx)
 5028    }
 5029
 5030    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5031        let Some(provider) = self.edit_prediction_provider() else {
 5032            return;
 5033        };
 5034
 5035        let Some((_, buffer, _)) = self
 5036            .buffer
 5037            .read(cx)
 5038            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5039        else {
 5040            return;
 5041        };
 5042
 5043        let extension = buffer
 5044            .read(cx)
 5045            .file()
 5046            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5047
 5048        let event_type = match accepted {
 5049            true => "Edit Prediction Accepted",
 5050            false => "Edit Prediction Discarded",
 5051        };
 5052        telemetry::event!(
 5053            event_type,
 5054            provider = provider.name(),
 5055            prediction_id = id,
 5056            suggestion_accepted = accepted,
 5057            file_extension = extension,
 5058        );
 5059    }
 5060
 5061    pub fn has_active_inline_completion(&self) -> bool {
 5062        self.active_inline_completion.is_some()
 5063    }
 5064
 5065    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5066        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5067            return false;
 5068        };
 5069
 5070        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5071        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5072        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5073        true
 5074    }
 5075
 5076    /// Returns true when we're displaying the inline completion popover below the cursor
 5077    /// like we are not previewing and the LSP autocomplete menu is visible
 5078    /// or we are in `when_holding_modifier` mode.
 5079    pub fn inline_completion_visible_in_cursor_popover(
 5080        &self,
 5081        has_completion: bool,
 5082        cx: &App,
 5083    ) -> bool {
 5084        if self.previewing_inline_completion
 5085            || !self.show_edit_predictions_in_menu(cx)
 5086            || !self.should_show_inline_completions(cx)
 5087        {
 5088            return false;
 5089        }
 5090
 5091        if self.has_visible_completions_menu() {
 5092            return true;
 5093        }
 5094
 5095        has_completion && self.edit_prediction_requires_modifier(cx)
 5096    }
 5097
 5098    fn handle_modifiers_changed(
 5099        &mut self,
 5100        modifiers: Modifiers,
 5101        position_map: &PositionMap,
 5102        window: &mut Window,
 5103        cx: &mut Context<Self>,
 5104    ) {
 5105        if self.show_edit_predictions_in_menu(cx) {
 5106            let accept_binding =
 5107                AcceptEditPredictionBinding::resolve(self.focus_handle(cx), window);
 5108            if let Some(accept_keystroke) = accept_binding.keystroke() {
 5109                let was_previewing_inline_completion = self.previewing_inline_completion;
 5110                self.previewing_inline_completion = modifiers == accept_keystroke.modifiers
 5111                    && accept_keystroke.modifiers.modified();
 5112                if self.previewing_inline_completion != was_previewing_inline_completion {
 5113                    self.update_visible_inline_completion(window, cx);
 5114                }
 5115            }
 5116        }
 5117
 5118        let mouse_position = window.mouse_position();
 5119        if !position_map.text_hitbox.is_hovered(window) {
 5120            return;
 5121        }
 5122
 5123        self.update_hovered_link(
 5124            position_map.point_for_position(mouse_position),
 5125            &position_map.snapshot,
 5126            modifiers,
 5127            window,
 5128            cx,
 5129        )
 5130    }
 5131
 5132    fn update_visible_inline_completion(
 5133        &mut self,
 5134        _window: &mut Window,
 5135        cx: &mut Context<Self>,
 5136    ) -> Option<()> {
 5137        let selection = self.selections.newest_anchor();
 5138        let cursor = selection.head();
 5139        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5140        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5141        let excerpt_id = cursor.excerpt_id;
 5142
 5143        let show_in_menu = self.show_edit_predictions_in_menu(cx);
 5144        let completions_menu_has_precedence = !show_in_menu
 5145            && (self.context_menu.borrow().is_some()
 5146                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5147        if completions_menu_has_precedence
 5148            || !offset_selection.is_empty()
 5149            || self
 5150                .active_inline_completion
 5151                .as_ref()
 5152                .map_or(false, |completion| {
 5153                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5154                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5155                    !invalidation_range.contains(&offset_selection.head())
 5156                })
 5157        {
 5158            self.discard_inline_completion(false, cx);
 5159            return None;
 5160        }
 5161
 5162        self.take_active_inline_completion(cx);
 5163        let provider = self.edit_prediction_provider()?;
 5164
 5165        let (buffer, cursor_buffer_position) =
 5166            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5167
 5168        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5169        let edits = inline_completion
 5170            .edits
 5171            .into_iter()
 5172            .flat_map(|(range, new_text)| {
 5173                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5174                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5175                Some((start..end, new_text))
 5176            })
 5177            .collect::<Vec<_>>();
 5178        if edits.is_empty() {
 5179            return None;
 5180        }
 5181
 5182        let first_edit_start = edits.first().unwrap().0.start;
 5183        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5184        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5185
 5186        let last_edit_end = edits.last().unwrap().0.end;
 5187        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5188        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5189
 5190        let cursor_row = cursor.to_point(&multibuffer).row;
 5191
 5192        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5193
 5194        let mut inlay_ids = Vec::new();
 5195        let invalidation_row_range;
 5196        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5197            Some(cursor_row..edit_end_row)
 5198        } else if cursor_row > edit_end_row {
 5199            Some(edit_start_row..cursor_row)
 5200        } else {
 5201            None
 5202        };
 5203        let is_move =
 5204            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5205        let completion = if is_move {
 5206            invalidation_row_range =
 5207                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5208            let target = first_edit_start;
 5209            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5210            // TODO: Base this off of TreeSitter or word boundaries?
 5211            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5212                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5213                Bias::Left,
 5214            ));
 5215            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5216                Point::new(target_point.row, target_point.column + 20),
 5217                Bias::Right,
 5218            ));
 5219            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5220            InlineCompletion::Move {
 5221                target,
 5222                range_around_target,
 5223                snapshot,
 5224            }
 5225        } else {
 5226            let show_completions_in_buffer = !self
 5227                .inline_completion_visible_in_cursor_popover(true, cx)
 5228                && !self.inline_completions_hidden_for_vim_mode;
 5229            if show_completions_in_buffer {
 5230                if edits
 5231                    .iter()
 5232                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5233                {
 5234                    let mut inlays = Vec::new();
 5235                    for (range, new_text) in &edits {
 5236                        let inlay = Inlay::inline_completion(
 5237                            post_inc(&mut self.next_inlay_id),
 5238                            range.start,
 5239                            new_text.as_str(),
 5240                        );
 5241                        inlay_ids.push(inlay.id);
 5242                        inlays.push(inlay);
 5243                    }
 5244
 5245                    self.splice_inlays(&[], inlays, cx);
 5246                } else {
 5247                    let background_color = cx.theme().status().deleted_background;
 5248                    self.highlight_text::<InlineCompletionHighlight>(
 5249                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5250                        HighlightStyle {
 5251                            background_color: Some(background_color),
 5252                            ..Default::default()
 5253                        },
 5254                        cx,
 5255                    );
 5256                }
 5257            }
 5258
 5259            invalidation_row_range = edit_start_row..edit_end_row;
 5260
 5261            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5262                if provider.show_tab_accept_marker() {
 5263                    EditDisplayMode::TabAccept
 5264                } else {
 5265                    EditDisplayMode::Inline
 5266                }
 5267            } else {
 5268                EditDisplayMode::DiffPopover
 5269            };
 5270
 5271            InlineCompletion::Edit {
 5272                edits,
 5273                edit_preview: inline_completion.edit_preview,
 5274                display_mode,
 5275                snapshot,
 5276            }
 5277        };
 5278
 5279        let invalidation_range = multibuffer
 5280            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5281            ..multibuffer.anchor_after(Point::new(
 5282                invalidation_row_range.end,
 5283                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5284            ));
 5285
 5286        self.stale_inline_completion_in_menu = None;
 5287        self.active_inline_completion = Some(InlineCompletionState {
 5288            inlay_ids,
 5289            completion,
 5290            completion_id: inline_completion.id,
 5291            invalidation_range,
 5292        });
 5293
 5294        cx.notify();
 5295
 5296        Some(())
 5297    }
 5298
 5299    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5300        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5301    }
 5302
 5303    fn show_edit_predictions_in_menu(&self, cx: &App) -> bool {
 5304        let by_provider = matches!(
 5305            self.menu_inline_completions_policy,
 5306            MenuInlineCompletionsPolicy::ByProvider
 5307        );
 5308
 5309        by_provider
 5310            && EditorSettings::get_global(cx).show_edit_predictions_in_menu
 5311            && self
 5312                .edit_prediction_provider()
 5313                .map_or(false, |provider| provider.show_completions_in_menu())
 5314    }
 5315
 5316    fn render_code_actions_indicator(
 5317        &self,
 5318        _style: &EditorStyle,
 5319        row: DisplayRow,
 5320        is_active: bool,
 5321        cx: &mut Context<Self>,
 5322    ) -> Option<IconButton> {
 5323        if self.available_code_actions.is_some() {
 5324            Some(
 5325                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5326                    .shape(ui::IconButtonShape::Square)
 5327                    .icon_size(IconSize::XSmall)
 5328                    .icon_color(Color::Muted)
 5329                    .toggle_state(is_active)
 5330                    .tooltip({
 5331                        let focus_handle = self.focus_handle.clone();
 5332                        move |window, cx| {
 5333                            Tooltip::for_action_in(
 5334                                "Toggle Code Actions",
 5335                                &ToggleCodeActions {
 5336                                    deployed_from_indicator: None,
 5337                                },
 5338                                &focus_handle,
 5339                                window,
 5340                                cx,
 5341                            )
 5342                        }
 5343                    })
 5344                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5345                        window.focus(&editor.focus_handle(cx));
 5346                        editor.toggle_code_actions(
 5347                            &ToggleCodeActions {
 5348                                deployed_from_indicator: Some(row),
 5349                            },
 5350                            window,
 5351                            cx,
 5352                        );
 5353                    })),
 5354            )
 5355        } else {
 5356            None
 5357        }
 5358    }
 5359
 5360    fn clear_tasks(&mut self) {
 5361        self.tasks.clear()
 5362    }
 5363
 5364    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5365        if self.tasks.insert(key, value).is_some() {
 5366            // This case should hopefully be rare, but just in case...
 5367            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5368        }
 5369    }
 5370
 5371    fn build_tasks_context(
 5372        project: &Entity<Project>,
 5373        buffer: &Entity<Buffer>,
 5374        buffer_row: u32,
 5375        tasks: &Arc<RunnableTasks>,
 5376        cx: &mut Context<Self>,
 5377    ) -> Task<Option<task::TaskContext>> {
 5378        let position = Point::new(buffer_row, tasks.column);
 5379        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5380        let location = Location {
 5381            buffer: buffer.clone(),
 5382            range: range_start..range_start,
 5383        };
 5384        // Fill in the environmental variables from the tree-sitter captures
 5385        let mut captured_task_variables = TaskVariables::default();
 5386        for (capture_name, value) in tasks.extra_variables.clone() {
 5387            captured_task_variables.insert(
 5388                task::VariableName::Custom(capture_name.into()),
 5389                value.clone(),
 5390            );
 5391        }
 5392        project.update(cx, |project, cx| {
 5393            project.task_store().update(cx, |task_store, cx| {
 5394                task_store.task_context_for_location(captured_task_variables, location, cx)
 5395            })
 5396        })
 5397    }
 5398
 5399    pub fn spawn_nearest_task(
 5400        &mut self,
 5401        action: &SpawnNearestTask,
 5402        window: &mut Window,
 5403        cx: &mut Context<Self>,
 5404    ) {
 5405        let Some((workspace, _)) = self.workspace.clone() else {
 5406            return;
 5407        };
 5408        let Some(project) = self.project.clone() else {
 5409            return;
 5410        };
 5411
 5412        // Try to find a closest, enclosing node using tree-sitter that has a
 5413        // task
 5414        let Some((buffer, buffer_row, tasks)) = self
 5415            .find_enclosing_node_task(cx)
 5416            // Or find the task that's closest in row-distance.
 5417            .or_else(|| self.find_closest_task(cx))
 5418        else {
 5419            return;
 5420        };
 5421
 5422        let reveal_strategy = action.reveal;
 5423        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5424        cx.spawn_in(window, |_, mut cx| async move {
 5425            let context = task_context.await?;
 5426            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5427
 5428            let resolved = resolved_task.resolved.as_mut()?;
 5429            resolved.reveal = reveal_strategy;
 5430
 5431            workspace
 5432                .update(&mut cx, |workspace, cx| {
 5433                    workspace::tasks::schedule_resolved_task(
 5434                        workspace,
 5435                        task_source_kind,
 5436                        resolved_task,
 5437                        false,
 5438                        cx,
 5439                    );
 5440                })
 5441                .ok()
 5442        })
 5443        .detach();
 5444    }
 5445
 5446    fn find_closest_task(
 5447        &mut self,
 5448        cx: &mut Context<Self>,
 5449    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5450        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5451
 5452        let ((buffer_id, row), tasks) = self
 5453            .tasks
 5454            .iter()
 5455            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5456
 5457        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5458        let tasks = Arc::new(tasks.to_owned());
 5459        Some((buffer, *row, tasks))
 5460    }
 5461
 5462    fn find_enclosing_node_task(
 5463        &mut self,
 5464        cx: &mut Context<Self>,
 5465    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5466        let snapshot = self.buffer.read(cx).snapshot(cx);
 5467        let offset = self.selections.newest::<usize>(cx).head();
 5468        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5469        let buffer_id = excerpt.buffer().remote_id();
 5470
 5471        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5472        let mut cursor = layer.node().walk();
 5473
 5474        while cursor.goto_first_child_for_byte(offset).is_some() {
 5475            if cursor.node().end_byte() == offset {
 5476                cursor.goto_next_sibling();
 5477            }
 5478        }
 5479
 5480        // Ascend to the smallest ancestor that contains the range and has a task.
 5481        loop {
 5482            let node = cursor.node();
 5483            let node_range = node.byte_range();
 5484            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5485
 5486            // Check if this node contains our offset
 5487            if node_range.start <= offset && node_range.end >= offset {
 5488                // If it contains offset, check for task
 5489                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5490                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5491                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5492                }
 5493            }
 5494
 5495            if !cursor.goto_parent() {
 5496                break;
 5497            }
 5498        }
 5499        None
 5500    }
 5501
 5502    fn render_run_indicator(
 5503        &self,
 5504        _style: &EditorStyle,
 5505        is_active: bool,
 5506        row: DisplayRow,
 5507        cx: &mut Context<Self>,
 5508    ) -> IconButton {
 5509        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5510            .shape(ui::IconButtonShape::Square)
 5511            .icon_size(IconSize::XSmall)
 5512            .icon_color(Color::Muted)
 5513            .toggle_state(is_active)
 5514            .on_click(cx.listener(move |editor, _e, window, cx| {
 5515                window.focus(&editor.focus_handle(cx));
 5516                editor.toggle_code_actions(
 5517                    &ToggleCodeActions {
 5518                        deployed_from_indicator: Some(row),
 5519                    },
 5520                    window,
 5521                    cx,
 5522                );
 5523            }))
 5524    }
 5525
 5526    pub fn context_menu_visible(&self) -> bool {
 5527        !self.previewing_inline_completion
 5528            && self
 5529                .context_menu
 5530                .borrow()
 5531                .as_ref()
 5532                .map_or(false, |menu| menu.visible())
 5533    }
 5534
 5535    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5536        self.context_menu
 5537            .borrow()
 5538            .as_ref()
 5539            .map(|menu| menu.origin())
 5540    }
 5541
 5542    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5543        px(30.)
 5544    }
 5545
 5546    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5547        if self.read_only(cx) {
 5548            cx.theme().players().read_only()
 5549        } else {
 5550            self.style.as_ref().unwrap().local_player
 5551        }
 5552    }
 5553
 5554    #[allow(clippy::too_many_arguments)]
 5555    fn render_edit_prediction_cursor_popover(
 5556        &self,
 5557        min_width: Pixels,
 5558        max_width: Pixels,
 5559        cursor_point: Point,
 5560        style: &EditorStyle,
 5561        accept_keystroke: &gpui::Keystroke,
 5562        window: &Window,
 5563        cx: &mut Context<Editor>,
 5564    ) -> Option<AnyElement> {
 5565        let provider = self.edit_prediction_provider.as_ref()?;
 5566
 5567        if provider.provider.needs_terms_acceptance(cx) {
 5568            return Some(
 5569                h_flex()
 5570                    .h(self.edit_prediction_cursor_popover_height())
 5571                    .min_w(min_width)
 5572                    .flex_1()
 5573                    .px_2()
 5574                    .gap_3()
 5575                    .elevation_2(cx)
 5576                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5577                    .id("accept-terms")
 5578                    .cursor_pointer()
 5579                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5580                    .on_click(cx.listener(|this, _event, window, cx| {
 5581                        cx.stop_propagation();
 5582                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5583                        window.dispatch_action(
 5584                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5585                            cx,
 5586                        );
 5587                    }))
 5588                    .child(
 5589                        h_flex()
 5590                            .flex_1()
 5591                            .gap_2()
 5592                            .child(Icon::new(IconName::ZedPredict))
 5593                            .child(Label::new("Accept Terms of Service"))
 5594                            .child(div().w_full())
 5595                            .child(
 5596                                Icon::new(IconName::ArrowUpRight)
 5597                                    .color(Color::Muted)
 5598                                    .size(IconSize::Small),
 5599                            )
 5600                            .into_any_element(),
 5601                    )
 5602                    .into_any(),
 5603            );
 5604        }
 5605
 5606        let is_refreshing = provider.provider.is_refreshing(cx);
 5607
 5608        fn pending_completion_container() -> Div {
 5609            h_flex()
 5610                .h_full()
 5611                .flex_1()
 5612                .gap_2()
 5613                .child(Icon::new(IconName::ZedPredict))
 5614        }
 5615
 5616        let completion = match &self.active_inline_completion {
 5617            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5618                completion,
 5619                cursor_point,
 5620                style,
 5621                window,
 5622                cx,
 5623            )?,
 5624
 5625            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5626                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5627                    stale_completion,
 5628                    cursor_point,
 5629                    style,
 5630                    window,
 5631                    cx,
 5632                )?,
 5633
 5634                None => {
 5635                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5636                }
 5637            },
 5638
 5639            None => pending_completion_container().child(Label::new("No Prediction")),
 5640        };
 5641
 5642        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5643        let completion = completion.font(buffer_font.clone());
 5644
 5645        let completion = if is_refreshing {
 5646            completion
 5647                .with_animation(
 5648                    "loading-completion",
 5649                    Animation::new(Duration::from_secs(2))
 5650                        .repeat()
 5651                        .with_easing(pulsating_between(0.4, 0.8)),
 5652                    |label, delta| label.opacity(delta),
 5653                )
 5654                .into_any_element()
 5655        } else {
 5656            completion.into_any_element()
 5657        };
 5658
 5659        let has_completion = self.active_inline_completion.is_some();
 5660
 5661        Some(
 5662            h_flex()
 5663                .h(self.edit_prediction_cursor_popover_height())
 5664                .min_w(min_width)
 5665                .max_w(max_width)
 5666                .flex_1()
 5667                .px_2()
 5668                .elevation_2(cx)
 5669                .child(completion)
 5670                .child(ui::Divider::vertical())
 5671                .child(
 5672                    h_flex()
 5673                        .h_full()
 5674                        .gap_1()
 5675                        .pl_2()
 5676                        .child(h_flex().font(buffer_font.clone()).gap_1().children(
 5677                            ui::render_modifiers(
 5678                                &accept_keystroke.modifiers,
 5679                                PlatformStyle::platform(),
 5680                                Some(if !has_completion {
 5681                                    Color::Muted
 5682                                } else {
 5683                                    Color::Default
 5684                                }),
 5685                                None,
 5686                                true,
 5687                            ),
 5688                        ))
 5689                        .child(Label::new("Preview").into_any_element())
 5690                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5691                )
 5692                .into_any(),
 5693        )
 5694    }
 5695
 5696    fn render_edit_prediction_cursor_popover_preview(
 5697        &self,
 5698        completion: &InlineCompletionState,
 5699        cursor_point: Point,
 5700        style: &EditorStyle,
 5701        window: &Window,
 5702        cx: &mut Context<Editor>,
 5703    ) -> Option<Div> {
 5704        use text::ToPoint as _;
 5705
 5706        fn render_relative_row_jump(
 5707            prefix: impl Into<String>,
 5708            current_row: u32,
 5709            target_row: u32,
 5710        ) -> Div {
 5711            let (row_diff, arrow) = if target_row < current_row {
 5712                (current_row - target_row, IconName::ArrowUp)
 5713            } else {
 5714                (target_row - current_row, IconName::ArrowDown)
 5715            };
 5716
 5717            h_flex()
 5718                .child(
 5719                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5720                        .color(Color::Muted)
 5721                        .size(LabelSize::Small),
 5722                )
 5723                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5724        }
 5725
 5726        match &completion.completion {
 5727            InlineCompletion::Edit {
 5728                edits,
 5729                edit_preview,
 5730                snapshot,
 5731                display_mode: _,
 5732            } => {
 5733                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5734
 5735                let highlighted_edits = crate::inline_completion_edit_text(
 5736                    &snapshot,
 5737                    &edits,
 5738                    edit_preview.as_ref()?,
 5739                    true,
 5740                    cx,
 5741                );
 5742
 5743                let len_total = highlighted_edits.text.len();
 5744                let first_line = &highlighted_edits.text
 5745                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5746                let first_line_len = first_line.len();
 5747
 5748                let first_highlight_start = highlighted_edits
 5749                    .highlights
 5750                    .first()
 5751                    .map_or(0, |(range, _)| range.start);
 5752                let drop_prefix_len = first_line
 5753                    .char_indices()
 5754                    .find(|(_, c)| !c.is_whitespace())
 5755                    .map_or(first_highlight_start, |(ix, _)| {
 5756                        ix.min(first_highlight_start)
 5757                    });
 5758
 5759                let preview_text = &first_line[drop_prefix_len..];
 5760                let preview_len = preview_text.len();
 5761                let highlights = highlighted_edits
 5762                    .highlights
 5763                    .into_iter()
 5764                    .take_until(|(range, _)| range.start > first_line_len)
 5765                    .map(|(range, style)| {
 5766                        (
 5767                            range.start - drop_prefix_len
 5768                                ..(range.end - drop_prefix_len).min(preview_len),
 5769                            style,
 5770                        )
 5771                    });
 5772
 5773                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5774                    .with_highlights(&style.text, highlights);
 5775
 5776                let preview = h_flex()
 5777                    .gap_1()
 5778                    .min_w_16()
 5779                    .child(styled_text)
 5780                    .when(len_total > first_line_len, |parent| parent.child(""));
 5781
 5782                let left = if first_edit_row != cursor_point.row {
 5783                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5784                        .into_any_element()
 5785                } else {
 5786                    Icon::new(IconName::ZedPredict).into_any_element()
 5787                };
 5788
 5789                Some(
 5790                    h_flex()
 5791                        .h_full()
 5792                        .flex_1()
 5793                        .gap_2()
 5794                        .pr_1()
 5795                        .overflow_x_hidden()
 5796                        .child(left)
 5797                        .child(preview),
 5798                )
 5799            }
 5800
 5801            InlineCompletion::Move {
 5802                target,
 5803                range_around_target,
 5804                snapshot,
 5805            } => {
 5806                let highlighted_text = snapshot.highlighted_text_for_range(
 5807                    range_around_target.clone(),
 5808                    None,
 5809                    &style.syntax,
 5810                );
 5811                let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
 5812                    "Jump ",
 5813                    cursor_point.row,
 5814                    target.text_anchor.to_point(&snapshot).row,
 5815                ));
 5816
 5817                if highlighted_text.text.is_empty() {
 5818                    return Some(base);
 5819                }
 5820
 5821                let cursor_color = self.current_user_player_color(cx).cursor;
 5822
 5823                let start_point = range_around_target.start.to_point(&snapshot);
 5824                let end_point = range_around_target.end.to_point(&snapshot);
 5825                let target_point = target.text_anchor.to_point(&snapshot);
 5826
 5827                let styled_text = highlighted_text.to_styled_text(&style.text);
 5828                let text_len = highlighted_text.text.len();
 5829
 5830                let cursor_relative_position = window
 5831                    .text_system()
 5832                    .layout_line(
 5833                        highlighted_text.text,
 5834                        style.text.font_size.to_pixels(window.rem_size()),
 5835                        // We don't need to include highlights
 5836                        // because we are only using this for the cursor position
 5837                        &[TextRun {
 5838                            len: text_len,
 5839                            font: style.text.font(),
 5840                            color: style.text.color,
 5841                            background_color: None,
 5842                            underline: None,
 5843                            strikethrough: None,
 5844                        }],
 5845                    )
 5846                    .log_err()
 5847                    .map(|line| {
 5848                        line.x_for_index(
 5849                            target_point.column.saturating_sub(start_point.column) as usize
 5850                        )
 5851                    });
 5852
 5853                let fade_before = start_point.column > 0;
 5854                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5855
 5856                let background = cx.theme().colors().elevated_surface_background;
 5857
 5858                let preview = h_flex()
 5859                    .relative()
 5860                    .child(styled_text)
 5861                    .when(fade_before, |parent| {
 5862                        parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
 5863                            linear_gradient(
 5864                                90.,
 5865                                linear_color_stop(background, 0.),
 5866                                linear_color_stop(background.opacity(0.), 1.),
 5867                            ),
 5868                        ))
 5869                    })
 5870                    .when(fade_after, |parent| {
 5871                        parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
 5872                            linear_gradient(
 5873                                -90.,
 5874                                linear_color_stop(background, 0.),
 5875                                linear_color_stop(background.opacity(0.), 1.),
 5876                            ),
 5877                        ))
 5878                    })
 5879                    .when_some(cursor_relative_position, |parent, position| {
 5880                        parent.child(
 5881                            div()
 5882                                .w(px(2.))
 5883                                .h_full()
 5884                                .bg(cursor_color)
 5885                                .absolute()
 5886                                .top_0()
 5887                                .left(position),
 5888                        )
 5889                    });
 5890
 5891                Some(base.child(preview))
 5892            }
 5893        }
 5894    }
 5895
 5896    fn render_context_menu(
 5897        &self,
 5898        style: &EditorStyle,
 5899        max_height_in_lines: u32,
 5900        y_flipped: bool,
 5901        window: &mut Window,
 5902        cx: &mut Context<Editor>,
 5903    ) -> Option<AnyElement> {
 5904        let menu = self.context_menu.borrow();
 5905        let menu = menu.as_ref()?;
 5906        if !menu.visible() {
 5907            return None;
 5908        };
 5909        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5910    }
 5911
 5912    fn render_context_menu_aside(
 5913        &self,
 5914        style: &EditorStyle,
 5915        max_size: Size<Pixels>,
 5916        cx: &mut Context<Editor>,
 5917    ) -> Option<AnyElement> {
 5918        self.context_menu.borrow().as_ref().and_then(|menu| {
 5919            if menu.visible() {
 5920                menu.render_aside(
 5921                    style,
 5922                    max_size,
 5923                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5924                    cx,
 5925                )
 5926            } else {
 5927                None
 5928            }
 5929        })
 5930    }
 5931
 5932    fn hide_context_menu(
 5933        &mut self,
 5934        window: &mut Window,
 5935        cx: &mut Context<Self>,
 5936    ) -> Option<CodeContextMenu> {
 5937        cx.notify();
 5938        self.completion_tasks.clear();
 5939        let context_menu = self.context_menu.borrow_mut().take();
 5940        self.stale_inline_completion_in_menu.take();
 5941        self.update_visible_inline_completion(window, cx);
 5942        context_menu
 5943    }
 5944
 5945    fn show_snippet_choices(
 5946        &mut self,
 5947        choices: &Vec<String>,
 5948        selection: Range<Anchor>,
 5949        cx: &mut Context<Self>,
 5950    ) {
 5951        if selection.start.buffer_id.is_none() {
 5952            return;
 5953        }
 5954        let buffer_id = selection.start.buffer_id.unwrap();
 5955        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5956        let id = post_inc(&mut self.next_completion_id);
 5957
 5958        if let Some(buffer) = buffer {
 5959            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5960                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5961            ));
 5962        }
 5963    }
 5964
 5965    pub fn insert_snippet(
 5966        &mut self,
 5967        insertion_ranges: &[Range<usize>],
 5968        snippet: Snippet,
 5969        window: &mut Window,
 5970        cx: &mut Context<Self>,
 5971    ) -> Result<()> {
 5972        struct Tabstop<T> {
 5973            is_end_tabstop: bool,
 5974            ranges: Vec<Range<T>>,
 5975            choices: Option<Vec<String>>,
 5976        }
 5977
 5978        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5979            let snippet_text: Arc<str> = snippet.text.clone().into();
 5980            buffer.edit(
 5981                insertion_ranges
 5982                    .iter()
 5983                    .cloned()
 5984                    .map(|range| (range, snippet_text.clone())),
 5985                Some(AutoindentMode::EachLine),
 5986                cx,
 5987            );
 5988
 5989            let snapshot = &*buffer.read(cx);
 5990            let snippet = &snippet;
 5991            snippet
 5992                .tabstops
 5993                .iter()
 5994                .map(|tabstop| {
 5995                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5996                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5997                    });
 5998                    let mut tabstop_ranges = tabstop
 5999                        .ranges
 6000                        .iter()
 6001                        .flat_map(|tabstop_range| {
 6002                            let mut delta = 0_isize;
 6003                            insertion_ranges.iter().map(move |insertion_range| {
 6004                                let insertion_start = insertion_range.start as isize + delta;
 6005                                delta +=
 6006                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6007
 6008                                let start = ((insertion_start + tabstop_range.start) as usize)
 6009                                    .min(snapshot.len());
 6010                                let end = ((insertion_start + tabstop_range.end) as usize)
 6011                                    .min(snapshot.len());
 6012                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6013                            })
 6014                        })
 6015                        .collect::<Vec<_>>();
 6016                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6017
 6018                    Tabstop {
 6019                        is_end_tabstop,
 6020                        ranges: tabstop_ranges,
 6021                        choices: tabstop.choices.clone(),
 6022                    }
 6023                })
 6024                .collect::<Vec<_>>()
 6025        });
 6026        if let Some(tabstop) = tabstops.first() {
 6027            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6028                s.select_ranges(tabstop.ranges.iter().cloned());
 6029            });
 6030
 6031            if let Some(choices) = &tabstop.choices {
 6032                if let Some(selection) = tabstop.ranges.first() {
 6033                    self.show_snippet_choices(choices, selection.clone(), cx)
 6034                }
 6035            }
 6036
 6037            // If we're already at the last tabstop and it's at the end of the snippet,
 6038            // we're done, we don't need to keep the state around.
 6039            if !tabstop.is_end_tabstop {
 6040                let choices = tabstops
 6041                    .iter()
 6042                    .map(|tabstop| tabstop.choices.clone())
 6043                    .collect();
 6044
 6045                let ranges = tabstops
 6046                    .into_iter()
 6047                    .map(|tabstop| tabstop.ranges)
 6048                    .collect::<Vec<_>>();
 6049
 6050                self.snippet_stack.push(SnippetState {
 6051                    active_index: 0,
 6052                    ranges,
 6053                    choices,
 6054                });
 6055            }
 6056
 6057            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6058            if self.autoclose_regions.is_empty() {
 6059                let snapshot = self.buffer.read(cx).snapshot(cx);
 6060                for selection in &mut self.selections.all::<Point>(cx) {
 6061                    let selection_head = selection.head();
 6062                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6063                        continue;
 6064                    };
 6065
 6066                    let mut bracket_pair = None;
 6067                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6068                    let prev_chars = snapshot
 6069                        .reversed_chars_at(selection_head)
 6070                        .collect::<String>();
 6071                    for (pair, enabled) in scope.brackets() {
 6072                        if enabled
 6073                            && pair.close
 6074                            && prev_chars.starts_with(pair.start.as_str())
 6075                            && next_chars.starts_with(pair.end.as_str())
 6076                        {
 6077                            bracket_pair = Some(pair.clone());
 6078                            break;
 6079                        }
 6080                    }
 6081                    if let Some(pair) = bracket_pair {
 6082                        let start = snapshot.anchor_after(selection_head);
 6083                        let end = snapshot.anchor_after(selection_head);
 6084                        self.autoclose_regions.push(AutocloseRegion {
 6085                            selection_id: selection.id,
 6086                            range: start..end,
 6087                            pair,
 6088                        });
 6089                    }
 6090                }
 6091            }
 6092        }
 6093        Ok(())
 6094    }
 6095
 6096    pub fn move_to_next_snippet_tabstop(
 6097        &mut self,
 6098        window: &mut Window,
 6099        cx: &mut Context<Self>,
 6100    ) -> bool {
 6101        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6102    }
 6103
 6104    pub fn move_to_prev_snippet_tabstop(
 6105        &mut self,
 6106        window: &mut Window,
 6107        cx: &mut Context<Self>,
 6108    ) -> bool {
 6109        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6110    }
 6111
 6112    pub fn move_to_snippet_tabstop(
 6113        &mut self,
 6114        bias: Bias,
 6115        window: &mut Window,
 6116        cx: &mut Context<Self>,
 6117    ) -> bool {
 6118        if let Some(mut snippet) = self.snippet_stack.pop() {
 6119            match bias {
 6120                Bias::Left => {
 6121                    if snippet.active_index > 0 {
 6122                        snippet.active_index -= 1;
 6123                    } else {
 6124                        self.snippet_stack.push(snippet);
 6125                        return false;
 6126                    }
 6127                }
 6128                Bias::Right => {
 6129                    if snippet.active_index + 1 < snippet.ranges.len() {
 6130                        snippet.active_index += 1;
 6131                    } else {
 6132                        self.snippet_stack.push(snippet);
 6133                        return false;
 6134                    }
 6135                }
 6136            }
 6137            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6138                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6139                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6140                });
 6141
 6142                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6143                    if let Some(selection) = current_ranges.first() {
 6144                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6145                    }
 6146                }
 6147
 6148                // If snippet state is not at the last tabstop, push it back on the stack
 6149                if snippet.active_index + 1 < snippet.ranges.len() {
 6150                    self.snippet_stack.push(snippet);
 6151                }
 6152                return true;
 6153            }
 6154        }
 6155
 6156        false
 6157    }
 6158
 6159    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6160        self.transact(window, cx, |this, window, cx| {
 6161            this.select_all(&SelectAll, window, cx);
 6162            this.insert("", window, cx);
 6163        });
 6164    }
 6165
 6166    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6167        self.transact(window, cx, |this, window, cx| {
 6168            this.select_autoclose_pair(window, cx);
 6169            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6170            if !this.linked_edit_ranges.is_empty() {
 6171                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6172                let snapshot = this.buffer.read(cx).snapshot(cx);
 6173
 6174                for selection in selections.iter() {
 6175                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6176                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6177                    if selection_start.buffer_id != selection_end.buffer_id {
 6178                        continue;
 6179                    }
 6180                    if let Some(ranges) =
 6181                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6182                    {
 6183                        for (buffer, entries) in ranges {
 6184                            linked_ranges.entry(buffer).or_default().extend(entries);
 6185                        }
 6186                    }
 6187                }
 6188            }
 6189
 6190            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6191            if !this.selections.line_mode {
 6192                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6193                for selection in &mut selections {
 6194                    if selection.is_empty() {
 6195                        let old_head = selection.head();
 6196                        let mut new_head =
 6197                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6198                                .to_point(&display_map);
 6199                        if let Some((buffer, line_buffer_range)) = display_map
 6200                            .buffer_snapshot
 6201                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6202                        {
 6203                            let indent_size =
 6204                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6205                            let indent_len = match indent_size.kind {
 6206                                IndentKind::Space => {
 6207                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6208                                }
 6209                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6210                            };
 6211                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6212                                let indent_len = indent_len.get();
 6213                                new_head = cmp::min(
 6214                                    new_head,
 6215                                    MultiBufferPoint::new(
 6216                                        old_head.row,
 6217                                        ((old_head.column - 1) / indent_len) * indent_len,
 6218                                    ),
 6219                                );
 6220                            }
 6221                        }
 6222
 6223                        selection.set_head(new_head, SelectionGoal::None);
 6224                    }
 6225                }
 6226            }
 6227
 6228            this.signature_help_state.set_backspace_pressed(true);
 6229            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6230                s.select(selections)
 6231            });
 6232            this.insert("", window, cx);
 6233            let empty_str: Arc<str> = Arc::from("");
 6234            for (buffer, edits) in linked_ranges {
 6235                let snapshot = buffer.read(cx).snapshot();
 6236                use text::ToPoint as TP;
 6237
 6238                let edits = edits
 6239                    .into_iter()
 6240                    .map(|range| {
 6241                        let end_point = TP::to_point(&range.end, &snapshot);
 6242                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6243
 6244                        if end_point == start_point {
 6245                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6246                                .saturating_sub(1);
 6247                            start_point =
 6248                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6249                        };
 6250
 6251                        (start_point..end_point, empty_str.clone())
 6252                    })
 6253                    .sorted_by_key(|(range, _)| range.start)
 6254                    .collect::<Vec<_>>();
 6255                buffer.update(cx, |this, cx| {
 6256                    this.edit(edits, None, cx);
 6257                })
 6258            }
 6259            this.refresh_inline_completion(true, false, window, cx);
 6260            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6261        });
 6262    }
 6263
 6264    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6265        self.transact(window, cx, |this, window, cx| {
 6266            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6267                let line_mode = s.line_mode;
 6268                s.move_with(|map, selection| {
 6269                    if selection.is_empty() && !line_mode {
 6270                        let cursor = movement::right(map, selection.head());
 6271                        selection.end = cursor;
 6272                        selection.reversed = true;
 6273                        selection.goal = SelectionGoal::None;
 6274                    }
 6275                })
 6276            });
 6277            this.insert("", window, cx);
 6278            this.refresh_inline_completion(true, false, window, cx);
 6279        });
 6280    }
 6281
 6282    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6283        if self.move_to_prev_snippet_tabstop(window, cx) {
 6284            return;
 6285        }
 6286
 6287        self.outdent(&Outdent, window, cx);
 6288    }
 6289
 6290    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6291        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6292            return;
 6293        }
 6294
 6295        let mut selections = self.selections.all_adjusted(cx);
 6296        let buffer = self.buffer.read(cx);
 6297        let snapshot = buffer.snapshot(cx);
 6298        let rows_iter = selections.iter().map(|s| s.head().row);
 6299        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6300
 6301        let mut edits = Vec::new();
 6302        let mut prev_edited_row = 0;
 6303        let mut row_delta = 0;
 6304        for selection in &mut selections {
 6305            if selection.start.row != prev_edited_row {
 6306                row_delta = 0;
 6307            }
 6308            prev_edited_row = selection.end.row;
 6309
 6310            // If the selection is non-empty, then increase the indentation of the selected lines.
 6311            if !selection.is_empty() {
 6312                row_delta =
 6313                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6314                continue;
 6315            }
 6316
 6317            // If the selection is empty and the cursor is in the leading whitespace before the
 6318            // suggested indentation, then auto-indent the line.
 6319            let cursor = selection.head();
 6320            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6321            if let Some(suggested_indent) =
 6322                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6323            {
 6324                if cursor.column < suggested_indent.len
 6325                    && cursor.column <= current_indent.len
 6326                    && current_indent.len <= suggested_indent.len
 6327                {
 6328                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6329                    selection.end = selection.start;
 6330                    if row_delta == 0 {
 6331                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6332                            cursor.row,
 6333                            current_indent,
 6334                            suggested_indent,
 6335                        ));
 6336                        row_delta = suggested_indent.len - current_indent.len;
 6337                    }
 6338                    continue;
 6339                }
 6340            }
 6341
 6342            // Otherwise, insert a hard or soft tab.
 6343            let settings = buffer.settings_at(cursor, cx);
 6344            let tab_size = if settings.hard_tabs {
 6345                IndentSize::tab()
 6346            } else {
 6347                let tab_size = settings.tab_size.get();
 6348                let char_column = snapshot
 6349                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6350                    .flat_map(str::chars)
 6351                    .count()
 6352                    + row_delta as usize;
 6353                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6354                IndentSize::spaces(chars_to_next_tab_stop)
 6355            };
 6356            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6357            selection.end = selection.start;
 6358            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6359            row_delta += tab_size.len;
 6360        }
 6361
 6362        self.transact(window, cx, |this, window, cx| {
 6363            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6364            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6365                s.select(selections)
 6366            });
 6367            this.refresh_inline_completion(true, false, window, cx);
 6368        });
 6369    }
 6370
 6371    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6372        if self.read_only(cx) {
 6373            return;
 6374        }
 6375        let mut selections = self.selections.all::<Point>(cx);
 6376        let mut prev_edited_row = 0;
 6377        let mut row_delta = 0;
 6378        let mut edits = Vec::new();
 6379        let buffer = self.buffer.read(cx);
 6380        let snapshot = buffer.snapshot(cx);
 6381        for selection in &mut selections {
 6382            if selection.start.row != prev_edited_row {
 6383                row_delta = 0;
 6384            }
 6385            prev_edited_row = selection.end.row;
 6386
 6387            row_delta =
 6388                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6389        }
 6390
 6391        self.transact(window, cx, |this, window, cx| {
 6392            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6393            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6394                s.select(selections)
 6395            });
 6396        });
 6397    }
 6398
 6399    fn indent_selection(
 6400        buffer: &MultiBuffer,
 6401        snapshot: &MultiBufferSnapshot,
 6402        selection: &mut Selection<Point>,
 6403        edits: &mut Vec<(Range<Point>, String)>,
 6404        delta_for_start_row: u32,
 6405        cx: &App,
 6406    ) -> u32 {
 6407        let settings = buffer.settings_at(selection.start, cx);
 6408        let tab_size = settings.tab_size.get();
 6409        let indent_kind = if settings.hard_tabs {
 6410            IndentKind::Tab
 6411        } else {
 6412            IndentKind::Space
 6413        };
 6414        let mut start_row = selection.start.row;
 6415        let mut end_row = selection.end.row + 1;
 6416
 6417        // If a selection ends at the beginning of a line, don't indent
 6418        // that last line.
 6419        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6420            end_row -= 1;
 6421        }
 6422
 6423        // Avoid re-indenting a row that has already been indented by a
 6424        // previous selection, but still update this selection's column
 6425        // to reflect that indentation.
 6426        if delta_for_start_row > 0 {
 6427            start_row += 1;
 6428            selection.start.column += delta_for_start_row;
 6429            if selection.end.row == selection.start.row {
 6430                selection.end.column += delta_for_start_row;
 6431            }
 6432        }
 6433
 6434        let mut delta_for_end_row = 0;
 6435        let has_multiple_rows = start_row + 1 != end_row;
 6436        for row in start_row..end_row {
 6437            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6438            let indent_delta = match (current_indent.kind, indent_kind) {
 6439                (IndentKind::Space, IndentKind::Space) => {
 6440                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6441                    IndentSize::spaces(columns_to_next_tab_stop)
 6442                }
 6443                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6444                (_, IndentKind::Tab) => IndentSize::tab(),
 6445            };
 6446
 6447            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6448                0
 6449            } else {
 6450                selection.start.column
 6451            };
 6452            let row_start = Point::new(row, start);
 6453            edits.push((
 6454                row_start..row_start,
 6455                indent_delta.chars().collect::<String>(),
 6456            ));
 6457
 6458            // Update this selection's endpoints to reflect the indentation.
 6459            if row == selection.start.row {
 6460                selection.start.column += indent_delta.len;
 6461            }
 6462            if row == selection.end.row {
 6463                selection.end.column += indent_delta.len;
 6464                delta_for_end_row = indent_delta.len;
 6465            }
 6466        }
 6467
 6468        if selection.start.row == selection.end.row {
 6469            delta_for_start_row + delta_for_end_row
 6470        } else {
 6471            delta_for_end_row
 6472        }
 6473    }
 6474
 6475    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6476        if self.read_only(cx) {
 6477            return;
 6478        }
 6479        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6480        let selections = self.selections.all::<Point>(cx);
 6481        let mut deletion_ranges = Vec::new();
 6482        let mut last_outdent = None;
 6483        {
 6484            let buffer = self.buffer.read(cx);
 6485            let snapshot = buffer.snapshot(cx);
 6486            for selection in &selections {
 6487                let settings = buffer.settings_at(selection.start, cx);
 6488                let tab_size = settings.tab_size.get();
 6489                let mut rows = selection.spanned_rows(false, &display_map);
 6490
 6491                // Avoid re-outdenting a row that has already been outdented by a
 6492                // previous selection.
 6493                if let Some(last_row) = last_outdent {
 6494                    if last_row == rows.start {
 6495                        rows.start = rows.start.next_row();
 6496                    }
 6497                }
 6498                let has_multiple_rows = rows.len() > 1;
 6499                for row in rows.iter_rows() {
 6500                    let indent_size = snapshot.indent_size_for_line(row);
 6501                    if indent_size.len > 0 {
 6502                        let deletion_len = match indent_size.kind {
 6503                            IndentKind::Space => {
 6504                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6505                                if columns_to_prev_tab_stop == 0 {
 6506                                    tab_size
 6507                                } else {
 6508                                    columns_to_prev_tab_stop
 6509                                }
 6510                            }
 6511                            IndentKind::Tab => 1,
 6512                        };
 6513                        let start = if has_multiple_rows
 6514                            || deletion_len > selection.start.column
 6515                            || indent_size.len < selection.start.column
 6516                        {
 6517                            0
 6518                        } else {
 6519                            selection.start.column - deletion_len
 6520                        };
 6521                        deletion_ranges.push(
 6522                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6523                        );
 6524                        last_outdent = Some(row);
 6525                    }
 6526                }
 6527            }
 6528        }
 6529
 6530        self.transact(window, cx, |this, window, cx| {
 6531            this.buffer.update(cx, |buffer, cx| {
 6532                let empty_str: Arc<str> = Arc::default();
 6533                buffer.edit(
 6534                    deletion_ranges
 6535                        .into_iter()
 6536                        .map(|range| (range, empty_str.clone())),
 6537                    None,
 6538                    cx,
 6539                );
 6540            });
 6541            let selections = this.selections.all::<usize>(cx);
 6542            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6543                s.select(selections)
 6544            });
 6545        });
 6546    }
 6547
 6548    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6549        if self.read_only(cx) {
 6550            return;
 6551        }
 6552        let selections = self
 6553            .selections
 6554            .all::<usize>(cx)
 6555            .into_iter()
 6556            .map(|s| s.range());
 6557
 6558        self.transact(window, cx, |this, window, cx| {
 6559            this.buffer.update(cx, |buffer, cx| {
 6560                buffer.autoindent_ranges(selections, cx);
 6561            });
 6562            let selections = this.selections.all::<usize>(cx);
 6563            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6564                s.select(selections)
 6565            });
 6566        });
 6567    }
 6568
 6569    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6570        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6571        let selections = self.selections.all::<Point>(cx);
 6572
 6573        let mut new_cursors = Vec::new();
 6574        let mut edit_ranges = Vec::new();
 6575        let mut selections = selections.iter().peekable();
 6576        while let Some(selection) = selections.next() {
 6577            let mut rows = selection.spanned_rows(false, &display_map);
 6578            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6579
 6580            // Accumulate contiguous regions of rows that we want to delete.
 6581            while let Some(next_selection) = selections.peek() {
 6582                let next_rows = next_selection.spanned_rows(false, &display_map);
 6583                if next_rows.start <= rows.end {
 6584                    rows.end = next_rows.end;
 6585                    selections.next().unwrap();
 6586                } else {
 6587                    break;
 6588                }
 6589            }
 6590
 6591            let buffer = &display_map.buffer_snapshot;
 6592            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6593            let edit_end;
 6594            let cursor_buffer_row;
 6595            if buffer.max_point().row >= rows.end.0 {
 6596                // If there's a line after the range, delete the \n from the end of the row range
 6597                // and position the cursor on the next line.
 6598                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6599                cursor_buffer_row = rows.end;
 6600            } else {
 6601                // If there isn't a line after the range, delete the \n from the line before the
 6602                // start of the row range and position the cursor there.
 6603                edit_start = edit_start.saturating_sub(1);
 6604                edit_end = buffer.len();
 6605                cursor_buffer_row = rows.start.previous_row();
 6606            }
 6607
 6608            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6609            *cursor.column_mut() =
 6610                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6611
 6612            new_cursors.push((
 6613                selection.id,
 6614                buffer.anchor_after(cursor.to_point(&display_map)),
 6615            ));
 6616            edit_ranges.push(edit_start..edit_end);
 6617        }
 6618
 6619        self.transact(window, cx, |this, window, cx| {
 6620            let buffer = this.buffer.update(cx, |buffer, cx| {
 6621                let empty_str: Arc<str> = Arc::default();
 6622                buffer.edit(
 6623                    edit_ranges
 6624                        .into_iter()
 6625                        .map(|range| (range, empty_str.clone())),
 6626                    None,
 6627                    cx,
 6628                );
 6629                buffer.snapshot(cx)
 6630            });
 6631            let new_selections = new_cursors
 6632                .into_iter()
 6633                .map(|(id, cursor)| {
 6634                    let cursor = cursor.to_point(&buffer);
 6635                    Selection {
 6636                        id,
 6637                        start: cursor,
 6638                        end: cursor,
 6639                        reversed: false,
 6640                        goal: SelectionGoal::None,
 6641                    }
 6642                })
 6643                .collect();
 6644
 6645            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6646                s.select(new_selections);
 6647            });
 6648        });
 6649    }
 6650
 6651    pub fn join_lines_impl(
 6652        &mut self,
 6653        insert_whitespace: bool,
 6654        window: &mut Window,
 6655        cx: &mut Context<Self>,
 6656    ) {
 6657        if self.read_only(cx) {
 6658            return;
 6659        }
 6660        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6661        for selection in self.selections.all::<Point>(cx) {
 6662            let start = MultiBufferRow(selection.start.row);
 6663            // Treat single line selections as if they include the next line. Otherwise this action
 6664            // would do nothing for single line selections individual cursors.
 6665            let end = if selection.start.row == selection.end.row {
 6666                MultiBufferRow(selection.start.row + 1)
 6667            } else {
 6668                MultiBufferRow(selection.end.row)
 6669            };
 6670
 6671            if let Some(last_row_range) = row_ranges.last_mut() {
 6672                if start <= last_row_range.end {
 6673                    last_row_range.end = end;
 6674                    continue;
 6675                }
 6676            }
 6677            row_ranges.push(start..end);
 6678        }
 6679
 6680        let snapshot = self.buffer.read(cx).snapshot(cx);
 6681        let mut cursor_positions = Vec::new();
 6682        for row_range in &row_ranges {
 6683            let anchor = snapshot.anchor_before(Point::new(
 6684                row_range.end.previous_row().0,
 6685                snapshot.line_len(row_range.end.previous_row()),
 6686            ));
 6687            cursor_positions.push(anchor..anchor);
 6688        }
 6689
 6690        self.transact(window, cx, |this, window, cx| {
 6691            for row_range in row_ranges.into_iter().rev() {
 6692                for row in row_range.iter_rows().rev() {
 6693                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6694                    let next_line_row = row.next_row();
 6695                    let indent = snapshot.indent_size_for_line(next_line_row);
 6696                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6697
 6698                    let replace =
 6699                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6700                            " "
 6701                        } else {
 6702                            ""
 6703                        };
 6704
 6705                    this.buffer.update(cx, |buffer, cx| {
 6706                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6707                    });
 6708                }
 6709            }
 6710
 6711            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6712                s.select_anchor_ranges(cursor_positions)
 6713            });
 6714        });
 6715    }
 6716
 6717    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6718        self.join_lines_impl(true, window, cx);
 6719    }
 6720
 6721    pub fn sort_lines_case_sensitive(
 6722        &mut self,
 6723        _: &SortLinesCaseSensitive,
 6724        window: &mut Window,
 6725        cx: &mut Context<Self>,
 6726    ) {
 6727        self.manipulate_lines(window, cx, |lines| lines.sort())
 6728    }
 6729
 6730    pub fn sort_lines_case_insensitive(
 6731        &mut self,
 6732        _: &SortLinesCaseInsensitive,
 6733        window: &mut Window,
 6734        cx: &mut Context<Self>,
 6735    ) {
 6736        self.manipulate_lines(window, cx, |lines| {
 6737            lines.sort_by_key(|line| line.to_lowercase())
 6738        })
 6739    }
 6740
 6741    pub fn unique_lines_case_insensitive(
 6742        &mut self,
 6743        _: &UniqueLinesCaseInsensitive,
 6744        window: &mut Window,
 6745        cx: &mut Context<Self>,
 6746    ) {
 6747        self.manipulate_lines(window, cx, |lines| {
 6748            let mut seen = HashSet::default();
 6749            lines.retain(|line| seen.insert(line.to_lowercase()));
 6750        })
 6751    }
 6752
 6753    pub fn unique_lines_case_sensitive(
 6754        &mut self,
 6755        _: &UniqueLinesCaseSensitive,
 6756        window: &mut Window,
 6757        cx: &mut Context<Self>,
 6758    ) {
 6759        self.manipulate_lines(window, cx, |lines| {
 6760            let mut seen = HashSet::default();
 6761            lines.retain(|line| seen.insert(*line));
 6762        })
 6763    }
 6764
 6765    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6766        let mut revert_changes = HashMap::default();
 6767        let snapshot = self.snapshot(window, cx);
 6768        for hunk in snapshot
 6769            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6770        {
 6771            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6772        }
 6773        if !revert_changes.is_empty() {
 6774            self.transact(window, cx, |editor, window, cx| {
 6775                editor.revert(revert_changes, window, cx);
 6776            });
 6777        }
 6778    }
 6779
 6780    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6781        let Some(project) = self.project.clone() else {
 6782            return;
 6783        };
 6784        self.reload(project, window, cx)
 6785            .detach_and_notify_err(window, cx);
 6786    }
 6787
 6788    pub fn revert_selected_hunks(
 6789        &mut self,
 6790        _: &RevertSelectedHunks,
 6791        window: &mut Window,
 6792        cx: &mut Context<Self>,
 6793    ) {
 6794        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6795        self.revert_hunks_in_ranges(selections, window, cx);
 6796    }
 6797
 6798    fn revert_hunks_in_ranges(
 6799        &mut self,
 6800        ranges: impl Iterator<Item = Range<Point>>,
 6801        window: &mut Window,
 6802        cx: &mut Context<Editor>,
 6803    ) {
 6804        let mut revert_changes = HashMap::default();
 6805        let snapshot = self.snapshot(window, cx);
 6806        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6807            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6808        }
 6809        if !revert_changes.is_empty() {
 6810            self.transact(window, cx, |editor, window, cx| {
 6811                editor.revert(revert_changes, window, cx);
 6812            });
 6813        }
 6814    }
 6815
 6816    pub fn open_active_item_in_terminal(
 6817        &mut self,
 6818        _: &OpenInTerminal,
 6819        window: &mut Window,
 6820        cx: &mut Context<Self>,
 6821    ) {
 6822        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6823            let project_path = buffer.read(cx).project_path(cx)?;
 6824            let project = self.project.as_ref()?.read(cx);
 6825            let entry = project.entry_for_path(&project_path, cx)?;
 6826            let parent = match &entry.canonical_path {
 6827                Some(canonical_path) => canonical_path.to_path_buf(),
 6828                None => project.absolute_path(&project_path, cx)?,
 6829            }
 6830            .parent()?
 6831            .to_path_buf();
 6832            Some(parent)
 6833        }) {
 6834            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6835        }
 6836    }
 6837
 6838    pub fn prepare_revert_change(
 6839        &self,
 6840        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6841        hunk: &MultiBufferDiffHunk,
 6842        cx: &mut App,
 6843    ) -> Option<()> {
 6844        let buffer = self.buffer.read(cx);
 6845        let diff = buffer.diff_for(hunk.buffer_id)?;
 6846        let buffer = buffer.buffer(hunk.buffer_id)?;
 6847        let buffer = buffer.read(cx);
 6848        let original_text = diff
 6849            .read(cx)
 6850            .snapshot
 6851            .base_text
 6852            .as_ref()?
 6853            .as_rope()
 6854            .slice(hunk.diff_base_byte_range.clone());
 6855        let buffer_snapshot = buffer.snapshot();
 6856        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6857        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6858            probe
 6859                .0
 6860                .start
 6861                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6862                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6863        }) {
 6864            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6865            Some(())
 6866        } else {
 6867            None
 6868        }
 6869    }
 6870
 6871    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6872        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6873    }
 6874
 6875    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6876        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6877    }
 6878
 6879    fn manipulate_lines<Fn>(
 6880        &mut self,
 6881        window: &mut Window,
 6882        cx: &mut Context<Self>,
 6883        mut callback: Fn,
 6884    ) where
 6885        Fn: FnMut(&mut Vec<&str>),
 6886    {
 6887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6888        let buffer = self.buffer.read(cx).snapshot(cx);
 6889
 6890        let mut edits = Vec::new();
 6891
 6892        let selections = self.selections.all::<Point>(cx);
 6893        let mut selections = selections.iter().peekable();
 6894        let mut contiguous_row_selections = Vec::new();
 6895        let mut new_selections = Vec::new();
 6896        let mut added_lines = 0;
 6897        let mut removed_lines = 0;
 6898
 6899        while let Some(selection) = selections.next() {
 6900            let (start_row, end_row) = consume_contiguous_rows(
 6901                &mut contiguous_row_selections,
 6902                selection,
 6903                &display_map,
 6904                &mut selections,
 6905            );
 6906
 6907            let start_point = Point::new(start_row.0, 0);
 6908            let end_point = Point::new(
 6909                end_row.previous_row().0,
 6910                buffer.line_len(end_row.previous_row()),
 6911            );
 6912            let text = buffer
 6913                .text_for_range(start_point..end_point)
 6914                .collect::<String>();
 6915
 6916            let mut lines = text.split('\n').collect_vec();
 6917
 6918            let lines_before = lines.len();
 6919            callback(&mut lines);
 6920            let lines_after = lines.len();
 6921
 6922            edits.push((start_point..end_point, lines.join("\n")));
 6923
 6924            // Selections must change based on added and removed line count
 6925            let start_row =
 6926                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6927            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6928            new_selections.push(Selection {
 6929                id: selection.id,
 6930                start: start_row,
 6931                end: end_row,
 6932                goal: SelectionGoal::None,
 6933                reversed: selection.reversed,
 6934            });
 6935
 6936            if lines_after > lines_before {
 6937                added_lines += lines_after - lines_before;
 6938            } else if lines_before > lines_after {
 6939                removed_lines += lines_before - lines_after;
 6940            }
 6941        }
 6942
 6943        self.transact(window, cx, |this, window, cx| {
 6944            let buffer = this.buffer.update(cx, |buffer, cx| {
 6945                buffer.edit(edits, None, cx);
 6946                buffer.snapshot(cx)
 6947            });
 6948
 6949            // Recalculate offsets on newly edited buffer
 6950            let new_selections = new_selections
 6951                .iter()
 6952                .map(|s| {
 6953                    let start_point = Point::new(s.start.0, 0);
 6954                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6955                    Selection {
 6956                        id: s.id,
 6957                        start: buffer.point_to_offset(start_point),
 6958                        end: buffer.point_to_offset(end_point),
 6959                        goal: s.goal,
 6960                        reversed: s.reversed,
 6961                    }
 6962                })
 6963                .collect();
 6964
 6965            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6966                s.select(new_selections);
 6967            });
 6968
 6969            this.request_autoscroll(Autoscroll::fit(), cx);
 6970        });
 6971    }
 6972
 6973    pub fn convert_to_upper_case(
 6974        &mut self,
 6975        _: &ConvertToUpperCase,
 6976        window: &mut Window,
 6977        cx: &mut Context<Self>,
 6978    ) {
 6979        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6980    }
 6981
 6982    pub fn convert_to_lower_case(
 6983        &mut self,
 6984        _: &ConvertToLowerCase,
 6985        window: &mut Window,
 6986        cx: &mut Context<Self>,
 6987    ) {
 6988        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6989    }
 6990
 6991    pub fn convert_to_title_case(
 6992        &mut self,
 6993        _: &ConvertToTitleCase,
 6994        window: &mut Window,
 6995        cx: &mut Context<Self>,
 6996    ) {
 6997        self.manipulate_text(window, cx, |text| {
 6998            text.split('\n')
 6999                .map(|line| line.to_case(Case::Title))
 7000                .join("\n")
 7001        })
 7002    }
 7003
 7004    pub fn convert_to_snake_case(
 7005        &mut self,
 7006        _: &ConvertToSnakeCase,
 7007        window: &mut Window,
 7008        cx: &mut Context<Self>,
 7009    ) {
 7010        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7011    }
 7012
 7013    pub fn convert_to_kebab_case(
 7014        &mut self,
 7015        _: &ConvertToKebabCase,
 7016        window: &mut Window,
 7017        cx: &mut Context<Self>,
 7018    ) {
 7019        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7020    }
 7021
 7022    pub fn convert_to_upper_camel_case(
 7023        &mut self,
 7024        _: &ConvertToUpperCamelCase,
 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::UpperCamel))
 7031                .join("\n")
 7032        })
 7033    }
 7034
 7035    pub fn convert_to_lower_camel_case(
 7036        &mut self,
 7037        _: &ConvertToLowerCamelCase,
 7038        window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7042    }
 7043
 7044    pub fn convert_to_opposite_case(
 7045        &mut self,
 7046        _: &ConvertToOppositeCase,
 7047        window: &mut Window,
 7048        cx: &mut Context<Self>,
 7049    ) {
 7050        self.manipulate_text(window, cx, |text| {
 7051            text.chars()
 7052                .fold(String::with_capacity(text.len()), |mut t, c| {
 7053                    if c.is_uppercase() {
 7054                        t.extend(c.to_lowercase());
 7055                    } else {
 7056                        t.extend(c.to_uppercase());
 7057                    }
 7058                    t
 7059                })
 7060        })
 7061    }
 7062
 7063    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7064    where
 7065        Fn: FnMut(&str) -> String,
 7066    {
 7067        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7068        let buffer = self.buffer.read(cx).snapshot(cx);
 7069
 7070        let mut new_selections = Vec::new();
 7071        let mut edits = Vec::new();
 7072        let mut selection_adjustment = 0i32;
 7073
 7074        for selection in self.selections.all::<usize>(cx) {
 7075            let selection_is_empty = selection.is_empty();
 7076
 7077            let (start, end) = if selection_is_empty {
 7078                let word_range = movement::surrounding_word(
 7079                    &display_map,
 7080                    selection.start.to_display_point(&display_map),
 7081                );
 7082                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7083                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7084                (start, end)
 7085            } else {
 7086                (selection.start, selection.end)
 7087            };
 7088
 7089            let text = buffer.text_for_range(start..end).collect::<String>();
 7090            let old_length = text.len() as i32;
 7091            let text = callback(&text);
 7092
 7093            new_selections.push(Selection {
 7094                start: (start as i32 - selection_adjustment) as usize,
 7095                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7096                goal: SelectionGoal::None,
 7097                ..selection
 7098            });
 7099
 7100            selection_adjustment += old_length - text.len() as i32;
 7101
 7102            edits.push((start..end, text));
 7103        }
 7104
 7105        self.transact(window, cx, |this, window, cx| {
 7106            this.buffer.update(cx, |buffer, cx| {
 7107                buffer.edit(edits, None, cx);
 7108            });
 7109
 7110            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7111                s.select(new_selections);
 7112            });
 7113
 7114            this.request_autoscroll(Autoscroll::fit(), cx);
 7115        });
 7116    }
 7117
 7118    pub fn duplicate(
 7119        &mut self,
 7120        upwards: bool,
 7121        whole_lines: bool,
 7122        window: &mut Window,
 7123        cx: &mut Context<Self>,
 7124    ) {
 7125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7126        let buffer = &display_map.buffer_snapshot;
 7127        let selections = self.selections.all::<Point>(cx);
 7128
 7129        let mut edits = Vec::new();
 7130        let mut selections_iter = selections.iter().peekable();
 7131        while let Some(selection) = selections_iter.next() {
 7132            let mut rows = selection.spanned_rows(false, &display_map);
 7133            // duplicate line-wise
 7134            if whole_lines || selection.start == selection.end {
 7135                // Avoid duplicating the same lines twice.
 7136                while let Some(next_selection) = selections_iter.peek() {
 7137                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7138                    if next_rows.start < rows.end {
 7139                        rows.end = next_rows.end;
 7140                        selections_iter.next().unwrap();
 7141                    } else {
 7142                        break;
 7143                    }
 7144                }
 7145
 7146                // Copy the text from the selected row region and splice it either at the start
 7147                // or end of the region.
 7148                let start = Point::new(rows.start.0, 0);
 7149                let end = Point::new(
 7150                    rows.end.previous_row().0,
 7151                    buffer.line_len(rows.end.previous_row()),
 7152                );
 7153                let text = buffer
 7154                    .text_for_range(start..end)
 7155                    .chain(Some("\n"))
 7156                    .collect::<String>();
 7157                let insert_location = if upwards {
 7158                    Point::new(rows.end.0, 0)
 7159                } else {
 7160                    start
 7161                };
 7162                edits.push((insert_location..insert_location, text));
 7163            } else {
 7164                // duplicate character-wise
 7165                let start = selection.start;
 7166                let end = selection.end;
 7167                let text = buffer.text_for_range(start..end).collect::<String>();
 7168                edits.push((selection.end..selection.end, text));
 7169            }
 7170        }
 7171
 7172        self.transact(window, cx, |this, _, cx| {
 7173            this.buffer.update(cx, |buffer, cx| {
 7174                buffer.edit(edits, None, cx);
 7175            });
 7176
 7177            this.request_autoscroll(Autoscroll::fit(), cx);
 7178        });
 7179    }
 7180
 7181    pub fn duplicate_line_up(
 7182        &mut self,
 7183        _: &DuplicateLineUp,
 7184        window: &mut Window,
 7185        cx: &mut Context<Self>,
 7186    ) {
 7187        self.duplicate(true, true, window, cx);
 7188    }
 7189
 7190    pub fn duplicate_line_down(
 7191        &mut self,
 7192        _: &DuplicateLineDown,
 7193        window: &mut Window,
 7194        cx: &mut Context<Self>,
 7195    ) {
 7196        self.duplicate(false, true, window, cx);
 7197    }
 7198
 7199    pub fn duplicate_selection(
 7200        &mut self,
 7201        _: &DuplicateSelection,
 7202        window: &mut Window,
 7203        cx: &mut Context<Self>,
 7204    ) {
 7205        self.duplicate(false, false, window, cx);
 7206    }
 7207
 7208    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7209        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7210        let buffer = self.buffer.read(cx).snapshot(cx);
 7211
 7212        let mut edits = Vec::new();
 7213        let mut unfold_ranges = Vec::new();
 7214        let mut refold_creases = Vec::new();
 7215
 7216        let selections = self.selections.all::<Point>(cx);
 7217        let mut selections = selections.iter().peekable();
 7218        let mut contiguous_row_selections = Vec::new();
 7219        let mut new_selections = Vec::new();
 7220
 7221        while let Some(selection) = selections.next() {
 7222            // Find all the selections that span a contiguous row range
 7223            let (start_row, end_row) = consume_contiguous_rows(
 7224                &mut contiguous_row_selections,
 7225                selection,
 7226                &display_map,
 7227                &mut selections,
 7228            );
 7229
 7230            // Move the text spanned by the row range to be before the line preceding the row range
 7231            if start_row.0 > 0 {
 7232                let range_to_move = Point::new(
 7233                    start_row.previous_row().0,
 7234                    buffer.line_len(start_row.previous_row()),
 7235                )
 7236                    ..Point::new(
 7237                        end_row.previous_row().0,
 7238                        buffer.line_len(end_row.previous_row()),
 7239                    );
 7240                let insertion_point = display_map
 7241                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7242                    .0;
 7243
 7244                // Don't move lines across excerpts
 7245                if buffer
 7246                    .excerpt_containing(insertion_point..range_to_move.end)
 7247                    .is_some()
 7248                {
 7249                    let text = buffer
 7250                        .text_for_range(range_to_move.clone())
 7251                        .flat_map(|s| s.chars())
 7252                        .skip(1)
 7253                        .chain(['\n'])
 7254                        .collect::<String>();
 7255
 7256                    edits.push((
 7257                        buffer.anchor_after(range_to_move.start)
 7258                            ..buffer.anchor_before(range_to_move.end),
 7259                        String::new(),
 7260                    ));
 7261                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7262                    edits.push((insertion_anchor..insertion_anchor, text));
 7263
 7264                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7265
 7266                    // Move selections up
 7267                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7268                        |mut selection| {
 7269                            selection.start.row -= row_delta;
 7270                            selection.end.row -= row_delta;
 7271                            selection
 7272                        },
 7273                    ));
 7274
 7275                    // Move folds up
 7276                    unfold_ranges.push(range_to_move.clone());
 7277                    for fold in display_map.folds_in_range(
 7278                        buffer.anchor_before(range_to_move.start)
 7279                            ..buffer.anchor_after(range_to_move.end),
 7280                    ) {
 7281                        let mut start = fold.range.start.to_point(&buffer);
 7282                        let mut end = fold.range.end.to_point(&buffer);
 7283                        start.row -= row_delta;
 7284                        end.row -= row_delta;
 7285                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7286                    }
 7287                }
 7288            }
 7289
 7290            // If we didn't move line(s), preserve the existing selections
 7291            new_selections.append(&mut contiguous_row_selections);
 7292        }
 7293
 7294        self.transact(window, cx, |this, window, cx| {
 7295            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7296            this.buffer.update(cx, |buffer, cx| {
 7297                for (range, text) in edits {
 7298                    buffer.edit([(range, text)], None, cx);
 7299                }
 7300            });
 7301            this.fold_creases(refold_creases, true, window, cx);
 7302            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7303                s.select(new_selections);
 7304            })
 7305        });
 7306    }
 7307
 7308    pub fn move_line_down(
 7309        &mut self,
 7310        _: &MoveLineDown,
 7311        window: &mut Window,
 7312        cx: &mut Context<Self>,
 7313    ) {
 7314        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7315        let buffer = self.buffer.read(cx).snapshot(cx);
 7316
 7317        let mut edits = Vec::new();
 7318        let mut unfold_ranges = Vec::new();
 7319        let mut refold_creases = Vec::new();
 7320
 7321        let selections = self.selections.all::<Point>(cx);
 7322        let mut selections = selections.iter().peekable();
 7323        let mut contiguous_row_selections = Vec::new();
 7324        let mut new_selections = Vec::new();
 7325
 7326        while let Some(selection) = selections.next() {
 7327            // Find all the selections that span a contiguous row range
 7328            let (start_row, end_row) = consume_contiguous_rows(
 7329                &mut contiguous_row_selections,
 7330                selection,
 7331                &display_map,
 7332                &mut selections,
 7333            );
 7334
 7335            // Move the text spanned by the row range to be after the last line of the row range
 7336            if end_row.0 <= buffer.max_point().row {
 7337                let range_to_move =
 7338                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7339                let insertion_point = display_map
 7340                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7341                    .0;
 7342
 7343                // Don't move lines across excerpt boundaries
 7344                if buffer
 7345                    .excerpt_containing(range_to_move.start..insertion_point)
 7346                    .is_some()
 7347                {
 7348                    let mut text = String::from("\n");
 7349                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7350                    text.pop(); // Drop trailing newline
 7351                    edits.push((
 7352                        buffer.anchor_after(range_to_move.start)
 7353                            ..buffer.anchor_before(range_to_move.end),
 7354                        String::new(),
 7355                    ));
 7356                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7357                    edits.push((insertion_anchor..insertion_anchor, text));
 7358
 7359                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7360
 7361                    // Move selections down
 7362                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7363                        |mut selection| {
 7364                            selection.start.row += row_delta;
 7365                            selection.end.row += row_delta;
 7366                            selection
 7367                        },
 7368                    ));
 7369
 7370                    // Move folds down
 7371                    unfold_ranges.push(range_to_move.clone());
 7372                    for fold in display_map.folds_in_range(
 7373                        buffer.anchor_before(range_to_move.start)
 7374                            ..buffer.anchor_after(range_to_move.end),
 7375                    ) {
 7376                        let mut start = fold.range.start.to_point(&buffer);
 7377                        let mut end = fold.range.end.to_point(&buffer);
 7378                        start.row += row_delta;
 7379                        end.row += row_delta;
 7380                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7381                    }
 7382                }
 7383            }
 7384
 7385            // If we didn't move line(s), preserve the existing selections
 7386            new_selections.append(&mut contiguous_row_selections);
 7387        }
 7388
 7389        self.transact(window, cx, |this, window, cx| {
 7390            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7391            this.buffer.update(cx, |buffer, cx| {
 7392                for (range, text) in edits {
 7393                    buffer.edit([(range, text)], None, cx);
 7394                }
 7395            });
 7396            this.fold_creases(refold_creases, true, window, cx);
 7397            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7398                s.select(new_selections)
 7399            });
 7400        });
 7401    }
 7402
 7403    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7404        let text_layout_details = &self.text_layout_details(window);
 7405        self.transact(window, cx, |this, window, cx| {
 7406            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7407                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7408                let line_mode = s.line_mode;
 7409                s.move_with(|display_map, selection| {
 7410                    if !selection.is_empty() || line_mode {
 7411                        return;
 7412                    }
 7413
 7414                    let mut head = selection.head();
 7415                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7416                    if head.column() == display_map.line_len(head.row()) {
 7417                        transpose_offset = display_map
 7418                            .buffer_snapshot
 7419                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7420                    }
 7421
 7422                    if transpose_offset == 0 {
 7423                        return;
 7424                    }
 7425
 7426                    *head.column_mut() += 1;
 7427                    head = display_map.clip_point(head, Bias::Right);
 7428                    let goal = SelectionGoal::HorizontalPosition(
 7429                        display_map
 7430                            .x_for_display_point(head, text_layout_details)
 7431                            .into(),
 7432                    );
 7433                    selection.collapse_to(head, goal);
 7434
 7435                    let transpose_start = display_map
 7436                        .buffer_snapshot
 7437                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7438                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7439                        let transpose_end = display_map
 7440                            .buffer_snapshot
 7441                            .clip_offset(transpose_offset + 1, Bias::Right);
 7442                        if let Some(ch) =
 7443                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7444                        {
 7445                            edits.push((transpose_start..transpose_offset, String::new()));
 7446                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7447                        }
 7448                    }
 7449                });
 7450                edits
 7451            });
 7452            this.buffer
 7453                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7454            let selections = this.selections.all::<usize>(cx);
 7455            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7456                s.select(selections);
 7457            });
 7458        });
 7459    }
 7460
 7461    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7462        self.rewrap_impl(IsVimMode::No, cx)
 7463    }
 7464
 7465    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7466        let buffer = self.buffer.read(cx).snapshot(cx);
 7467        let selections = self.selections.all::<Point>(cx);
 7468        let mut selections = selections.iter().peekable();
 7469
 7470        let mut edits = Vec::new();
 7471        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7472
 7473        while let Some(selection) = selections.next() {
 7474            let mut start_row = selection.start.row;
 7475            let mut end_row = selection.end.row;
 7476
 7477            // Skip selections that overlap with a range that has already been rewrapped.
 7478            let selection_range = start_row..end_row;
 7479            if rewrapped_row_ranges
 7480                .iter()
 7481                .any(|range| range.overlaps(&selection_range))
 7482            {
 7483                continue;
 7484            }
 7485
 7486            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7487
 7488            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7489                match language_scope.language_name().as_ref() {
 7490                    "Markdown" | "Plain Text" => {
 7491                        should_rewrap = true;
 7492                    }
 7493                    _ => {}
 7494                }
 7495            }
 7496
 7497            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7498
 7499            // Since not all lines in the selection may be at the same indent
 7500            // level, choose the indent size that is the most common between all
 7501            // of the lines.
 7502            //
 7503            // If there is a tie, we use the deepest indent.
 7504            let (indent_size, indent_end) = {
 7505                let mut indent_size_occurrences = HashMap::default();
 7506                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7507
 7508                for row in start_row..=end_row {
 7509                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7510                    rows_by_indent_size.entry(indent).or_default().push(row);
 7511                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7512                }
 7513
 7514                let indent_size = indent_size_occurrences
 7515                    .into_iter()
 7516                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7517                    .map(|(indent, _)| indent)
 7518                    .unwrap_or_default();
 7519                let row = rows_by_indent_size[&indent_size][0];
 7520                let indent_end = Point::new(row, indent_size.len);
 7521
 7522                (indent_size, indent_end)
 7523            };
 7524
 7525            let mut line_prefix = indent_size.chars().collect::<String>();
 7526
 7527            if let Some(comment_prefix) =
 7528                buffer
 7529                    .language_scope_at(selection.head())
 7530                    .and_then(|language| {
 7531                        language
 7532                            .line_comment_prefixes()
 7533                            .iter()
 7534                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7535                            .cloned()
 7536                    })
 7537            {
 7538                line_prefix.push_str(&comment_prefix);
 7539                should_rewrap = true;
 7540            }
 7541
 7542            if !should_rewrap {
 7543                continue;
 7544            }
 7545
 7546            if selection.is_empty() {
 7547                'expand_upwards: while start_row > 0 {
 7548                    let prev_row = start_row - 1;
 7549                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7550                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7551                    {
 7552                        start_row = prev_row;
 7553                    } else {
 7554                        break 'expand_upwards;
 7555                    }
 7556                }
 7557
 7558                'expand_downwards: while end_row < buffer.max_point().row {
 7559                    let next_row = end_row + 1;
 7560                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7561                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7562                    {
 7563                        end_row = next_row;
 7564                    } else {
 7565                        break 'expand_downwards;
 7566                    }
 7567                }
 7568            }
 7569
 7570            let start = Point::new(start_row, 0);
 7571            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7572            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7573            let Some(lines_without_prefixes) = selection_text
 7574                .lines()
 7575                .map(|line| {
 7576                    line.strip_prefix(&line_prefix)
 7577                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7578                        .ok_or_else(|| {
 7579                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7580                        })
 7581                })
 7582                .collect::<Result<Vec<_>, _>>()
 7583                .log_err()
 7584            else {
 7585                continue;
 7586            };
 7587
 7588            let wrap_column = buffer
 7589                .settings_at(Point::new(start_row, 0), cx)
 7590                .preferred_line_length as usize;
 7591            let wrapped_text = wrap_with_prefix(
 7592                line_prefix,
 7593                lines_without_prefixes.join(" "),
 7594                wrap_column,
 7595                tab_size,
 7596            );
 7597
 7598            // TODO: should always use char-based diff while still supporting cursor behavior that
 7599            // matches vim.
 7600            let diff = match is_vim_mode {
 7601                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7602                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7603            };
 7604            let mut offset = start.to_offset(&buffer);
 7605            let mut moved_since_edit = true;
 7606
 7607            for change in diff.iter_all_changes() {
 7608                let value = change.value();
 7609                match change.tag() {
 7610                    ChangeTag::Equal => {
 7611                        offset += value.len();
 7612                        moved_since_edit = true;
 7613                    }
 7614                    ChangeTag::Delete => {
 7615                        let start = buffer.anchor_after(offset);
 7616                        let end = buffer.anchor_before(offset + value.len());
 7617
 7618                        if moved_since_edit {
 7619                            edits.push((start..end, String::new()));
 7620                        } else {
 7621                            edits.last_mut().unwrap().0.end = end;
 7622                        }
 7623
 7624                        offset += value.len();
 7625                        moved_since_edit = false;
 7626                    }
 7627                    ChangeTag::Insert => {
 7628                        if moved_since_edit {
 7629                            let anchor = buffer.anchor_after(offset);
 7630                            edits.push((anchor..anchor, value.to_string()));
 7631                        } else {
 7632                            edits.last_mut().unwrap().1.push_str(value);
 7633                        }
 7634
 7635                        moved_since_edit = false;
 7636                    }
 7637                }
 7638            }
 7639
 7640            rewrapped_row_ranges.push(start_row..=end_row);
 7641        }
 7642
 7643        self.buffer
 7644            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7645    }
 7646
 7647    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7648        let mut text = String::new();
 7649        let buffer = self.buffer.read(cx).snapshot(cx);
 7650        let mut selections = self.selections.all::<Point>(cx);
 7651        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7652        {
 7653            let max_point = buffer.max_point();
 7654            let mut is_first = true;
 7655            for selection in &mut selections {
 7656                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7657                if is_entire_line {
 7658                    selection.start = Point::new(selection.start.row, 0);
 7659                    if !selection.is_empty() && selection.end.column == 0 {
 7660                        selection.end = cmp::min(max_point, selection.end);
 7661                    } else {
 7662                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7663                    }
 7664                    selection.goal = SelectionGoal::None;
 7665                }
 7666                if is_first {
 7667                    is_first = false;
 7668                } else {
 7669                    text += "\n";
 7670                }
 7671                let mut len = 0;
 7672                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7673                    text.push_str(chunk);
 7674                    len += chunk.len();
 7675                }
 7676                clipboard_selections.push(ClipboardSelection {
 7677                    len,
 7678                    is_entire_line,
 7679                    first_line_indent: buffer
 7680                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7681                        .len,
 7682                });
 7683            }
 7684        }
 7685
 7686        self.transact(window, cx, |this, window, cx| {
 7687            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7688                s.select(selections);
 7689            });
 7690            this.insert("", window, cx);
 7691        });
 7692        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7693    }
 7694
 7695    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7696        let item = self.cut_common(window, cx);
 7697        cx.write_to_clipboard(item);
 7698    }
 7699
 7700    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7701        self.change_selections(None, window, cx, |s| {
 7702            s.move_with(|snapshot, sel| {
 7703                if sel.is_empty() {
 7704                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7705                }
 7706            });
 7707        });
 7708        let item = self.cut_common(window, cx);
 7709        cx.set_global(KillRing(item))
 7710    }
 7711
 7712    pub fn kill_ring_yank(
 7713        &mut self,
 7714        _: &KillRingYank,
 7715        window: &mut Window,
 7716        cx: &mut Context<Self>,
 7717    ) {
 7718        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7719            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7720                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7721            } else {
 7722                return;
 7723            }
 7724        } else {
 7725            return;
 7726        };
 7727        self.do_paste(&text, metadata, false, window, cx);
 7728    }
 7729
 7730    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7731        let selections = self.selections.all::<Point>(cx);
 7732        let buffer = self.buffer.read(cx).read(cx);
 7733        let mut text = String::new();
 7734
 7735        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7736        {
 7737            let max_point = buffer.max_point();
 7738            let mut is_first = true;
 7739            for selection in selections.iter() {
 7740                let mut start = selection.start;
 7741                let mut end = selection.end;
 7742                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7743                if is_entire_line {
 7744                    start = Point::new(start.row, 0);
 7745                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7746                }
 7747                if is_first {
 7748                    is_first = false;
 7749                } else {
 7750                    text += "\n";
 7751                }
 7752                let mut len = 0;
 7753                for chunk in buffer.text_for_range(start..end) {
 7754                    text.push_str(chunk);
 7755                    len += chunk.len();
 7756                }
 7757                clipboard_selections.push(ClipboardSelection {
 7758                    len,
 7759                    is_entire_line,
 7760                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7761                });
 7762            }
 7763        }
 7764
 7765        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7766            text,
 7767            clipboard_selections,
 7768        ));
 7769    }
 7770
 7771    pub fn do_paste(
 7772        &mut self,
 7773        text: &String,
 7774        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7775        handle_entire_lines: bool,
 7776        window: &mut Window,
 7777        cx: &mut Context<Self>,
 7778    ) {
 7779        if self.read_only(cx) {
 7780            return;
 7781        }
 7782
 7783        let clipboard_text = Cow::Borrowed(text);
 7784
 7785        self.transact(window, cx, |this, window, cx| {
 7786            if let Some(mut clipboard_selections) = clipboard_selections {
 7787                let old_selections = this.selections.all::<usize>(cx);
 7788                let all_selections_were_entire_line =
 7789                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7790                let first_selection_indent_column =
 7791                    clipboard_selections.first().map(|s| s.first_line_indent);
 7792                if clipboard_selections.len() != old_selections.len() {
 7793                    clipboard_selections.drain(..);
 7794                }
 7795                let cursor_offset = this.selections.last::<usize>(cx).head();
 7796                let mut auto_indent_on_paste = true;
 7797
 7798                this.buffer.update(cx, |buffer, cx| {
 7799                    let snapshot = buffer.read(cx);
 7800                    auto_indent_on_paste =
 7801                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7802
 7803                    let mut start_offset = 0;
 7804                    let mut edits = Vec::new();
 7805                    let mut original_indent_columns = Vec::new();
 7806                    for (ix, selection) in old_selections.iter().enumerate() {
 7807                        let to_insert;
 7808                        let entire_line;
 7809                        let original_indent_column;
 7810                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7811                            let end_offset = start_offset + clipboard_selection.len;
 7812                            to_insert = &clipboard_text[start_offset..end_offset];
 7813                            entire_line = clipboard_selection.is_entire_line;
 7814                            start_offset = end_offset + 1;
 7815                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7816                        } else {
 7817                            to_insert = clipboard_text.as_str();
 7818                            entire_line = all_selections_were_entire_line;
 7819                            original_indent_column = first_selection_indent_column
 7820                        }
 7821
 7822                        // If the corresponding selection was empty when this slice of the
 7823                        // clipboard text was written, then the entire line containing the
 7824                        // selection was copied. If this selection is also currently empty,
 7825                        // then paste the line before the current line of the buffer.
 7826                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7827                            let column = selection.start.to_point(&snapshot).column as usize;
 7828                            let line_start = selection.start - column;
 7829                            line_start..line_start
 7830                        } else {
 7831                            selection.range()
 7832                        };
 7833
 7834                        edits.push((range, to_insert));
 7835                        original_indent_columns.extend(original_indent_column);
 7836                    }
 7837                    drop(snapshot);
 7838
 7839                    buffer.edit(
 7840                        edits,
 7841                        if auto_indent_on_paste {
 7842                            Some(AutoindentMode::Block {
 7843                                original_indent_columns,
 7844                            })
 7845                        } else {
 7846                            None
 7847                        },
 7848                        cx,
 7849                    );
 7850                });
 7851
 7852                let selections = this.selections.all::<usize>(cx);
 7853                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7854                    s.select(selections)
 7855                });
 7856            } else {
 7857                this.insert(&clipboard_text, window, cx);
 7858            }
 7859        });
 7860    }
 7861
 7862    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7863        if let Some(item) = cx.read_from_clipboard() {
 7864            let entries = item.entries();
 7865
 7866            match entries.first() {
 7867                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7868                // of all the pasted entries.
 7869                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7870                    .do_paste(
 7871                        clipboard_string.text(),
 7872                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7873                        true,
 7874                        window,
 7875                        cx,
 7876                    ),
 7877                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7878            }
 7879        }
 7880    }
 7881
 7882    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7883        if self.read_only(cx) {
 7884            return;
 7885        }
 7886
 7887        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7888            if let Some((selections, _)) =
 7889                self.selection_history.transaction(transaction_id).cloned()
 7890            {
 7891                self.change_selections(None, window, cx, |s| {
 7892                    s.select_anchors(selections.to_vec());
 7893                });
 7894            }
 7895            self.request_autoscroll(Autoscroll::fit(), cx);
 7896            self.unmark_text(window, cx);
 7897            self.refresh_inline_completion(true, false, window, cx);
 7898            cx.emit(EditorEvent::Edited { transaction_id });
 7899            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7900        }
 7901    }
 7902
 7903    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7904        if self.read_only(cx) {
 7905            return;
 7906        }
 7907
 7908        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7909            if let Some((_, Some(selections))) =
 7910                self.selection_history.transaction(transaction_id).cloned()
 7911            {
 7912                self.change_selections(None, window, cx, |s| {
 7913                    s.select_anchors(selections.to_vec());
 7914                });
 7915            }
 7916            self.request_autoscroll(Autoscroll::fit(), cx);
 7917            self.unmark_text(window, cx);
 7918            self.refresh_inline_completion(true, false, window, cx);
 7919            cx.emit(EditorEvent::Edited { transaction_id });
 7920        }
 7921    }
 7922
 7923    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7924        self.buffer
 7925            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7926    }
 7927
 7928    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7929        self.buffer
 7930            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7931    }
 7932
 7933    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7934        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7935            let line_mode = s.line_mode;
 7936            s.move_with(|map, selection| {
 7937                let cursor = if selection.is_empty() && !line_mode {
 7938                    movement::left(map, selection.start)
 7939                } else {
 7940                    selection.start
 7941                };
 7942                selection.collapse_to(cursor, SelectionGoal::None);
 7943            });
 7944        })
 7945    }
 7946
 7947    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7948        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7949            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7950        })
 7951    }
 7952
 7953    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7954        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7955            let line_mode = s.line_mode;
 7956            s.move_with(|map, selection| {
 7957                let cursor = if selection.is_empty() && !line_mode {
 7958                    movement::right(map, selection.end)
 7959                } else {
 7960                    selection.end
 7961                };
 7962                selection.collapse_to(cursor, SelectionGoal::None)
 7963            });
 7964        })
 7965    }
 7966
 7967    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7969            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7970        })
 7971    }
 7972
 7973    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7974        if self.take_rename(true, window, cx).is_some() {
 7975            return;
 7976        }
 7977
 7978        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7979            cx.propagate();
 7980            return;
 7981        }
 7982
 7983        let text_layout_details = &self.text_layout_details(window);
 7984        let selection_count = self.selections.count();
 7985        let first_selection = self.selections.first_anchor();
 7986
 7987        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7988            let line_mode = s.line_mode;
 7989            s.move_with(|map, selection| {
 7990                if !selection.is_empty() && !line_mode {
 7991                    selection.goal = SelectionGoal::None;
 7992                }
 7993                let (cursor, goal) = movement::up(
 7994                    map,
 7995                    selection.start,
 7996                    selection.goal,
 7997                    false,
 7998                    text_layout_details,
 7999                );
 8000                selection.collapse_to(cursor, goal);
 8001            });
 8002        });
 8003
 8004        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8005        {
 8006            cx.propagate();
 8007        }
 8008    }
 8009
 8010    pub fn move_up_by_lines(
 8011        &mut self,
 8012        action: &MoveUpByLines,
 8013        window: &mut Window,
 8014        cx: &mut Context<Self>,
 8015    ) {
 8016        if self.take_rename(true, window, cx).is_some() {
 8017            return;
 8018        }
 8019
 8020        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8021            cx.propagate();
 8022            return;
 8023        }
 8024
 8025        let text_layout_details = &self.text_layout_details(window);
 8026
 8027        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8028            let line_mode = s.line_mode;
 8029            s.move_with(|map, selection| {
 8030                if !selection.is_empty() && !line_mode {
 8031                    selection.goal = SelectionGoal::None;
 8032                }
 8033                let (cursor, goal) = movement::up_by_rows(
 8034                    map,
 8035                    selection.start,
 8036                    action.lines,
 8037                    selection.goal,
 8038                    false,
 8039                    text_layout_details,
 8040                );
 8041                selection.collapse_to(cursor, goal);
 8042            });
 8043        })
 8044    }
 8045
 8046    pub fn move_down_by_lines(
 8047        &mut self,
 8048        action: &MoveDownByLines,
 8049        window: &mut Window,
 8050        cx: &mut Context<Self>,
 8051    ) {
 8052        if self.take_rename(true, window, cx).is_some() {
 8053            return;
 8054        }
 8055
 8056        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8057            cx.propagate();
 8058            return;
 8059        }
 8060
 8061        let text_layout_details = &self.text_layout_details(window);
 8062
 8063        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8064            let line_mode = s.line_mode;
 8065            s.move_with(|map, selection| {
 8066                if !selection.is_empty() && !line_mode {
 8067                    selection.goal = SelectionGoal::None;
 8068                }
 8069                let (cursor, goal) = movement::down_by_rows(
 8070                    map,
 8071                    selection.start,
 8072                    action.lines,
 8073                    selection.goal,
 8074                    false,
 8075                    text_layout_details,
 8076                );
 8077                selection.collapse_to(cursor, goal);
 8078            });
 8079        })
 8080    }
 8081
 8082    pub fn select_down_by_lines(
 8083        &mut self,
 8084        action: &SelectDownByLines,
 8085        window: &mut Window,
 8086        cx: &mut Context<Self>,
 8087    ) {
 8088        let text_layout_details = &self.text_layout_details(window);
 8089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8090            s.move_heads_with(|map, head, goal| {
 8091                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8092            })
 8093        })
 8094    }
 8095
 8096    pub fn select_up_by_lines(
 8097        &mut self,
 8098        action: &SelectUpByLines,
 8099        window: &mut Window,
 8100        cx: &mut Context<Self>,
 8101    ) {
 8102        let text_layout_details = &self.text_layout_details(window);
 8103        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8104            s.move_heads_with(|map, head, goal| {
 8105                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8106            })
 8107        })
 8108    }
 8109
 8110    pub fn select_page_up(
 8111        &mut self,
 8112        _: &SelectPageUp,
 8113        window: &mut Window,
 8114        cx: &mut Context<Self>,
 8115    ) {
 8116        let Some(row_count) = self.visible_row_count() else {
 8117            return;
 8118        };
 8119
 8120        let text_layout_details = &self.text_layout_details(window);
 8121
 8122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8123            s.move_heads_with(|map, head, goal| {
 8124                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8125            })
 8126        })
 8127    }
 8128
 8129    pub fn move_page_up(
 8130        &mut self,
 8131        action: &MovePageUp,
 8132        window: &mut Window,
 8133        cx: &mut Context<Self>,
 8134    ) {
 8135        if self.take_rename(true, window, cx).is_some() {
 8136            return;
 8137        }
 8138
 8139        if self
 8140            .context_menu
 8141            .borrow_mut()
 8142            .as_mut()
 8143            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8144            .unwrap_or(false)
 8145        {
 8146            return;
 8147        }
 8148
 8149        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8150            cx.propagate();
 8151            return;
 8152        }
 8153
 8154        let Some(row_count) = self.visible_row_count() else {
 8155            return;
 8156        };
 8157
 8158        let autoscroll = if action.center_cursor {
 8159            Autoscroll::center()
 8160        } else {
 8161            Autoscroll::fit()
 8162        };
 8163
 8164        let text_layout_details = &self.text_layout_details(window);
 8165
 8166        self.change_selections(Some(autoscroll), window, cx, |s| {
 8167            let line_mode = s.line_mode;
 8168            s.move_with(|map, selection| {
 8169                if !selection.is_empty() && !line_mode {
 8170                    selection.goal = SelectionGoal::None;
 8171                }
 8172                let (cursor, goal) = movement::up_by_rows(
 8173                    map,
 8174                    selection.end,
 8175                    row_count,
 8176                    selection.goal,
 8177                    false,
 8178                    text_layout_details,
 8179                );
 8180                selection.collapse_to(cursor, goal);
 8181            });
 8182        });
 8183    }
 8184
 8185    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8186        let text_layout_details = &self.text_layout_details(window);
 8187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8188            s.move_heads_with(|map, head, goal| {
 8189                movement::up(map, head, goal, false, text_layout_details)
 8190            })
 8191        })
 8192    }
 8193
 8194    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8195        self.take_rename(true, window, cx);
 8196
 8197        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8198            cx.propagate();
 8199            return;
 8200        }
 8201
 8202        let text_layout_details = &self.text_layout_details(window);
 8203        let selection_count = self.selections.count();
 8204        let first_selection = self.selections.first_anchor();
 8205
 8206        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8207            let line_mode = s.line_mode;
 8208            s.move_with(|map, selection| {
 8209                if !selection.is_empty() && !line_mode {
 8210                    selection.goal = SelectionGoal::None;
 8211                }
 8212                let (cursor, goal) = movement::down(
 8213                    map,
 8214                    selection.end,
 8215                    selection.goal,
 8216                    false,
 8217                    text_layout_details,
 8218                );
 8219                selection.collapse_to(cursor, goal);
 8220            });
 8221        });
 8222
 8223        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8224        {
 8225            cx.propagate();
 8226        }
 8227    }
 8228
 8229    pub fn select_page_down(
 8230        &mut self,
 8231        _: &SelectPageDown,
 8232        window: &mut Window,
 8233        cx: &mut Context<Self>,
 8234    ) {
 8235        let Some(row_count) = self.visible_row_count() else {
 8236            return;
 8237        };
 8238
 8239        let text_layout_details = &self.text_layout_details(window);
 8240
 8241        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8242            s.move_heads_with(|map, head, goal| {
 8243                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8244            })
 8245        })
 8246    }
 8247
 8248    pub fn move_page_down(
 8249        &mut self,
 8250        action: &MovePageDown,
 8251        window: &mut Window,
 8252        cx: &mut Context<Self>,
 8253    ) {
 8254        if self.take_rename(true, window, cx).is_some() {
 8255            return;
 8256        }
 8257
 8258        if self
 8259            .context_menu
 8260            .borrow_mut()
 8261            .as_mut()
 8262            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8263            .unwrap_or(false)
 8264        {
 8265            return;
 8266        }
 8267
 8268        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8269            cx.propagate();
 8270            return;
 8271        }
 8272
 8273        let Some(row_count) = self.visible_row_count() else {
 8274            return;
 8275        };
 8276
 8277        let autoscroll = if action.center_cursor {
 8278            Autoscroll::center()
 8279        } else {
 8280            Autoscroll::fit()
 8281        };
 8282
 8283        let text_layout_details = &self.text_layout_details(window);
 8284        self.change_selections(Some(autoscroll), window, cx, |s| {
 8285            let line_mode = s.line_mode;
 8286            s.move_with(|map, selection| {
 8287                if !selection.is_empty() && !line_mode {
 8288                    selection.goal = SelectionGoal::None;
 8289                }
 8290                let (cursor, goal) = movement::down_by_rows(
 8291                    map,
 8292                    selection.end,
 8293                    row_count,
 8294                    selection.goal,
 8295                    false,
 8296                    text_layout_details,
 8297                );
 8298                selection.collapse_to(cursor, goal);
 8299            });
 8300        });
 8301    }
 8302
 8303    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8304        let text_layout_details = &self.text_layout_details(window);
 8305        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8306            s.move_heads_with(|map, head, goal| {
 8307                movement::down(map, head, goal, false, text_layout_details)
 8308            })
 8309        });
 8310    }
 8311
 8312    pub fn context_menu_first(
 8313        &mut self,
 8314        _: &ContextMenuFirst,
 8315        _window: &mut Window,
 8316        cx: &mut Context<Self>,
 8317    ) {
 8318        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8319            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8320        }
 8321    }
 8322
 8323    pub fn context_menu_prev(
 8324        &mut self,
 8325        _: &ContextMenuPrev,
 8326        _window: &mut Window,
 8327        cx: &mut Context<Self>,
 8328    ) {
 8329        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8330            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8331        }
 8332    }
 8333
 8334    pub fn context_menu_next(
 8335        &mut self,
 8336        _: &ContextMenuNext,
 8337        _window: &mut Window,
 8338        cx: &mut Context<Self>,
 8339    ) {
 8340        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8341            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8342        }
 8343    }
 8344
 8345    pub fn context_menu_last(
 8346        &mut self,
 8347        _: &ContextMenuLast,
 8348        _window: &mut Window,
 8349        cx: &mut Context<Self>,
 8350    ) {
 8351        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8352            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8353        }
 8354    }
 8355
 8356    pub fn move_to_previous_word_start(
 8357        &mut self,
 8358        _: &MoveToPreviousWordStart,
 8359        window: &mut Window,
 8360        cx: &mut Context<Self>,
 8361    ) {
 8362        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8363            s.move_cursors_with(|map, head, _| {
 8364                (
 8365                    movement::previous_word_start(map, head),
 8366                    SelectionGoal::None,
 8367                )
 8368            });
 8369        })
 8370    }
 8371
 8372    pub fn move_to_previous_subword_start(
 8373        &mut self,
 8374        _: &MoveToPreviousSubwordStart,
 8375        window: &mut Window,
 8376        cx: &mut Context<Self>,
 8377    ) {
 8378        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8379            s.move_cursors_with(|map, head, _| {
 8380                (
 8381                    movement::previous_subword_start(map, head),
 8382                    SelectionGoal::None,
 8383                )
 8384            });
 8385        })
 8386    }
 8387
 8388    pub fn select_to_previous_word_start(
 8389        &mut self,
 8390        _: &SelectToPreviousWordStart,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8395            s.move_heads_with(|map, head, _| {
 8396                (
 8397                    movement::previous_word_start(map, head),
 8398                    SelectionGoal::None,
 8399                )
 8400            });
 8401        })
 8402    }
 8403
 8404    pub fn select_to_previous_subword_start(
 8405        &mut self,
 8406        _: &SelectToPreviousSubwordStart,
 8407        window: &mut Window,
 8408        cx: &mut Context<Self>,
 8409    ) {
 8410        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8411            s.move_heads_with(|map, head, _| {
 8412                (
 8413                    movement::previous_subword_start(map, head),
 8414                    SelectionGoal::None,
 8415                )
 8416            });
 8417        })
 8418    }
 8419
 8420    pub fn delete_to_previous_word_start(
 8421        &mut self,
 8422        action: &DeleteToPreviousWordStart,
 8423        window: &mut Window,
 8424        cx: &mut Context<Self>,
 8425    ) {
 8426        self.transact(window, cx, |this, window, cx| {
 8427            this.select_autoclose_pair(window, cx);
 8428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8429                let line_mode = s.line_mode;
 8430                s.move_with(|map, selection| {
 8431                    if selection.is_empty() && !line_mode {
 8432                        let cursor = if action.ignore_newlines {
 8433                            movement::previous_word_start(map, selection.head())
 8434                        } else {
 8435                            movement::previous_word_start_or_newline(map, selection.head())
 8436                        };
 8437                        selection.set_head(cursor, SelectionGoal::None);
 8438                    }
 8439                });
 8440            });
 8441            this.insert("", window, cx);
 8442        });
 8443    }
 8444
 8445    pub fn delete_to_previous_subword_start(
 8446        &mut self,
 8447        _: &DeleteToPreviousSubwordStart,
 8448        window: &mut Window,
 8449        cx: &mut Context<Self>,
 8450    ) {
 8451        self.transact(window, cx, |this, window, cx| {
 8452            this.select_autoclose_pair(window, cx);
 8453            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8454                let line_mode = s.line_mode;
 8455                s.move_with(|map, selection| {
 8456                    if selection.is_empty() && !line_mode {
 8457                        let cursor = movement::previous_subword_start(map, selection.head());
 8458                        selection.set_head(cursor, SelectionGoal::None);
 8459                    }
 8460                });
 8461            });
 8462            this.insert("", window, cx);
 8463        });
 8464    }
 8465
 8466    pub fn move_to_next_word_end(
 8467        &mut self,
 8468        _: &MoveToNextWordEnd,
 8469        window: &mut Window,
 8470        cx: &mut Context<Self>,
 8471    ) {
 8472        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8473            s.move_cursors_with(|map, head, _| {
 8474                (movement::next_word_end(map, head), SelectionGoal::None)
 8475            });
 8476        })
 8477    }
 8478
 8479    pub fn move_to_next_subword_end(
 8480        &mut self,
 8481        _: &MoveToNextSubwordEnd,
 8482        window: &mut Window,
 8483        cx: &mut Context<Self>,
 8484    ) {
 8485        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8486            s.move_cursors_with(|map, head, _| {
 8487                (movement::next_subword_end(map, head), SelectionGoal::None)
 8488            });
 8489        })
 8490    }
 8491
 8492    pub fn select_to_next_word_end(
 8493        &mut self,
 8494        _: &SelectToNextWordEnd,
 8495        window: &mut Window,
 8496        cx: &mut Context<Self>,
 8497    ) {
 8498        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8499            s.move_heads_with(|map, head, _| {
 8500                (movement::next_word_end(map, head), SelectionGoal::None)
 8501            });
 8502        })
 8503    }
 8504
 8505    pub fn select_to_next_subword_end(
 8506        &mut self,
 8507        _: &SelectToNextSubwordEnd,
 8508        window: &mut Window,
 8509        cx: &mut Context<Self>,
 8510    ) {
 8511        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8512            s.move_heads_with(|map, head, _| {
 8513                (movement::next_subword_end(map, head), SelectionGoal::None)
 8514            });
 8515        })
 8516    }
 8517
 8518    pub fn delete_to_next_word_end(
 8519        &mut self,
 8520        action: &DeleteToNextWordEnd,
 8521        window: &mut Window,
 8522        cx: &mut Context<Self>,
 8523    ) {
 8524        self.transact(window, cx, |this, window, cx| {
 8525            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8526                let line_mode = s.line_mode;
 8527                s.move_with(|map, selection| {
 8528                    if selection.is_empty() && !line_mode {
 8529                        let cursor = if action.ignore_newlines {
 8530                            movement::next_word_end(map, selection.head())
 8531                        } else {
 8532                            movement::next_word_end_or_newline(map, selection.head())
 8533                        };
 8534                        selection.set_head(cursor, SelectionGoal::None);
 8535                    }
 8536                });
 8537            });
 8538            this.insert("", window, cx);
 8539        });
 8540    }
 8541
 8542    pub fn delete_to_next_subword_end(
 8543        &mut self,
 8544        _: &DeleteToNextSubwordEnd,
 8545        window: &mut Window,
 8546        cx: &mut Context<Self>,
 8547    ) {
 8548        self.transact(window, cx, |this, window, cx| {
 8549            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8550                s.move_with(|map, selection| {
 8551                    if selection.is_empty() {
 8552                        let cursor = movement::next_subword_end(map, selection.head());
 8553                        selection.set_head(cursor, SelectionGoal::None);
 8554                    }
 8555                });
 8556            });
 8557            this.insert("", window, cx);
 8558        });
 8559    }
 8560
 8561    pub fn move_to_beginning_of_line(
 8562        &mut self,
 8563        action: &MoveToBeginningOfLine,
 8564        window: &mut Window,
 8565        cx: &mut Context<Self>,
 8566    ) {
 8567        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8568            s.move_cursors_with(|map, head, _| {
 8569                (
 8570                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8571                    SelectionGoal::None,
 8572                )
 8573            });
 8574        })
 8575    }
 8576
 8577    pub fn select_to_beginning_of_line(
 8578        &mut self,
 8579        action: &SelectToBeginningOfLine,
 8580        window: &mut Window,
 8581        cx: &mut Context<Self>,
 8582    ) {
 8583        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8584            s.move_heads_with(|map, head, _| {
 8585                (
 8586                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8587                    SelectionGoal::None,
 8588                )
 8589            });
 8590        });
 8591    }
 8592
 8593    pub fn delete_to_beginning_of_line(
 8594        &mut self,
 8595        _: &DeleteToBeginningOfLine,
 8596        window: &mut Window,
 8597        cx: &mut Context<Self>,
 8598    ) {
 8599        self.transact(window, cx, |this, window, cx| {
 8600            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8601                s.move_with(|_, selection| {
 8602                    selection.reversed = true;
 8603                });
 8604            });
 8605
 8606            this.select_to_beginning_of_line(
 8607                &SelectToBeginningOfLine {
 8608                    stop_at_soft_wraps: false,
 8609                },
 8610                window,
 8611                cx,
 8612            );
 8613            this.backspace(&Backspace, window, cx);
 8614        });
 8615    }
 8616
 8617    pub fn move_to_end_of_line(
 8618        &mut self,
 8619        action: &MoveToEndOfLine,
 8620        window: &mut Window,
 8621        cx: &mut Context<Self>,
 8622    ) {
 8623        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8624            s.move_cursors_with(|map, head, _| {
 8625                (
 8626                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8627                    SelectionGoal::None,
 8628                )
 8629            });
 8630        })
 8631    }
 8632
 8633    pub fn select_to_end_of_line(
 8634        &mut self,
 8635        action: &SelectToEndOfLine,
 8636        window: &mut Window,
 8637        cx: &mut Context<Self>,
 8638    ) {
 8639        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8640            s.move_heads_with(|map, head, _| {
 8641                (
 8642                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8643                    SelectionGoal::None,
 8644                )
 8645            });
 8646        })
 8647    }
 8648
 8649    pub fn delete_to_end_of_line(
 8650        &mut self,
 8651        _: &DeleteToEndOfLine,
 8652        window: &mut Window,
 8653        cx: &mut Context<Self>,
 8654    ) {
 8655        self.transact(window, cx, |this, window, cx| {
 8656            this.select_to_end_of_line(
 8657                &SelectToEndOfLine {
 8658                    stop_at_soft_wraps: false,
 8659                },
 8660                window,
 8661                cx,
 8662            );
 8663            this.delete(&Delete, window, cx);
 8664        });
 8665    }
 8666
 8667    pub fn cut_to_end_of_line(
 8668        &mut self,
 8669        _: &CutToEndOfLine,
 8670        window: &mut Window,
 8671        cx: &mut Context<Self>,
 8672    ) {
 8673        self.transact(window, cx, |this, window, cx| {
 8674            this.select_to_end_of_line(
 8675                &SelectToEndOfLine {
 8676                    stop_at_soft_wraps: false,
 8677                },
 8678                window,
 8679                cx,
 8680            );
 8681            this.cut(&Cut, window, cx);
 8682        });
 8683    }
 8684
 8685    pub fn move_to_start_of_paragraph(
 8686        &mut self,
 8687        _: &MoveToStartOfParagraph,
 8688        window: &mut Window,
 8689        cx: &mut Context<Self>,
 8690    ) {
 8691        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8692            cx.propagate();
 8693            return;
 8694        }
 8695
 8696        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8697            s.move_with(|map, selection| {
 8698                selection.collapse_to(
 8699                    movement::start_of_paragraph(map, selection.head(), 1),
 8700                    SelectionGoal::None,
 8701                )
 8702            });
 8703        })
 8704    }
 8705
 8706    pub fn move_to_end_of_paragraph(
 8707        &mut self,
 8708        _: &MoveToEndOfParagraph,
 8709        window: &mut Window,
 8710        cx: &mut Context<Self>,
 8711    ) {
 8712        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8713            cx.propagate();
 8714            return;
 8715        }
 8716
 8717        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8718            s.move_with(|map, selection| {
 8719                selection.collapse_to(
 8720                    movement::end_of_paragraph(map, selection.head(), 1),
 8721                    SelectionGoal::None,
 8722                )
 8723            });
 8724        })
 8725    }
 8726
 8727    pub fn select_to_start_of_paragraph(
 8728        &mut self,
 8729        _: &SelectToStartOfParagraph,
 8730        window: &mut Window,
 8731        cx: &mut Context<Self>,
 8732    ) {
 8733        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8734            cx.propagate();
 8735            return;
 8736        }
 8737
 8738        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8739            s.move_heads_with(|map, head, _| {
 8740                (
 8741                    movement::start_of_paragraph(map, head, 1),
 8742                    SelectionGoal::None,
 8743                )
 8744            });
 8745        })
 8746    }
 8747
 8748    pub fn select_to_end_of_paragraph(
 8749        &mut self,
 8750        _: &SelectToEndOfParagraph,
 8751        window: &mut Window,
 8752        cx: &mut Context<Self>,
 8753    ) {
 8754        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8755            cx.propagate();
 8756            return;
 8757        }
 8758
 8759        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8760            s.move_heads_with(|map, head, _| {
 8761                (
 8762                    movement::end_of_paragraph(map, head, 1),
 8763                    SelectionGoal::None,
 8764                )
 8765            });
 8766        })
 8767    }
 8768
 8769    pub fn move_to_beginning(
 8770        &mut self,
 8771        _: &MoveToBeginning,
 8772        window: &mut Window,
 8773        cx: &mut Context<Self>,
 8774    ) {
 8775        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8776            cx.propagate();
 8777            return;
 8778        }
 8779
 8780        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8781            s.select_ranges(vec![0..0]);
 8782        });
 8783    }
 8784
 8785    pub fn select_to_beginning(
 8786        &mut self,
 8787        _: &SelectToBeginning,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        let mut selection = self.selections.last::<Point>(cx);
 8792        selection.set_head(Point::zero(), SelectionGoal::None);
 8793
 8794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8795            s.select(vec![selection]);
 8796        });
 8797    }
 8798
 8799    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8800        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8801            cx.propagate();
 8802            return;
 8803        }
 8804
 8805        let cursor = self.buffer.read(cx).read(cx).len();
 8806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8807            s.select_ranges(vec![cursor..cursor])
 8808        });
 8809    }
 8810
 8811    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8812        self.nav_history = nav_history;
 8813    }
 8814
 8815    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8816        self.nav_history.as_ref()
 8817    }
 8818
 8819    fn push_to_nav_history(
 8820        &mut self,
 8821        cursor_anchor: Anchor,
 8822        new_position: Option<Point>,
 8823        cx: &mut Context<Self>,
 8824    ) {
 8825        if let Some(nav_history) = self.nav_history.as_mut() {
 8826            let buffer = self.buffer.read(cx).read(cx);
 8827            let cursor_position = cursor_anchor.to_point(&buffer);
 8828            let scroll_state = self.scroll_manager.anchor();
 8829            let scroll_top_row = scroll_state.top_row(&buffer);
 8830            drop(buffer);
 8831
 8832            if let Some(new_position) = new_position {
 8833                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8834                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8835                    return;
 8836                }
 8837            }
 8838
 8839            nav_history.push(
 8840                Some(NavigationData {
 8841                    cursor_anchor,
 8842                    cursor_position,
 8843                    scroll_anchor: scroll_state,
 8844                    scroll_top_row,
 8845                }),
 8846                cx,
 8847            );
 8848        }
 8849    }
 8850
 8851    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8852        let buffer = self.buffer.read(cx).snapshot(cx);
 8853        let mut selection = self.selections.first::<usize>(cx);
 8854        selection.set_head(buffer.len(), SelectionGoal::None);
 8855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8856            s.select(vec![selection]);
 8857        });
 8858    }
 8859
 8860    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8861        let end = self.buffer.read(cx).read(cx).len();
 8862        self.change_selections(None, window, cx, |s| {
 8863            s.select_ranges(vec![0..end]);
 8864        });
 8865    }
 8866
 8867    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8868        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8869        let mut selections = self.selections.all::<Point>(cx);
 8870        let max_point = display_map.buffer_snapshot.max_point();
 8871        for selection in &mut selections {
 8872            let rows = selection.spanned_rows(true, &display_map);
 8873            selection.start = Point::new(rows.start.0, 0);
 8874            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8875            selection.reversed = false;
 8876        }
 8877        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8878            s.select(selections);
 8879        });
 8880    }
 8881
 8882    pub fn split_selection_into_lines(
 8883        &mut self,
 8884        _: &SplitSelectionIntoLines,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887    ) {
 8888        let mut to_unfold = Vec::new();
 8889        let mut new_selection_ranges = Vec::new();
 8890        {
 8891            let selections = self.selections.all::<Point>(cx);
 8892            let buffer = self.buffer.read(cx).read(cx);
 8893            for selection in selections {
 8894                for row in selection.start.row..selection.end.row {
 8895                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8896                    new_selection_ranges.push(cursor..cursor);
 8897                }
 8898                new_selection_ranges.push(selection.end..selection.end);
 8899                to_unfold.push(selection.start..selection.end);
 8900            }
 8901        }
 8902        self.unfold_ranges(&to_unfold, true, true, cx);
 8903        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8904            s.select_ranges(new_selection_ranges);
 8905        });
 8906    }
 8907
 8908    pub fn add_selection_above(
 8909        &mut self,
 8910        _: &AddSelectionAbove,
 8911        window: &mut Window,
 8912        cx: &mut Context<Self>,
 8913    ) {
 8914        self.add_selection(true, window, cx);
 8915    }
 8916
 8917    pub fn add_selection_below(
 8918        &mut self,
 8919        _: &AddSelectionBelow,
 8920        window: &mut Window,
 8921        cx: &mut Context<Self>,
 8922    ) {
 8923        self.add_selection(false, window, cx);
 8924    }
 8925
 8926    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8927        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8928        let mut selections = self.selections.all::<Point>(cx);
 8929        let text_layout_details = self.text_layout_details(window);
 8930        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8931            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8932            let range = oldest_selection.display_range(&display_map).sorted();
 8933
 8934            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8935            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8936            let positions = start_x.min(end_x)..start_x.max(end_x);
 8937
 8938            selections.clear();
 8939            let mut stack = Vec::new();
 8940            for row in range.start.row().0..=range.end.row().0 {
 8941                if let Some(selection) = self.selections.build_columnar_selection(
 8942                    &display_map,
 8943                    DisplayRow(row),
 8944                    &positions,
 8945                    oldest_selection.reversed,
 8946                    &text_layout_details,
 8947                ) {
 8948                    stack.push(selection.id);
 8949                    selections.push(selection);
 8950                }
 8951            }
 8952
 8953            if above {
 8954                stack.reverse();
 8955            }
 8956
 8957            AddSelectionsState { above, stack }
 8958        });
 8959
 8960        let last_added_selection = *state.stack.last().unwrap();
 8961        let mut new_selections = Vec::new();
 8962        if above == state.above {
 8963            let end_row = if above {
 8964                DisplayRow(0)
 8965            } else {
 8966                display_map.max_point().row()
 8967            };
 8968
 8969            'outer: for selection in selections {
 8970                if selection.id == last_added_selection {
 8971                    let range = selection.display_range(&display_map).sorted();
 8972                    debug_assert_eq!(range.start.row(), range.end.row());
 8973                    let mut row = range.start.row();
 8974                    let positions =
 8975                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8976                            px(start)..px(end)
 8977                        } else {
 8978                            let start_x =
 8979                                display_map.x_for_display_point(range.start, &text_layout_details);
 8980                            let end_x =
 8981                                display_map.x_for_display_point(range.end, &text_layout_details);
 8982                            start_x.min(end_x)..start_x.max(end_x)
 8983                        };
 8984
 8985                    while row != end_row {
 8986                        if above {
 8987                            row.0 -= 1;
 8988                        } else {
 8989                            row.0 += 1;
 8990                        }
 8991
 8992                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8993                            &display_map,
 8994                            row,
 8995                            &positions,
 8996                            selection.reversed,
 8997                            &text_layout_details,
 8998                        ) {
 8999                            state.stack.push(new_selection.id);
 9000                            if above {
 9001                                new_selections.push(new_selection);
 9002                                new_selections.push(selection);
 9003                            } else {
 9004                                new_selections.push(selection);
 9005                                new_selections.push(new_selection);
 9006                            }
 9007
 9008                            continue 'outer;
 9009                        }
 9010                    }
 9011                }
 9012
 9013                new_selections.push(selection);
 9014            }
 9015        } else {
 9016            new_selections = selections;
 9017            new_selections.retain(|s| s.id != last_added_selection);
 9018            state.stack.pop();
 9019        }
 9020
 9021        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9022            s.select(new_selections);
 9023        });
 9024        if state.stack.len() > 1 {
 9025            self.add_selections_state = Some(state);
 9026        }
 9027    }
 9028
 9029    pub fn select_next_match_internal(
 9030        &mut self,
 9031        display_map: &DisplaySnapshot,
 9032        replace_newest: bool,
 9033        autoscroll: Option<Autoscroll>,
 9034        window: &mut Window,
 9035        cx: &mut Context<Self>,
 9036    ) -> Result<()> {
 9037        fn select_next_match_ranges(
 9038            this: &mut Editor,
 9039            range: Range<usize>,
 9040            replace_newest: bool,
 9041            auto_scroll: Option<Autoscroll>,
 9042            window: &mut Window,
 9043            cx: &mut Context<Editor>,
 9044        ) {
 9045            this.unfold_ranges(&[range.clone()], false, true, cx);
 9046            this.change_selections(auto_scroll, window, cx, |s| {
 9047                if replace_newest {
 9048                    s.delete(s.newest_anchor().id);
 9049                }
 9050                s.insert_range(range.clone());
 9051            });
 9052        }
 9053
 9054        let buffer = &display_map.buffer_snapshot;
 9055        let mut selections = self.selections.all::<usize>(cx);
 9056        if let Some(mut select_next_state) = self.select_next_state.take() {
 9057            let query = &select_next_state.query;
 9058            if !select_next_state.done {
 9059                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9060                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9061                let mut next_selected_range = None;
 9062
 9063                let bytes_after_last_selection =
 9064                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9065                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9066                let query_matches = query
 9067                    .stream_find_iter(bytes_after_last_selection)
 9068                    .map(|result| (last_selection.end, result))
 9069                    .chain(
 9070                        query
 9071                            .stream_find_iter(bytes_before_first_selection)
 9072                            .map(|result| (0, result)),
 9073                    );
 9074
 9075                for (start_offset, query_match) in query_matches {
 9076                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9077                    let offset_range =
 9078                        start_offset + query_match.start()..start_offset + query_match.end();
 9079                    let display_range = offset_range.start.to_display_point(display_map)
 9080                        ..offset_range.end.to_display_point(display_map);
 9081
 9082                    if !select_next_state.wordwise
 9083                        || (!movement::is_inside_word(display_map, display_range.start)
 9084                            && !movement::is_inside_word(display_map, display_range.end))
 9085                    {
 9086                        // TODO: This is n^2, because we might check all the selections
 9087                        if !selections
 9088                            .iter()
 9089                            .any(|selection| selection.range().overlaps(&offset_range))
 9090                        {
 9091                            next_selected_range = Some(offset_range);
 9092                            break;
 9093                        }
 9094                    }
 9095                }
 9096
 9097                if let Some(next_selected_range) = next_selected_range {
 9098                    select_next_match_ranges(
 9099                        self,
 9100                        next_selected_range,
 9101                        replace_newest,
 9102                        autoscroll,
 9103                        window,
 9104                        cx,
 9105                    );
 9106                } else {
 9107                    select_next_state.done = true;
 9108                }
 9109            }
 9110
 9111            self.select_next_state = Some(select_next_state);
 9112        } else {
 9113            let mut only_carets = true;
 9114            let mut same_text_selected = true;
 9115            let mut selected_text = None;
 9116
 9117            let mut selections_iter = selections.iter().peekable();
 9118            while let Some(selection) = selections_iter.next() {
 9119                if selection.start != selection.end {
 9120                    only_carets = false;
 9121                }
 9122
 9123                if same_text_selected {
 9124                    if selected_text.is_none() {
 9125                        selected_text =
 9126                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9127                    }
 9128
 9129                    if let Some(next_selection) = selections_iter.peek() {
 9130                        if next_selection.range().len() == selection.range().len() {
 9131                            let next_selected_text = buffer
 9132                                .text_for_range(next_selection.range())
 9133                                .collect::<String>();
 9134                            if Some(next_selected_text) != selected_text {
 9135                                same_text_selected = false;
 9136                                selected_text = None;
 9137                            }
 9138                        } else {
 9139                            same_text_selected = false;
 9140                            selected_text = None;
 9141                        }
 9142                    }
 9143                }
 9144            }
 9145
 9146            if only_carets {
 9147                for selection in &mut selections {
 9148                    let word_range = movement::surrounding_word(
 9149                        display_map,
 9150                        selection.start.to_display_point(display_map),
 9151                    );
 9152                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9153                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9154                    selection.goal = SelectionGoal::None;
 9155                    selection.reversed = false;
 9156                    select_next_match_ranges(
 9157                        self,
 9158                        selection.start..selection.end,
 9159                        replace_newest,
 9160                        autoscroll,
 9161                        window,
 9162                        cx,
 9163                    );
 9164                }
 9165
 9166                if selections.len() == 1 {
 9167                    let selection = selections
 9168                        .last()
 9169                        .expect("ensured that there's only one selection");
 9170                    let query = buffer
 9171                        .text_for_range(selection.start..selection.end)
 9172                        .collect::<String>();
 9173                    let is_empty = query.is_empty();
 9174                    let select_state = SelectNextState {
 9175                        query: AhoCorasick::new(&[query])?,
 9176                        wordwise: true,
 9177                        done: is_empty,
 9178                    };
 9179                    self.select_next_state = Some(select_state);
 9180                } else {
 9181                    self.select_next_state = None;
 9182                }
 9183            } else if let Some(selected_text) = selected_text {
 9184                self.select_next_state = Some(SelectNextState {
 9185                    query: AhoCorasick::new(&[selected_text])?,
 9186                    wordwise: false,
 9187                    done: false,
 9188                });
 9189                self.select_next_match_internal(
 9190                    display_map,
 9191                    replace_newest,
 9192                    autoscroll,
 9193                    window,
 9194                    cx,
 9195                )?;
 9196            }
 9197        }
 9198        Ok(())
 9199    }
 9200
 9201    pub fn select_all_matches(
 9202        &mut self,
 9203        _action: &SelectAllMatches,
 9204        window: &mut Window,
 9205        cx: &mut Context<Self>,
 9206    ) -> Result<()> {
 9207        self.push_to_selection_history();
 9208        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9209
 9210        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9211        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9212            return Ok(());
 9213        };
 9214        if select_next_state.done {
 9215            return Ok(());
 9216        }
 9217
 9218        let mut new_selections = self.selections.all::<usize>(cx);
 9219
 9220        let buffer = &display_map.buffer_snapshot;
 9221        let query_matches = select_next_state
 9222            .query
 9223            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9224
 9225        for query_match in query_matches {
 9226            let query_match = query_match.unwrap(); // can only fail due to I/O
 9227            let offset_range = query_match.start()..query_match.end();
 9228            let display_range = offset_range.start.to_display_point(&display_map)
 9229                ..offset_range.end.to_display_point(&display_map);
 9230
 9231            if !select_next_state.wordwise
 9232                || (!movement::is_inside_word(&display_map, display_range.start)
 9233                    && !movement::is_inside_word(&display_map, display_range.end))
 9234            {
 9235                self.selections.change_with(cx, |selections| {
 9236                    new_selections.push(Selection {
 9237                        id: selections.new_selection_id(),
 9238                        start: offset_range.start,
 9239                        end: offset_range.end,
 9240                        reversed: false,
 9241                        goal: SelectionGoal::None,
 9242                    });
 9243                });
 9244            }
 9245        }
 9246
 9247        new_selections.sort_by_key(|selection| selection.start);
 9248        let mut ix = 0;
 9249        while ix + 1 < new_selections.len() {
 9250            let current_selection = &new_selections[ix];
 9251            let next_selection = &new_selections[ix + 1];
 9252            if current_selection.range().overlaps(&next_selection.range()) {
 9253                if current_selection.id < next_selection.id {
 9254                    new_selections.remove(ix + 1);
 9255                } else {
 9256                    new_selections.remove(ix);
 9257                }
 9258            } else {
 9259                ix += 1;
 9260            }
 9261        }
 9262
 9263        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9264
 9265        for selection in new_selections.iter_mut() {
 9266            selection.reversed = reversed;
 9267        }
 9268
 9269        select_next_state.done = true;
 9270        self.unfold_ranges(
 9271            &new_selections
 9272                .iter()
 9273                .map(|selection| selection.range())
 9274                .collect::<Vec<_>>(),
 9275            false,
 9276            false,
 9277            cx,
 9278        );
 9279        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9280            selections.select(new_selections)
 9281        });
 9282
 9283        Ok(())
 9284    }
 9285
 9286    pub fn select_next(
 9287        &mut self,
 9288        action: &SelectNext,
 9289        window: &mut Window,
 9290        cx: &mut Context<Self>,
 9291    ) -> Result<()> {
 9292        self.push_to_selection_history();
 9293        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9294        self.select_next_match_internal(
 9295            &display_map,
 9296            action.replace_newest,
 9297            Some(Autoscroll::newest()),
 9298            window,
 9299            cx,
 9300        )?;
 9301        Ok(())
 9302    }
 9303
 9304    pub fn select_previous(
 9305        &mut self,
 9306        action: &SelectPrevious,
 9307        window: &mut Window,
 9308        cx: &mut Context<Self>,
 9309    ) -> Result<()> {
 9310        self.push_to_selection_history();
 9311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9312        let buffer = &display_map.buffer_snapshot;
 9313        let mut selections = self.selections.all::<usize>(cx);
 9314        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9315            let query = &select_prev_state.query;
 9316            if !select_prev_state.done {
 9317                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9318                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9319                let mut next_selected_range = None;
 9320                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9321                let bytes_before_last_selection =
 9322                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9323                let bytes_after_first_selection =
 9324                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9325                let query_matches = query
 9326                    .stream_find_iter(bytes_before_last_selection)
 9327                    .map(|result| (last_selection.start, result))
 9328                    .chain(
 9329                        query
 9330                            .stream_find_iter(bytes_after_first_selection)
 9331                            .map(|result| (buffer.len(), result)),
 9332                    );
 9333                for (end_offset, query_match) in query_matches {
 9334                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9335                    let offset_range =
 9336                        end_offset - query_match.end()..end_offset - query_match.start();
 9337                    let display_range = offset_range.start.to_display_point(&display_map)
 9338                        ..offset_range.end.to_display_point(&display_map);
 9339
 9340                    if !select_prev_state.wordwise
 9341                        || (!movement::is_inside_word(&display_map, display_range.start)
 9342                            && !movement::is_inside_word(&display_map, display_range.end))
 9343                    {
 9344                        next_selected_range = Some(offset_range);
 9345                        break;
 9346                    }
 9347                }
 9348
 9349                if let Some(next_selected_range) = next_selected_range {
 9350                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9351                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9352                        if action.replace_newest {
 9353                            s.delete(s.newest_anchor().id);
 9354                        }
 9355                        s.insert_range(next_selected_range);
 9356                    });
 9357                } else {
 9358                    select_prev_state.done = true;
 9359                }
 9360            }
 9361
 9362            self.select_prev_state = Some(select_prev_state);
 9363        } else {
 9364            let mut only_carets = true;
 9365            let mut same_text_selected = true;
 9366            let mut selected_text = None;
 9367
 9368            let mut selections_iter = selections.iter().peekable();
 9369            while let Some(selection) = selections_iter.next() {
 9370                if selection.start != selection.end {
 9371                    only_carets = false;
 9372                }
 9373
 9374                if same_text_selected {
 9375                    if selected_text.is_none() {
 9376                        selected_text =
 9377                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9378                    }
 9379
 9380                    if let Some(next_selection) = selections_iter.peek() {
 9381                        if next_selection.range().len() == selection.range().len() {
 9382                            let next_selected_text = buffer
 9383                                .text_for_range(next_selection.range())
 9384                                .collect::<String>();
 9385                            if Some(next_selected_text) != selected_text {
 9386                                same_text_selected = false;
 9387                                selected_text = None;
 9388                            }
 9389                        } else {
 9390                            same_text_selected = false;
 9391                            selected_text = None;
 9392                        }
 9393                    }
 9394                }
 9395            }
 9396
 9397            if only_carets {
 9398                for selection in &mut selections {
 9399                    let word_range = movement::surrounding_word(
 9400                        &display_map,
 9401                        selection.start.to_display_point(&display_map),
 9402                    );
 9403                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9404                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9405                    selection.goal = SelectionGoal::None;
 9406                    selection.reversed = false;
 9407                }
 9408                if selections.len() == 1 {
 9409                    let selection = selections
 9410                        .last()
 9411                        .expect("ensured that there's only one selection");
 9412                    let query = buffer
 9413                        .text_for_range(selection.start..selection.end)
 9414                        .collect::<String>();
 9415                    let is_empty = query.is_empty();
 9416                    let select_state = SelectNextState {
 9417                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9418                        wordwise: true,
 9419                        done: is_empty,
 9420                    };
 9421                    self.select_prev_state = Some(select_state);
 9422                } else {
 9423                    self.select_prev_state = None;
 9424                }
 9425
 9426                self.unfold_ranges(
 9427                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9428                    false,
 9429                    true,
 9430                    cx,
 9431                );
 9432                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9433                    s.select(selections);
 9434                });
 9435            } else if let Some(selected_text) = selected_text {
 9436                self.select_prev_state = Some(SelectNextState {
 9437                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9438                    wordwise: false,
 9439                    done: false,
 9440                });
 9441                self.select_previous(action, window, cx)?;
 9442            }
 9443        }
 9444        Ok(())
 9445    }
 9446
 9447    pub fn toggle_comments(
 9448        &mut self,
 9449        action: &ToggleComments,
 9450        window: &mut Window,
 9451        cx: &mut Context<Self>,
 9452    ) {
 9453        if self.read_only(cx) {
 9454            return;
 9455        }
 9456        let text_layout_details = &self.text_layout_details(window);
 9457        self.transact(window, cx, |this, window, cx| {
 9458            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9459            let mut edits = Vec::new();
 9460            let mut selection_edit_ranges = Vec::new();
 9461            let mut last_toggled_row = None;
 9462            let snapshot = this.buffer.read(cx).read(cx);
 9463            let empty_str: Arc<str> = Arc::default();
 9464            let mut suffixes_inserted = Vec::new();
 9465            let ignore_indent = action.ignore_indent;
 9466
 9467            fn comment_prefix_range(
 9468                snapshot: &MultiBufferSnapshot,
 9469                row: MultiBufferRow,
 9470                comment_prefix: &str,
 9471                comment_prefix_whitespace: &str,
 9472                ignore_indent: bool,
 9473            ) -> Range<Point> {
 9474                let indent_size = if ignore_indent {
 9475                    0
 9476                } else {
 9477                    snapshot.indent_size_for_line(row).len
 9478                };
 9479
 9480                let start = Point::new(row.0, indent_size);
 9481
 9482                let mut line_bytes = snapshot
 9483                    .bytes_in_range(start..snapshot.max_point())
 9484                    .flatten()
 9485                    .copied();
 9486
 9487                // If this line currently begins with the line comment prefix, then record
 9488                // the range containing the prefix.
 9489                if line_bytes
 9490                    .by_ref()
 9491                    .take(comment_prefix.len())
 9492                    .eq(comment_prefix.bytes())
 9493                {
 9494                    // Include any whitespace that matches the comment prefix.
 9495                    let matching_whitespace_len = line_bytes
 9496                        .zip(comment_prefix_whitespace.bytes())
 9497                        .take_while(|(a, b)| a == b)
 9498                        .count() as u32;
 9499                    let end = Point::new(
 9500                        start.row,
 9501                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9502                    );
 9503                    start..end
 9504                } else {
 9505                    start..start
 9506                }
 9507            }
 9508
 9509            fn comment_suffix_range(
 9510                snapshot: &MultiBufferSnapshot,
 9511                row: MultiBufferRow,
 9512                comment_suffix: &str,
 9513                comment_suffix_has_leading_space: bool,
 9514            ) -> Range<Point> {
 9515                let end = Point::new(row.0, snapshot.line_len(row));
 9516                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9517
 9518                let mut line_end_bytes = snapshot
 9519                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9520                    .flatten()
 9521                    .copied();
 9522
 9523                let leading_space_len = if suffix_start_column > 0
 9524                    && line_end_bytes.next() == Some(b' ')
 9525                    && comment_suffix_has_leading_space
 9526                {
 9527                    1
 9528                } else {
 9529                    0
 9530                };
 9531
 9532                // If this line currently begins with the line comment prefix, then record
 9533                // the range containing the prefix.
 9534                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9535                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9536                    start..end
 9537                } else {
 9538                    end..end
 9539                }
 9540            }
 9541
 9542            // TODO: Handle selections that cross excerpts
 9543            for selection in &mut selections {
 9544                let start_column = snapshot
 9545                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9546                    .len;
 9547                let language = if let Some(language) =
 9548                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9549                {
 9550                    language
 9551                } else {
 9552                    continue;
 9553                };
 9554
 9555                selection_edit_ranges.clear();
 9556
 9557                // If multiple selections contain a given row, avoid processing that
 9558                // row more than once.
 9559                let mut start_row = MultiBufferRow(selection.start.row);
 9560                if last_toggled_row == Some(start_row) {
 9561                    start_row = start_row.next_row();
 9562                }
 9563                let end_row =
 9564                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9565                        MultiBufferRow(selection.end.row - 1)
 9566                    } else {
 9567                        MultiBufferRow(selection.end.row)
 9568                    };
 9569                last_toggled_row = Some(end_row);
 9570
 9571                if start_row > end_row {
 9572                    continue;
 9573                }
 9574
 9575                // If the language has line comments, toggle those.
 9576                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9577
 9578                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9579                if ignore_indent {
 9580                    full_comment_prefixes = full_comment_prefixes
 9581                        .into_iter()
 9582                        .map(|s| Arc::from(s.trim_end()))
 9583                        .collect();
 9584                }
 9585
 9586                if !full_comment_prefixes.is_empty() {
 9587                    let first_prefix = full_comment_prefixes
 9588                        .first()
 9589                        .expect("prefixes is non-empty");
 9590                    let prefix_trimmed_lengths = full_comment_prefixes
 9591                        .iter()
 9592                        .map(|p| p.trim_end_matches(' ').len())
 9593                        .collect::<SmallVec<[usize; 4]>>();
 9594
 9595                    let mut all_selection_lines_are_comments = true;
 9596
 9597                    for row in start_row.0..=end_row.0 {
 9598                        let row = MultiBufferRow(row);
 9599                        if start_row < end_row && snapshot.is_line_blank(row) {
 9600                            continue;
 9601                        }
 9602
 9603                        let prefix_range = full_comment_prefixes
 9604                            .iter()
 9605                            .zip(prefix_trimmed_lengths.iter().copied())
 9606                            .map(|(prefix, trimmed_prefix_len)| {
 9607                                comment_prefix_range(
 9608                                    snapshot.deref(),
 9609                                    row,
 9610                                    &prefix[..trimmed_prefix_len],
 9611                                    &prefix[trimmed_prefix_len..],
 9612                                    ignore_indent,
 9613                                )
 9614                            })
 9615                            .max_by_key(|range| range.end.column - range.start.column)
 9616                            .expect("prefixes is non-empty");
 9617
 9618                        if prefix_range.is_empty() {
 9619                            all_selection_lines_are_comments = false;
 9620                        }
 9621
 9622                        selection_edit_ranges.push(prefix_range);
 9623                    }
 9624
 9625                    if all_selection_lines_are_comments {
 9626                        edits.extend(
 9627                            selection_edit_ranges
 9628                                .iter()
 9629                                .cloned()
 9630                                .map(|range| (range, empty_str.clone())),
 9631                        );
 9632                    } else {
 9633                        let min_column = selection_edit_ranges
 9634                            .iter()
 9635                            .map(|range| range.start.column)
 9636                            .min()
 9637                            .unwrap_or(0);
 9638                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9639                            let position = Point::new(range.start.row, min_column);
 9640                            (position..position, first_prefix.clone())
 9641                        }));
 9642                    }
 9643                } else if let Some((full_comment_prefix, comment_suffix)) =
 9644                    language.block_comment_delimiters()
 9645                {
 9646                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9647                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9648                    let prefix_range = comment_prefix_range(
 9649                        snapshot.deref(),
 9650                        start_row,
 9651                        comment_prefix,
 9652                        comment_prefix_whitespace,
 9653                        ignore_indent,
 9654                    );
 9655                    let suffix_range = comment_suffix_range(
 9656                        snapshot.deref(),
 9657                        end_row,
 9658                        comment_suffix.trim_start_matches(' '),
 9659                        comment_suffix.starts_with(' '),
 9660                    );
 9661
 9662                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9663                        edits.push((
 9664                            prefix_range.start..prefix_range.start,
 9665                            full_comment_prefix.clone(),
 9666                        ));
 9667                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9668                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9669                    } else {
 9670                        edits.push((prefix_range, empty_str.clone()));
 9671                        edits.push((suffix_range, empty_str.clone()));
 9672                    }
 9673                } else {
 9674                    continue;
 9675                }
 9676            }
 9677
 9678            drop(snapshot);
 9679            this.buffer.update(cx, |buffer, cx| {
 9680                buffer.edit(edits, None, cx);
 9681            });
 9682
 9683            // Adjust selections so that they end before any comment suffixes that
 9684            // were inserted.
 9685            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9686            let mut selections = this.selections.all::<Point>(cx);
 9687            let snapshot = this.buffer.read(cx).read(cx);
 9688            for selection in &mut selections {
 9689                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9690                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9691                        Ordering::Less => {
 9692                            suffixes_inserted.next();
 9693                            continue;
 9694                        }
 9695                        Ordering::Greater => break,
 9696                        Ordering::Equal => {
 9697                            if selection.end.column == snapshot.line_len(row) {
 9698                                if selection.is_empty() {
 9699                                    selection.start.column -= suffix_len as u32;
 9700                                }
 9701                                selection.end.column -= suffix_len as u32;
 9702                            }
 9703                            break;
 9704                        }
 9705                    }
 9706                }
 9707            }
 9708
 9709            drop(snapshot);
 9710            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9711                s.select(selections)
 9712            });
 9713
 9714            let selections = this.selections.all::<Point>(cx);
 9715            let selections_on_single_row = selections.windows(2).all(|selections| {
 9716                selections[0].start.row == selections[1].start.row
 9717                    && selections[0].end.row == selections[1].end.row
 9718                    && selections[0].start.row == selections[0].end.row
 9719            });
 9720            let selections_selecting = selections
 9721                .iter()
 9722                .any(|selection| selection.start != selection.end);
 9723            let advance_downwards = action.advance_downwards
 9724                && selections_on_single_row
 9725                && !selections_selecting
 9726                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9727
 9728            if advance_downwards {
 9729                let snapshot = this.buffer.read(cx).snapshot(cx);
 9730
 9731                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9732                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9733                        let mut point = display_point.to_point(display_snapshot);
 9734                        point.row += 1;
 9735                        point = snapshot.clip_point(point, Bias::Left);
 9736                        let display_point = point.to_display_point(display_snapshot);
 9737                        let goal = SelectionGoal::HorizontalPosition(
 9738                            display_snapshot
 9739                                .x_for_display_point(display_point, text_layout_details)
 9740                                .into(),
 9741                        );
 9742                        (display_point, goal)
 9743                    })
 9744                });
 9745            }
 9746        });
 9747    }
 9748
 9749    pub fn select_enclosing_symbol(
 9750        &mut self,
 9751        _: &SelectEnclosingSymbol,
 9752        window: &mut Window,
 9753        cx: &mut Context<Self>,
 9754    ) {
 9755        let buffer = self.buffer.read(cx).snapshot(cx);
 9756        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9757
 9758        fn update_selection(
 9759            selection: &Selection<usize>,
 9760            buffer_snap: &MultiBufferSnapshot,
 9761        ) -> Option<Selection<usize>> {
 9762            let cursor = selection.head();
 9763            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9764            for symbol in symbols.iter().rev() {
 9765                let start = symbol.range.start.to_offset(buffer_snap);
 9766                let end = symbol.range.end.to_offset(buffer_snap);
 9767                let new_range = start..end;
 9768                if start < selection.start || end > selection.end {
 9769                    return Some(Selection {
 9770                        id: selection.id,
 9771                        start: new_range.start,
 9772                        end: new_range.end,
 9773                        goal: SelectionGoal::None,
 9774                        reversed: selection.reversed,
 9775                    });
 9776                }
 9777            }
 9778            None
 9779        }
 9780
 9781        let mut selected_larger_symbol = false;
 9782        let new_selections = old_selections
 9783            .iter()
 9784            .map(|selection| match update_selection(selection, &buffer) {
 9785                Some(new_selection) => {
 9786                    if new_selection.range() != selection.range() {
 9787                        selected_larger_symbol = true;
 9788                    }
 9789                    new_selection
 9790                }
 9791                None => selection.clone(),
 9792            })
 9793            .collect::<Vec<_>>();
 9794
 9795        if selected_larger_symbol {
 9796            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9797                s.select(new_selections);
 9798            });
 9799        }
 9800    }
 9801
 9802    pub fn select_larger_syntax_node(
 9803        &mut self,
 9804        _: &SelectLargerSyntaxNode,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9809        let buffer = self.buffer.read(cx).snapshot(cx);
 9810        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9811
 9812        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9813        let mut selected_larger_node = false;
 9814        let new_selections = old_selections
 9815            .iter()
 9816            .map(|selection| {
 9817                let old_range = selection.start..selection.end;
 9818                let mut new_range = old_range.clone();
 9819                let mut new_node = None;
 9820                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9821                {
 9822                    new_node = Some(node);
 9823                    new_range = containing_range;
 9824                    if !display_map.intersects_fold(new_range.start)
 9825                        && !display_map.intersects_fold(new_range.end)
 9826                    {
 9827                        break;
 9828                    }
 9829                }
 9830
 9831                if let Some(node) = new_node {
 9832                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9833                    // nodes. Parent and grandparent are also logged because this operation will not
 9834                    // visit nodes that have the same range as their parent.
 9835                    log::info!("Node: {node:?}");
 9836                    let parent = node.parent();
 9837                    log::info!("Parent: {parent:?}");
 9838                    let grandparent = parent.and_then(|x| x.parent());
 9839                    log::info!("Grandparent: {grandparent:?}");
 9840                }
 9841
 9842                selected_larger_node |= new_range != old_range;
 9843                Selection {
 9844                    id: selection.id,
 9845                    start: new_range.start,
 9846                    end: new_range.end,
 9847                    goal: SelectionGoal::None,
 9848                    reversed: selection.reversed,
 9849                }
 9850            })
 9851            .collect::<Vec<_>>();
 9852
 9853        if selected_larger_node {
 9854            stack.push(old_selections);
 9855            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9856                s.select(new_selections);
 9857            });
 9858        }
 9859        self.select_larger_syntax_node_stack = stack;
 9860    }
 9861
 9862    pub fn select_smaller_syntax_node(
 9863        &mut self,
 9864        _: &SelectSmallerSyntaxNode,
 9865        window: &mut Window,
 9866        cx: &mut Context<Self>,
 9867    ) {
 9868        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9869        if let Some(selections) = stack.pop() {
 9870            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9871                s.select(selections.to_vec());
 9872            });
 9873        }
 9874        self.select_larger_syntax_node_stack = stack;
 9875    }
 9876
 9877    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9878        if !EditorSettings::get_global(cx).gutter.runnables {
 9879            self.clear_tasks();
 9880            return Task::ready(());
 9881        }
 9882        let project = self.project.as_ref().map(Entity::downgrade);
 9883        cx.spawn_in(window, |this, mut cx| async move {
 9884            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9885            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9886                return;
 9887            };
 9888            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9889                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9890            }) else {
 9891                return;
 9892            };
 9893
 9894            let hide_runnables = project
 9895                .update(&mut cx, |project, cx| {
 9896                    // Do not display any test indicators in non-dev server remote projects.
 9897                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9898                })
 9899                .unwrap_or(true);
 9900            if hide_runnables {
 9901                return;
 9902            }
 9903            let new_rows =
 9904                cx.background_executor()
 9905                    .spawn({
 9906                        let snapshot = display_snapshot.clone();
 9907                        async move {
 9908                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9909                        }
 9910                    })
 9911                    .await;
 9912
 9913            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9914            this.update(&mut cx, |this, _| {
 9915                this.clear_tasks();
 9916                for (key, value) in rows {
 9917                    this.insert_tasks(key, value);
 9918                }
 9919            })
 9920            .ok();
 9921        })
 9922    }
 9923    fn fetch_runnable_ranges(
 9924        snapshot: &DisplaySnapshot,
 9925        range: Range<Anchor>,
 9926    ) -> Vec<language::RunnableRange> {
 9927        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9928    }
 9929
 9930    fn runnable_rows(
 9931        project: Entity<Project>,
 9932        snapshot: DisplaySnapshot,
 9933        runnable_ranges: Vec<RunnableRange>,
 9934        mut cx: AsyncWindowContext,
 9935    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9936        runnable_ranges
 9937            .into_iter()
 9938            .filter_map(|mut runnable| {
 9939                let tasks = cx
 9940                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9941                    .ok()?;
 9942                if tasks.is_empty() {
 9943                    return None;
 9944                }
 9945
 9946                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9947
 9948                let row = snapshot
 9949                    .buffer_snapshot
 9950                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9951                    .1
 9952                    .start
 9953                    .row;
 9954
 9955                let context_range =
 9956                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9957                Some((
 9958                    (runnable.buffer_id, row),
 9959                    RunnableTasks {
 9960                        templates: tasks,
 9961                        offset: MultiBufferOffset(runnable.run_range.start),
 9962                        context_range,
 9963                        column: point.column,
 9964                        extra_variables: runnable.extra_captures,
 9965                    },
 9966                ))
 9967            })
 9968            .collect()
 9969    }
 9970
 9971    fn templates_with_tags(
 9972        project: &Entity<Project>,
 9973        runnable: &mut Runnable,
 9974        cx: &mut App,
 9975    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9976        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9977            let (worktree_id, file) = project
 9978                .buffer_for_id(runnable.buffer, cx)
 9979                .and_then(|buffer| buffer.read(cx).file())
 9980                .map(|file| (file.worktree_id(cx), file.clone()))
 9981                .unzip();
 9982
 9983            (
 9984                project.task_store().read(cx).task_inventory().cloned(),
 9985                worktree_id,
 9986                file,
 9987            )
 9988        });
 9989
 9990        let tags = mem::take(&mut runnable.tags);
 9991        let mut tags: Vec<_> = tags
 9992            .into_iter()
 9993            .flat_map(|tag| {
 9994                let tag = tag.0.clone();
 9995                inventory
 9996                    .as_ref()
 9997                    .into_iter()
 9998                    .flat_map(|inventory| {
 9999                        inventory.read(cx).list_tasks(
10000                            file.clone(),
10001                            Some(runnable.language.clone()),
10002                            worktree_id,
10003                            cx,
10004                        )
10005                    })
10006                    .filter(move |(_, template)| {
10007                        template.tags.iter().any(|source_tag| source_tag == &tag)
10008                    })
10009            })
10010            .sorted_by_key(|(kind, _)| kind.to_owned())
10011            .collect();
10012        if let Some((leading_tag_source, _)) = tags.first() {
10013            // Strongest source wins; if we have worktree tag binding, prefer that to
10014            // global and language bindings;
10015            // if we have a global binding, prefer that to language binding.
10016            let first_mismatch = tags
10017                .iter()
10018                .position(|(tag_source, _)| tag_source != leading_tag_source);
10019            if let Some(index) = first_mismatch {
10020                tags.truncate(index);
10021            }
10022        }
10023
10024        tags
10025    }
10026
10027    pub fn move_to_enclosing_bracket(
10028        &mut self,
10029        _: &MoveToEnclosingBracket,
10030        window: &mut Window,
10031        cx: &mut Context<Self>,
10032    ) {
10033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10034            s.move_offsets_with(|snapshot, selection| {
10035                let Some(enclosing_bracket_ranges) =
10036                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10037                else {
10038                    return;
10039                };
10040
10041                let mut best_length = usize::MAX;
10042                let mut best_inside = false;
10043                let mut best_in_bracket_range = false;
10044                let mut best_destination = None;
10045                for (open, close) in enclosing_bracket_ranges {
10046                    let close = close.to_inclusive();
10047                    let length = close.end() - open.start;
10048                    let inside = selection.start >= open.end && selection.end <= *close.start();
10049                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10050                        || close.contains(&selection.head());
10051
10052                    // If best is next to a bracket and current isn't, skip
10053                    if !in_bracket_range && best_in_bracket_range {
10054                        continue;
10055                    }
10056
10057                    // Prefer smaller lengths unless best is inside and current isn't
10058                    if length > best_length && (best_inside || !inside) {
10059                        continue;
10060                    }
10061
10062                    best_length = length;
10063                    best_inside = inside;
10064                    best_in_bracket_range = in_bracket_range;
10065                    best_destination = Some(
10066                        if close.contains(&selection.start) && close.contains(&selection.end) {
10067                            if inside {
10068                                open.end
10069                            } else {
10070                                open.start
10071                            }
10072                        } else if inside {
10073                            *close.start()
10074                        } else {
10075                            *close.end()
10076                        },
10077                    );
10078                }
10079
10080                if let Some(destination) = best_destination {
10081                    selection.collapse_to(destination, SelectionGoal::None);
10082                }
10083            })
10084        });
10085    }
10086
10087    pub fn undo_selection(
10088        &mut self,
10089        _: &UndoSelection,
10090        window: &mut Window,
10091        cx: &mut Context<Self>,
10092    ) {
10093        self.end_selection(window, cx);
10094        self.selection_history.mode = SelectionHistoryMode::Undoing;
10095        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10096            self.change_selections(None, window, cx, |s| {
10097                s.select_anchors(entry.selections.to_vec())
10098            });
10099            self.select_next_state = entry.select_next_state;
10100            self.select_prev_state = entry.select_prev_state;
10101            self.add_selections_state = entry.add_selections_state;
10102            self.request_autoscroll(Autoscroll::newest(), cx);
10103        }
10104        self.selection_history.mode = SelectionHistoryMode::Normal;
10105    }
10106
10107    pub fn redo_selection(
10108        &mut self,
10109        _: &RedoSelection,
10110        window: &mut Window,
10111        cx: &mut Context<Self>,
10112    ) {
10113        self.end_selection(window, cx);
10114        self.selection_history.mode = SelectionHistoryMode::Redoing;
10115        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10116            self.change_selections(None, window, cx, |s| {
10117                s.select_anchors(entry.selections.to_vec())
10118            });
10119            self.select_next_state = entry.select_next_state;
10120            self.select_prev_state = entry.select_prev_state;
10121            self.add_selections_state = entry.add_selections_state;
10122            self.request_autoscroll(Autoscroll::newest(), cx);
10123        }
10124        self.selection_history.mode = SelectionHistoryMode::Normal;
10125    }
10126
10127    pub fn expand_excerpts(
10128        &mut self,
10129        action: &ExpandExcerpts,
10130        _: &mut Window,
10131        cx: &mut Context<Self>,
10132    ) {
10133        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10134    }
10135
10136    pub fn expand_excerpts_down(
10137        &mut self,
10138        action: &ExpandExcerptsDown,
10139        _: &mut Window,
10140        cx: &mut Context<Self>,
10141    ) {
10142        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10143    }
10144
10145    pub fn expand_excerpts_up(
10146        &mut self,
10147        action: &ExpandExcerptsUp,
10148        _: &mut Window,
10149        cx: &mut Context<Self>,
10150    ) {
10151        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10152    }
10153
10154    pub fn expand_excerpts_for_direction(
10155        &mut self,
10156        lines: u32,
10157        direction: ExpandExcerptDirection,
10158
10159        cx: &mut Context<Self>,
10160    ) {
10161        let selections = self.selections.disjoint_anchors();
10162
10163        let lines = if lines == 0 {
10164            EditorSettings::get_global(cx).expand_excerpt_lines
10165        } else {
10166            lines
10167        };
10168
10169        self.buffer.update(cx, |buffer, cx| {
10170            let snapshot = buffer.snapshot(cx);
10171            let mut excerpt_ids = selections
10172                .iter()
10173                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10174                .collect::<Vec<_>>();
10175            excerpt_ids.sort();
10176            excerpt_ids.dedup();
10177            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10178        })
10179    }
10180
10181    pub fn expand_excerpt(
10182        &mut self,
10183        excerpt: ExcerptId,
10184        direction: ExpandExcerptDirection,
10185        cx: &mut Context<Self>,
10186    ) {
10187        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10188        self.buffer.update(cx, |buffer, cx| {
10189            buffer.expand_excerpts([excerpt], lines, direction, cx)
10190        })
10191    }
10192
10193    pub fn go_to_singleton_buffer_point(
10194        &mut self,
10195        point: Point,
10196        window: &mut Window,
10197        cx: &mut Context<Self>,
10198    ) {
10199        self.go_to_singleton_buffer_range(point..point, window, cx);
10200    }
10201
10202    pub fn go_to_singleton_buffer_range(
10203        &mut self,
10204        range: Range<Point>,
10205        window: &mut Window,
10206        cx: &mut Context<Self>,
10207    ) {
10208        let multibuffer = self.buffer().read(cx);
10209        let Some(buffer) = multibuffer.as_singleton() else {
10210            return;
10211        };
10212        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10213            return;
10214        };
10215        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10216            return;
10217        };
10218        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10219            s.select_anchor_ranges([start..end])
10220        });
10221    }
10222
10223    fn go_to_diagnostic(
10224        &mut self,
10225        _: &GoToDiagnostic,
10226        window: &mut Window,
10227        cx: &mut Context<Self>,
10228    ) {
10229        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10230    }
10231
10232    fn go_to_prev_diagnostic(
10233        &mut self,
10234        _: &GoToPrevDiagnostic,
10235        window: &mut Window,
10236        cx: &mut Context<Self>,
10237    ) {
10238        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10239    }
10240
10241    pub fn go_to_diagnostic_impl(
10242        &mut self,
10243        direction: Direction,
10244        window: &mut Window,
10245        cx: &mut Context<Self>,
10246    ) {
10247        let buffer = self.buffer.read(cx).snapshot(cx);
10248        let selection = self.selections.newest::<usize>(cx);
10249
10250        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10251        if direction == Direction::Next {
10252            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10253                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10254                    return;
10255                };
10256                self.activate_diagnostics(
10257                    buffer_id,
10258                    popover.local_diagnostic.diagnostic.group_id,
10259                    window,
10260                    cx,
10261                );
10262                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10263                    let primary_range_start = active_diagnostics.primary_range.start;
10264                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10265                        let mut new_selection = s.newest_anchor().clone();
10266                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10267                        s.select_anchors(vec![new_selection.clone()]);
10268                    });
10269                    self.refresh_inline_completion(false, true, window, cx);
10270                }
10271                return;
10272            }
10273        }
10274
10275        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10276            active_diagnostics
10277                .primary_range
10278                .to_offset(&buffer)
10279                .to_inclusive()
10280        });
10281        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10282            if active_primary_range.contains(&selection.head()) {
10283                *active_primary_range.start()
10284            } else {
10285                selection.head()
10286            }
10287        } else {
10288            selection.head()
10289        };
10290        let snapshot = self.snapshot(window, cx);
10291        loop {
10292            let mut diagnostics;
10293            if direction == Direction::Prev {
10294                diagnostics = buffer
10295                    .diagnostics_in_range::<usize>(0..search_start)
10296                    .collect::<Vec<_>>();
10297                diagnostics.reverse();
10298            } else {
10299                diagnostics = buffer
10300                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10301                    .collect::<Vec<_>>();
10302            };
10303            let group = diagnostics
10304                .into_iter()
10305                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10306                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10307                // be sorted in a stable way
10308                // skip until we are at current active diagnostic, if it exists
10309                .skip_while(|entry| {
10310                    let is_in_range = match direction {
10311                        Direction::Prev => entry.range.end > search_start,
10312                        Direction::Next => entry.range.start < search_start,
10313                    };
10314                    is_in_range
10315                        && self
10316                            .active_diagnostics
10317                            .as_ref()
10318                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10319                })
10320                .find_map(|entry| {
10321                    if entry.diagnostic.is_primary
10322                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10323                        && entry.range.start != entry.range.end
10324                        // if we match with the active diagnostic, skip it
10325                        && Some(entry.diagnostic.group_id)
10326                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10327                    {
10328                        Some((entry.range, entry.diagnostic.group_id))
10329                    } else {
10330                        None
10331                    }
10332                });
10333
10334            if let Some((primary_range, group_id)) = group {
10335                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10336                    return;
10337                };
10338                self.activate_diagnostics(buffer_id, group_id, window, cx);
10339                if self.active_diagnostics.is_some() {
10340                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10341                        s.select(vec![Selection {
10342                            id: selection.id,
10343                            start: primary_range.start,
10344                            end: primary_range.start,
10345                            reversed: false,
10346                            goal: SelectionGoal::None,
10347                        }]);
10348                    });
10349                    self.refresh_inline_completion(false, true, window, cx);
10350                }
10351                break;
10352            } else {
10353                // Cycle around to the start of the buffer, potentially moving back to the start of
10354                // the currently active diagnostic.
10355                active_primary_range.take();
10356                if direction == Direction::Prev {
10357                    if search_start == buffer.len() {
10358                        break;
10359                    } else {
10360                        search_start = buffer.len();
10361                    }
10362                } else if search_start == 0 {
10363                    break;
10364                } else {
10365                    search_start = 0;
10366                }
10367            }
10368        }
10369    }
10370
10371    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10372        let snapshot = self.snapshot(window, cx);
10373        let selection = self.selections.newest::<Point>(cx);
10374        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10375    }
10376
10377    fn go_to_hunk_after_position(
10378        &mut self,
10379        snapshot: &EditorSnapshot,
10380        position: Point,
10381        window: &mut Window,
10382        cx: &mut Context<Editor>,
10383    ) -> Option<MultiBufferDiffHunk> {
10384        let mut hunk = snapshot
10385            .buffer_snapshot
10386            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10387            .find(|hunk| hunk.row_range.start.0 > position.row);
10388        if hunk.is_none() {
10389            hunk = snapshot
10390                .buffer_snapshot
10391                .diff_hunks_in_range(Point::zero()..position)
10392                .find(|hunk| hunk.row_range.end.0 < position.row)
10393        }
10394        if let Some(hunk) = &hunk {
10395            let destination = Point::new(hunk.row_range.start.0, 0);
10396            self.unfold_ranges(&[destination..destination], false, false, cx);
10397            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10398                s.select_ranges(vec![destination..destination]);
10399            });
10400        }
10401
10402        hunk
10403    }
10404
10405    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10406        let snapshot = self.snapshot(window, cx);
10407        let selection = self.selections.newest::<Point>(cx);
10408        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10409    }
10410
10411    fn go_to_hunk_before_position(
10412        &mut self,
10413        snapshot: &EditorSnapshot,
10414        position: Point,
10415        window: &mut Window,
10416        cx: &mut Context<Editor>,
10417    ) -> Option<MultiBufferDiffHunk> {
10418        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10419        if hunk.is_none() {
10420            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10421        }
10422        if let Some(hunk) = &hunk {
10423            let destination = Point::new(hunk.row_range.start.0, 0);
10424            self.unfold_ranges(&[destination..destination], false, false, cx);
10425            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10426                s.select_ranges(vec![destination..destination]);
10427            });
10428        }
10429
10430        hunk
10431    }
10432
10433    pub fn go_to_definition(
10434        &mut self,
10435        _: &GoToDefinition,
10436        window: &mut Window,
10437        cx: &mut Context<Self>,
10438    ) -> Task<Result<Navigated>> {
10439        let definition =
10440            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10441        cx.spawn_in(window, |editor, mut cx| async move {
10442            if definition.await? == Navigated::Yes {
10443                return Ok(Navigated::Yes);
10444            }
10445            match editor.update_in(&mut cx, |editor, window, cx| {
10446                editor.find_all_references(&FindAllReferences, window, cx)
10447            })? {
10448                Some(references) => references.await,
10449                None => Ok(Navigated::No),
10450            }
10451        })
10452    }
10453
10454    pub fn go_to_declaration(
10455        &mut self,
10456        _: &GoToDeclaration,
10457        window: &mut Window,
10458        cx: &mut Context<Self>,
10459    ) -> Task<Result<Navigated>> {
10460        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10461    }
10462
10463    pub fn go_to_declaration_split(
10464        &mut self,
10465        _: &GoToDeclaration,
10466        window: &mut Window,
10467        cx: &mut Context<Self>,
10468    ) -> Task<Result<Navigated>> {
10469        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10470    }
10471
10472    pub fn go_to_implementation(
10473        &mut self,
10474        _: &GoToImplementation,
10475        window: &mut Window,
10476        cx: &mut Context<Self>,
10477    ) -> Task<Result<Navigated>> {
10478        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10479    }
10480
10481    pub fn go_to_implementation_split(
10482        &mut self,
10483        _: &GoToImplementationSplit,
10484        window: &mut Window,
10485        cx: &mut Context<Self>,
10486    ) -> Task<Result<Navigated>> {
10487        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10488    }
10489
10490    pub fn go_to_type_definition(
10491        &mut self,
10492        _: &GoToTypeDefinition,
10493        window: &mut Window,
10494        cx: &mut Context<Self>,
10495    ) -> Task<Result<Navigated>> {
10496        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10497    }
10498
10499    pub fn go_to_definition_split(
10500        &mut self,
10501        _: &GoToDefinitionSplit,
10502        window: &mut Window,
10503        cx: &mut Context<Self>,
10504    ) -> Task<Result<Navigated>> {
10505        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10506    }
10507
10508    pub fn go_to_type_definition_split(
10509        &mut self,
10510        _: &GoToTypeDefinitionSplit,
10511        window: &mut Window,
10512        cx: &mut Context<Self>,
10513    ) -> Task<Result<Navigated>> {
10514        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10515    }
10516
10517    fn go_to_definition_of_kind(
10518        &mut self,
10519        kind: GotoDefinitionKind,
10520        split: bool,
10521        window: &mut Window,
10522        cx: &mut Context<Self>,
10523    ) -> Task<Result<Navigated>> {
10524        let Some(provider) = self.semantics_provider.clone() else {
10525            return Task::ready(Ok(Navigated::No));
10526        };
10527        let head = self.selections.newest::<usize>(cx).head();
10528        let buffer = self.buffer.read(cx);
10529        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10530            text_anchor
10531        } else {
10532            return Task::ready(Ok(Navigated::No));
10533        };
10534
10535        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10536            return Task::ready(Ok(Navigated::No));
10537        };
10538
10539        cx.spawn_in(window, |editor, mut cx| async move {
10540            let definitions = definitions.await?;
10541            let navigated = editor
10542                .update_in(&mut cx, |editor, window, cx| {
10543                    editor.navigate_to_hover_links(
10544                        Some(kind),
10545                        definitions
10546                            .into_iter()
10547                            .filter(|location| {
10548                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10549                            })
10550                            .map(HoverLink::Text)
10551                            .collect::<Vec<_>>(),
10552                        split,
10553                        window,
10554                        cx,
10555                    )
10556                })?
10557                .await?;
10558            anyhow::Ok(navigated)
10559        })
10560    }
10561
10562    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10563        let selection = self.selections.newest_anchor();
10564        let head = selection.head();
10565        let tail = selection.tail();
10566
10567        let Some((buffer, start_position)) =
10568            self.buffer.read(cx).text_anchor_for_position(head, cx)
10569        else {
10570            return;
10571        };
10572
10573        let end_position = if head != tail {
10574            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10575                return;
10576            };
10577            Some(pos)
10578        } else {
10579            None
10580        };
10581
10582        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10583            let url = if let Some(end_pos) = end_position {
10584                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10585            } else {
10586                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10587            };
10588
10589            if let Some(url) = url {
10590                editor.update(&mut cx, |_, cx| {
10591                    cx.open_url(&url);
10592                })
10593            } else {
10594                Ok(())
10595            }
10596        });
10597
10598        url_finder.detach();
10599    }
10600
10601    pub fn open_selected_filename(
10602        &mut self,
10603        _: &OpenSelectedFilename,
10604        window: &mut Window,
10605        cx: &mut Context<Self>,
10606    ) {
10607        let Some(workspace) = self.workspace() else {
10608            return;
10609        };
10610
10611        let position = self.selections.newest_anchor().head();
10612
10613        let Some((buffer, buffer_position)) =
10614            self.buffer.read(cx).text_anchor_for_position(position, cx)
10615        else {
10616            return;
10617        };
10618
10619        let project = self.project.clone();
10620
10621        cx.spawn_in(window, |_, mut cx| async move {
10622            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10623
10624            if let Some((_, path)) = result {
10625                workspace
10626                    .update_in(&mut cx, |workspace, window, cx| {
10627                        workspace.open_resolved_path(path, window, cx)
10628                    })?
10629                    .await?;
10630            }
10631            anyhow::Ok(())
10632        })
10633        .detach();
10634    }
10635
10636    pub(crate) fn navigate_to_hover_links(
10637        &mut self,
10638        kind: Option<GotoDefinitionKind>,
10639        mut definitions: Vec<HoverLink>,
10640        split: bool,
10641        window: &mut Window,
10642        cx: &mut Context<Editor>,
10643    ) -> Task<Result<Navigated>> {
10644        // If there is one definition, just open it directly
10645        if definitions.len() == 1 {
10646            let definition = definitions.pop().unwrap();
10647
10648            enum TargetTaskResult {
10649                Location(Option<Location>),
10650                AlreadyNavigated,
10651            }
10652
10653            let target_task = match definition {
10654                HoverLink::Text(link) => {
10655                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10656                }
10657                HoverLink::InlayHint(lsp_location, server_id) => {
10658                    let computation =
10659                        self.compute_target_location(lsp_location, server_id, window, cx);
10660                    cx.background_executor().spawn(async move {
10661                        let location = computation.await?;
10662                        Ok(TargetTaskResult::Location(location))
10663                    })
10664                }
10665                HoverLink::Url(url) => {
10666                    cx.open_url(&url);
10667                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10668                }
10669                HoverLink::File(path) => {
10670                    if let Some(workspace) = self.workspace() {
10671                        cx.spawn_in(window, |_, mut cx| async move {
10672                            workspace
10673                                .update_in(&mut cx, |workspace, window, cx| {
10674                                    workspace.open_resolved_path(path, window, cx)
10675                                })?
10676                                .await
10677                                .map(|_| TargetTaskResult::AlreadyNavigated)
10678                        })
10679                    } else {
10680                        Task::ready(Ok(TargetTaskResult::Location(None)))
10681                    }
10682                }
10683            };
10684            cx.spawn_in(window, |editor, mut cx| async move {
10685                let target = match target_task.await.context("target resolution task")? {
10686                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10687                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10688                    TargetTaskResult::Location(Some(target)) => target,
10689                };
10690
10691                editor.update_in(&mut cx, |editor, window, cx| {
10692                    let Some(workspace) = editor.workspace() else {
10693                        return Navigated::No;
10694                    };
10695                    let pane = workspace.read(cx).active_pane().clone();
10696
10697                    let range = target.range.to_point(target.buffer.read(cx));
10698                    let range = editor.range_for_match(&range);
10699                    let range = collapse_multiline_range(range);
10700
10701                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10702                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10703                    } else {
10704                        window.defer(cx, move |window, cx| {
10705                            let target_editor: Entity<Self> =
10706                                workspace.update(cx, |workspace, cx| {
10707                                    let pane = if split {
10708                                        workspace.adjacent_pane(window, cx)
10709                                    } else {
10710                                        workspace.active_pane().clone()
10711                                    };
10712
10713                                    workspace.open_project_item(
10714                                        pane,
10715                                        target.buffer.clone(),
10716                                        true,
10717                                        true,
10718                                        window,
10719                                        cx,
10720                                    )
10721                                });
10722                            target_editor.update(cx, |target_editor, cx| {
10723                                // When selecting a definition in a different buffer, disable the nav history
10724                                // to avoid creating a history entry at the previous cursor location.
10725                                pane.update(cx, |pane, _| pane.disable_history());
10726                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10727                                pane.update(cx, |pane, _| pane.enable_history());
10728                            });
10729                        });
10730                    }
10731                    Navigated::Yes
10732                })
10733            })
10734        } else if !definitions.is_empty() {
10735            cx.spawn_in(window, |editor, mut cx| async move {
10736                let (title, location_tasks, workspace) = editor
10737                    .update_in(&mut cx, |editor, window, cx| {
10738                        let tab_kind = match kind {
10739                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10740                            _ => "Definitions",
10741                        };
10742                        let title = definitions
10743                            .iter()
10744                            .find_map(|definition| match definition {
10745                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10746                                    let buffer = origin.buffer.read(cx);
10747                                    format!(
10748                                        "{} for {}",
10749                                        tab_kind,
10750                                        buffer
10751                                            .text_for_range(origin.range.clone())
10752                                            .collect::<String>()
10753                                    )
10754                                }),
10755                                HoverLink::InlayHint(_, _) => None,
10756                                HoverLink::Url(_) => None,
10757                                HoverLink::File(_) => None,
10758                            })
10759                            .unwrap_or(tab_kind.to_string());
10760                        let location_tasks = definitions
10761                            .into_iter()
10762                            .map(|definition| match definition {
10763                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10764                                HoverLink::InlayHint(lsp_location, server_id) => editor
10765                                    .compute_target_location(lsp_location, server_id, window, cx),
10766                                HoverLink::Url(_) => Task::ready(Ok(None)),
10767                                HoverLink::File(_) => Task::ready(Ok(None)),
10768                            })
10769                            .collect::<Vec<_>>();
10770                        (title, location_tasks, editor.workspace().clone())
10771                    })
10772                    .context("location tasks preparation")?;
10773
10774                let locations = future::join_all(location_tasks)
10775                    .await
10776                    .into_iter()
10777                    .filter_map(|location| location.transpose())
10778                    .collect::<Result<_>>()
10779                    .context("location tasks")?;
10780
10781                let Some(workspace) = workspace else {
10782                    return Ok(Navigated::No);
10783                };
10784                let opened = workspace
10785                    .update_in(&mut cx, |workspace, window, cx| {
10786                        Self::open_locations_in_multibuffer(
10787                            workspace,
10788                            locations,
10789                            title,
10790                            split,
10791                            MultibufferSelectionMode::First,
10792                            window,
10793                            cx,
10794                        )
10795                    })
10796                    .ok();
10797
10798                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10799            })
10800        } else {
10801            Task::ready(Ok(Navigated::No))
10802        }
10803    }
10804
10805    fn compute_target_location(
10806        &self,
10807        lsp_location: lsp::Location,
10808        server_id: LanguageServerId,
10809        window: &mut Window,
10810        cx: &mut Context<Self>,
10811    ) -> Task<anyhow::Result<Option<Location>>> {
10812        let Some(project) = self.project.clone() else {
10813            return Task::ready(Ok(None));
10814        };
10815
10816        cx.spawn_in(window, move |editor, mut cx| async move {
10817            let location_task = editor.update(&mut cx, |_, cx| {
10818                project.update(cx, |project, cx| {
10819                    let language_server_name = project
10820                        .language_server_statuses(cx)
10821                        .find(|(id, _)| server_id == *id)
10822                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10823                    language_server_name.map(|language_server_name| {
10824                        project.open_local_buffer_via_lsp(
10825                            lsp_location.uri.clone(),
10826                            server_id,
10827                            language_server_name,
10828                            cx,
10829                        )
10830                    })
10831                })
10832            })?;
10833            let location = match location_task {
10834                Some(task) => Some({
10835                    let target_buffer_handle = task.await.context("open local buffer")?;
10836                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10837                        let target_start = target_buffer
10838                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10839                        let target_end = target_buffer
10840                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10841                        target_buffer.anchor_after(target_start)
10842                            ..target_buffer.anchor_before(target_end)
10843                    })?;
10844                    Location {
10845                        buffer: target_buffer_handle,
10846                        range,
10847                    }
10848                }),
10849                None => None,
10850            };
10851            Ok(location)
10852        })
10853    }
10854
10855    pub fn find_all_references(
10856        &mut self,
10857        _: &FindAllReferences,
10858        window: &mut Window,
10859        cx: &mut Context<Self>,
10860    ) -> Option<Task<Result<Navigated>>> {
10861        let selection = self.selections.newest::<usize>(cx);
10862        let multi_buffer = self.buffer.read(cx);
10863        let head = selection.head();
10864
10865        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10866        let head_anchor = multi_buffer_snapshot.anchor_at(
10867            head,
10868            if head < selection.tail() {
10869                Bias::Right
10870            } else {
10871                Bias::Left
10872            },
10873        );
10874
10875        match self
10876            .find_all_references_task_sources
10877            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10878        {
10879            Ok(_) => {
10880                log::info!(
10881                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10882                );
10883                return None;
10884            }
10885            Err(i) => {
10886                self.find_all_references_task_sources.insert(i, head_anchor);
10887            }
10888        }
10889
10890        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10891        let workspace = self.workspace()?;
10892        let project = workspace.read(cx).project().clone();
10893        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10894        Some(cx.spawn_in(window, |editor, mut cx| async move {
10895            let _cleanup = defer({
10896                let mut cx = cx.clone();
10897                move || {
10898                    let _ = editor.update(&mut cx, |editor, _| {
10899                        if let Ok(i) =
10900                            editor
10901                                .find_all_references_task_sources
10902                                .binary_search_by(|anchor| {
10903                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10904                                })
10905                        {
10906                            editor.find_all_references_task_sources.remove(i);
10907                        }
10908                    });
10909                }
10910            });
10911
10912            let locations = references.await?;
10913            if locations.is_empty() {
10914                return anyhow::Ok(Navigated::No);
10915            }
10916
10917            workspace.update_in(&mut cx, |workspace, window, cx| {
10918                let title = locations
10919                    .first()
10920                    .as_ref()
10921                    .map(|location| {
10922                        let buffer = location.buffer.read(cx);
10923                        format!(
10924                            "References to `{}`",
10925                            buffer
10926                                .text_for_range(location.range.clone())
10927                                .collect::<String>()
10928                        )
10929                    })
10930                    .unwrap();
10931                Self::open_locations_in_multibuffer(
10932                    workspace,
10933                    locations,
10934                    title,
10935                    false,
10936                    MultibufferSelectionMode::First,
10937                    window,
10938                    cx,
10939                );
10940                Navigated::Yes
10941            })
10942        }))
10943    }
10944
10945    /// Opens a multibuffer with the given project locations in it
10946    pub fn open_locations_in_multibuffer(
10947        workspace: &mut Workspace,
10948        mut locations: Vec<Location>,
10949        title: String,
10950        split: bool,
10951        multibuffer_selection_mode: MultibufferSelectionMode,
10952        window: &mut Window,
10953        cx: &mut Context<Workspace>,
10954    ) {
10955        // If there are multiple definitions, open them in a multibuffer
10956        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10957        let mut locations = locations.into_iter().peekable();
10958        let mut ranges = Vec::new();
10959        let capability = workspace.project().read(cx).capability();
10960
10961        let excerpt_buffer = cx.new(|cx| {
10962            let mut multibuffer = MultiBuffer::new(capability);
10963            while let Some(location) = locations.next() {
10964                let buffer = location.buffer.read(cx);
10965                let mut ranges_for_buffer = Vec::new();
10966                let range = location.range.to_offset(buffer);
10967                ranges_for_buffer.push(range.clone());
10968
10969                while let Some(next_location) = locations.peek() {
10970                    if next_location.buffer == location.buffer {
10971                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10972                        locations.next();
10973                    } else {
10974                        break;
10975                    }
10976                }
10977
10978                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10979                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10980                    location.buffer.clone(),
10981                    ranges_for_buffer,
10982                    DEFAULT_MULTIBUFFER_CONTEXT,
10983                    cx,
10984                ))
10985            }
10986
10987            multibuffer.with_title(title)
10988        });
10989
10990        let editor = cx.new(|cx| {
10991            Editor::for_multibuffer(
10992                excerpt_buffer,
10993                Some(workspace.project().clone()),
10994                true,
10995                window,
10996                cx,
10997            )
10998        });
10999        editor.update(cx, |editor, cx| {
11000            match multibuffer_selection_mode {
11001                MultibufferSelectionMode::First => {
11002                    if let Some(first_range) = ranges.first() {
11003                        editor.change_selections(None, window, cx, |selections| {
11004                            selections.clear_disjoint();
11005                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11006                        });
11007                    }
11008                    editor.highlight_background::<Self>(
11009                        &ranges,
11010                        |theme| theme.editor_highlighted_line_background,
11011                        cx,
11012                    );
11013                }
11014                MultibufferSelectionMode::All => {
11015                    editor.change_selections(None, window, cx, |selections| {
11016                        selections.clear_disjoint();
11017                        selections.select_anchor_ranges(ranges);
11018                    });
11019                }
11020            }
11021            editor.register_buffers_with_language_servers(cx);
11022        });
11023
11024        let item = Box::new(editor);
11025        let item_id = item.item_id();
11026
11027        if split {
11028            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11029        } else {
11030            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11031                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11032                    pane.close_current_preview_item(window, cx)
11033                } else {
11034                    None
11035                }
11036            });
11037            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11038        }
11039        workspace.active_pane().update(cx, |pane, cx| {
11040            pane.set_preview_item_id(Some(item_id), cx);
11041        });
11042    }
11043
11044    pub fn rename(
11045        &mut self,
11046        _: &Rename,
11047        window: &mut Window,
11048        cx: &mut Context<Self>,
11049    ) -> Option<Task<Result<()>>> {
11050        use language::ToOffset as _;
11051
11052        let provider = self.semantics_provider.clone()?;
11053        let selection = self.selections.newest_anchor().clone();
11054        let (cursor_buffer, cursor_buffer_position) = self
11055            .buffer
11056            .read(cx)
11057            .text_anchor_for_position(selection.head(), cx)?;
11058        let (tail_buffer, cursor_buffer_position_end) = self
11059            .buffer
11060            .read(cx)
11061            .text_anchor_for_position(selection.tail(), cx)?;
11062        if tail_buffer != cursor_buffer {
11063            return None;
11064        }
11065
11066        let snapshot = cursor_buffer.read(cx).snapshot();
11067        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11068        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11069        let prepare_rename = provider
11070            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11071            .unwrap_or_else(|| Task::ready(Ok(None)));
11072        drop(snapshot);
11073
11074        Some(cx.spawn_in(window, |this, mut cx| async move {
11075            let rename_range = if let Some(range) = prepare_rename.await? {
11076                Some(range)
11077            } else {
11078                this.update(&mut cx, |this, cx| {
11079                    let buffer = this.buffer.read(cx).snapshot(cx);
11080                    let mut buffer_highlights = this
11081                        .document_highlights_for_position(selection.head(), &buffer)
11082                        .filter(|highlight| {
11083                            highlight.start.excerpt_id == selection.head().excerpt_id
11084                                && highlight.end.excerpt_id == selection.head().excerpt_id
11085                        });
11086                    buffer_highlights
11087                        .next()
11088                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11089                })?
11090            };
11091            if let Some(rename_range) = rename_range {
11092                this.update_in(&mut cx, |this, window, cx| {
11093                    let snapshot = cursor_buffer.read(cx).snapshot();
11094                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11095                    let cursor_offset_in_rename_range =
11096                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11097                    let cursor_offset_in_rename_range_end =
11098                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11099
11100                    this.take_rename(false, window, cx);
11101                    let buffer = this.buffer.read(cx).read(cx);
11102                    let cursor_offset = selection.head().to_offset(&buffer);
11103                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11104                    let rename_end = rename_start + rename_buffer_range.len();
11105                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11106                    let mut old_highlight_id = None;
11107                    let old_name: Arc<str> = buffer
11108                        .chunks(rename_start..rename_end, true)
11109                        .map(|chunk| {
11110                            if old_highlight_id.is_none() {
11111                                old_highlight_id = chunk.syntax_highlight_id;
11112                            }
11113                            chunk.text
11114                        })
11115                        .collect::<String>()
11116                        .into();
11117
11118                    drop(buffer);
11119
11120                    // Position the selection in the rename editor so that it matches the current selection.
11121                    this.show_local_selections = false;
11122                    let rename_editor = cx.new(|cx| {
11123                        let mut editor = Editor::single_line(window, cx);
11124                        editor.buffer.update(cx, |buffer, cx| {
11125                            buffer.edit([(0..0, old_name.clone())], None, cx)
11126                        });
11127                        let rename_selection_range = match cursor_offset_in_rename_range
11128                            .cmp(&cursor_offset_in_rename_range_end)
11129                        {
11130                            Ordering::Equal => {
11131                                editor.select_all(&SelectAll, window, cx);
11132                                return editor;
11133                            }
11134                            Ordering::Less => {
11135                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11136                            }
11137                            Ordering::Greater => {
11138                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11139                            }
11140                        };
11141                        if rename_selection_range.end > old_name.len() {
11142                            editor.select_all(&SelectAll, window, cx);
11143                        } else {
11144                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11145                                s.select_ranges([rename_selection_range]);
11146                            });
11147                        }
11148                        editor
11149                    });
11150                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11151                        if e == &EditorEvent::Focused {
11152                            cx.emit(EditorEvent::FocusedIn)
11153                        }
11154                    })
11155                    .detach();
11156
11157                    let write_highlights =
11158                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11159                    let read_highlights =
11160                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11161                    let ranges = write_highlights
11162                        .iter()
11163                        .flat_map(|(_, ranges)| ranges.iter())
11164                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11165                        .cloned()
11166                        .collect();
11167
11168                    this.highlight_text::<Rename>(
11169                        ranges,
11170                        HighlightStyle {
11171                            fade_out: Some(0.6),
11172                            ..Default::default()
11173                        },
11174                        cx,
11175                    );
11176                    let rename_focus_handle = rename_editor.focus_handle(cx);
11177                    window.focus(&rename_focus_handle);
11178                    let block_id = this.insert_blocks(
11179                        [BlockProperties {
11180                            style: BlockStyle::Flex,
11181                            placement: BlockPlacement::Below(range.start),
11182                            height: 1,
11183                            render: Arc::new({
11184                                let rename_editor = rename_editor.clone();
11185                                move |cx: &mut BlockContext| {
11186                                    let mut text_style = cx.editor_style.text.clone();
11187                                    if let Some(highlight_style) = old_highlight_id
11188                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11189                                    {
11190                                        text_style = text_style.highlight(highlight_style);
11191                                    }
11192                                    div()
11193                                        .block_mouse_down()
11194                                        .pl(cx.anchor_x)
11195                                        .child(EditorElement::new(
11196                                            &rename_editor,
11197                                            EditorStyle {
11198                                                background: cx.theme().system().transparent,
11199                                                local_player: cx.editor_style.local_player,
11200                                                text: text_style,
11201                                                scrollbar_width: cx.editor_style.scrollbar_width,
11202                                                syntax: cx.editor_style.syntax.clone(),
11203                                                status: cx.editor_style.status.clone(),
11204                                                inlay_hints_style: HighlightStyle {
11205                                                    font_weight: Some(FontWeight::BOLD),
11206                                                    ..make_inlay_hints_style(cx.app)
11207                                                },
11208                                                inline_completion_styles: make_suggestion_styles(
11209                                                    cx.app,
11210                                                ),
11211                                                ..EditorStyle::default()
11212                                            },
11213                                        ))
11214                                        .into_any_element()
11215                                }
11216                            }),
11217                            priority: 0,
11218                        }],
11219                        Some(Autoscroll::fit()),
11220                        cx,
11221                    )[0];
11222                    this.pending_rename = Some(RenameState {
11223                        range,
11224                        old_name,
11225                        editor: rename_editor,
11226                        block_id,
11227                    });
11228                })?;
11229            }
11230
11231            Ok(())
11232        }))
11233    }
11234
11235    pub fn confirm_rename(
11236        &mut self,
11237        _: &ConfirmRename,
11238        window: &mut Window,
11239        cx: &mut Context<Self>,
11240    ) -> Option<Task<Result<()>>> {
11241        let rename = self.take_rename(false, window, cx)?;
11242        let workspace = self.workspace()?.downgrade();
11243        let (buffer, start) = self
11244            .buffer
11245            .read(cx)
11246            .text_anchor_for_position(rename.range.start, cx)?;
11247        let (end_buffer, _) = self
11248            .buffer
11249            .read(cx)
11250            .text_anchor_for_position(rename.range.end, cx)?;
11251        if buffer != end_buffer {
11252            return None;
11253        }
11254
11255        let old_name = rename.old_name;
11256        let new_name = rename.editor.read(cx).text(cx);
11257
11258        let rename = self.semantics_provider.as_ref()?.perform_rename(
11259            &buffer,
11260            start,
11261            new_name.clone(),
11262            cx,
11263        )?;
11264
11265        Some(cx.spawn_in(window, |editor, mut cx| async move {
11266            let project_transaction = rename.await?;
11267            Self::open_project_transaction(
11268                &editor,
11269                workspace,
11270                project_transaction,
11271                format!("Rename: {}{}", old_name, new_name),
11272                cx.clone(),
11273            )
11274            .await?;
11275
11276            editor.update(&mut cx, |editor, cx| {
11277                editor.refresh_document_highlights(cx);
11278            })?;
11279            Ok(())
11280        }))
11281    }
11282
11283    fn take_rename(
11284        &mut self,
11285        moving_cursor: bool,
11286        window: &mut Window,
11287        cx: &mut Context<Self>,
11288    ) -> Option<RenameState> {
11289        let rename = self.pending_rename.take()?;
11290        if rename.editor.focus_handle(cx).is_focused(window) {
11291            window.focus(&self.focus_handle);
11292        }
11293
11294        self.remove_blocks(
11295            [rename.block_id].into_iter().collect(),
11296            Some(Autoscroll::fit()),
11297            cx,
11298        );
11299        self.clear_highlights::<Rename>(cx);
11300        self.show_local_selections = true;
11301
11302        if moving_cursor {
11303            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11304                editor.selections.newest::<usize>(cx).head()
11305            });
11306
11307            // Update the selection to match the position of the selection inside
11308            // the rename editor.
11309            let snapshot = self.buffer.read(cx).read(cx);
11310            let rename_range = rename.range.to_offset(&snapshot);
11311            let cursor_in_editor = snapshot
11312                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11313                .min(rename_range.end);
11314            drop(snapshot);
11315
11316            self.change_selections(None, window, cx, |s| {
11317                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11318            });
11319        } else {
11320            self.refresh_document_highlights(cx);
11321        }
11322
11323        Some(rename)
11324    }
11325
11326    pub fn pending_rename(&self) -> Option<&RenameState> {
11327        self.pending_rename.as_ref()
11328    }
11329
11330    fn format(
11331        &mut self,
11332        _: &Format,
11333        window: &mut Window,
11334        cx: &mut Context<Self>,
11335    ) -> Option<Task<Result<()>>> {
11336        let project = match &self.project {
11337            Some(project) => project.clone(),
11338            None => return None,
11339        };
11340
11341        Some(self.perform_format(
11342            project,
11343            FormatTrigger::Manual,
11344            FormatTarget::Buffers,
11345            window,
11346            cx,
11347        ))
11348    }
11349
11350    fn format_selections(
11351        &mut self,
11352        _: &FormatSelections,
11353        window: &mut Window,
11354        cx: &mut Context<Self>,
11355    ) -> Option<Task<Result<()>>> {
11356        let project = match &self.project {
11357            Some(project) => project.clone(),
11358            None => return None,
11359        };
11360
11361        let ranges = self
11362            .selections
11363            .all_adjusted(cx)
11364            .into_iter()
11365            .map(|selection| selection.range())
11366            .collect_vec();
11367
11368        Some(self.perform_format(
11369            project,
11370            FormatTrigger::Manual,
11371            FormatTarget::Ranges(ranges),
11372            window,
11373            cx,
11374        ))
11375    }
11376
11377    fn perform_format(
11378        &mut self,
11379        project: Entity<Project>,
11380        trigger: FormatTrigger,
11381        target: FormatTarget,
11382        window: &mut Window,
11383        cx: &mut Context<Self>,
11384    ) -> Task<Result<()>> {
11385        let buffer = self.buffer.clone();
11386        let (buffers, target) = match target {
11387            FormatTarget::Buffers => {
11388                let mut buffers = buffer.read(cx).all_buffers();
11389                if trigger == FormatTrigger::Save {
11390                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11391                }
11392                (buffers, LspFormatTarget::Buffers)
11393            }
11394            FormatTarget::Ranges(selection_ranges) => {
11395                let multi_buffer = buffer.read(cx);
11396                let snapshot = multi_buffer.read(cx);
11397                let mut buffers = HashSet::default();
11398                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11399                    BTreeMap::new();
11400                for selection_range in selection_ranges {
11401                    for (buffer, buffer_range, _) in
11402                        snapshot.range_to_buffer_ranges(selection_range)
11403                    {
11404                        let buffer_id = buffer.remote_id();
11405                        let start = buffer.anchor_before(buffer_range.start);
11406                        let end = buffer.anchor_after(buffer_range.end);
11407                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11408                        buffer_id_to_ranges
11409                            .entry(buffer_id)
11410                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11411                            .or_insert_with(|| vec![start..end]);
11412                    }
11413                }
11414                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11415            }
11416        };
11417
11418        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11419        let format = project.update(cx, |project, cx| {
11420            project.format(buffers, target, true, trigger, cx)
11421        });
11422
11423        cx.spawn_in(window, |_, mut cx| async move {
11424            let transaction = futures::select_biased! {
11425                () = timeout => {
11426                    log::warn!("timed out waiting for formatting");
11427                    None
11428                }
11429                transaction = format.log_err().fuse() => transaction,
11430            };
11431
11432            buffer
11433                .update(&mut cx, |buffer, cx| {
11434                    if let Some(transaction) = transaction {
11435                        if !buffer.is_singleton() {
11436                            buffer.push_transaction(&transaction.0, cx);
11437                        }
11438                    }
11439
11440                    cx.notify();
11441                })
11442                .ok();
11443
11444            Ok(())
11445        })
11446    }
11447
11448    fn restart_language_server(
11449        &mut self,
11450        _: &RestartLanguageServer,
11451        _: &mut Window,
11452        cx: &mut Context<Self>,
11453    ) {
11454        if let Some(project) = self.project.clone() {
11455            self.buffer.update(cx, |multi_buffer, cx| {
11456                project.update(cx, |project, cx| {
11457                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11458                });
11459            })
11460        }
11461    }
11462
11463    fn cancel_language_server_work(
11464        workspace: &mut Workspace,
11465        _: &actions::CancelLanguageServerWork,
11466        _: &mut Window,
11467        cx: &mut Context<Workspace>,
11468    ) {
11469        let project = workspace.project();
11470        let buffers = workspace
11471            .active_item(cx)
11472            .and_then(|item| item.act_as::<Editor>(cx))
11473            .map_or(HashSet::default(), |editor| {
11474                editor.read(cx).buffer.read(cx).all_buffers()
11475            });
11476        project.update(cx, |project, cx| {
11477            project.cancel_language_server_work_for_buffers(buffers, cx);
11478        });
11479    }
11480
11481    fn show_character_palette(
11482        &mut self,
11483        _: &ShowCharacterPalette,
11484        window: &mut Window,
11485        _: &mut Context<Self>,
11486    ) {
11487        window.show_character_palette();
11488    }
11489
11490    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11491        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11492            let buffer = self.buffer.read(cx).snapshot(cx);
11493            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11494            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11495            let is_valid = buffer
11496                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11497                .any(|entry| {
11498                    entry.diagnostic.is_primary
11499                        && !entry.range.is_empty()
11500                        && entry.range.start == primary_range_start
11501                        && entry.diagnostic.message == active_diagnostics.primary_message
11502                });
11503
11504            if is_valid != active_diagnostics.is_valid {
11505                active_diagnostics.is_valid = is_valid;
11506                let mut new_styles = HashMap::default();
11507                for (block_id, diagnostic) in &active_diagnostics.blocks {
11508                    new_styles.insert(
11509                        *block_id,
11510                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11511                    );
11512                }
11513                self.display_map.update(cx, |display_map, _cx| {
11514                    display_map.replace_blocks(new_styles)
11515                });
11516            }
11517        }
11518    }
11519
11520    fn activate_diagnostics(
11521        &mut self,
11522        buffer_id: BufferId,
11523        group_id: usize,
11524        window: &mut Window,
11525        cx: &mut Context<Self>,
11526    ) {
11527        self.dismiss_diagnostics(cx);
11528        let snapshot = self.snapshot(window, cx);
11529        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11530            let buffer = self.buffer.read(cx).snapshot(cx);
11531
11532            let mut primary_range = None;
11533            let mut primary_message = None;
11534            let diagnostic_group = buffer
11535                .diagnostic_group(buffer_id, group_id)
11536                .filter_map(|entry| {
11537                    let start = entry.range.start;
11538                    let end = entry.range.end;
11539                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11540                        && (start.row == end.row
11541                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11542                    {
11543                        return None;
11544                    }
11545                    if entry.diagnostic.is_primary {
11546                        primary_range = Some(entry.range.clone());
11547                        primary_message = Some(entry.diagnostic.message.clone());
11548                    }
11549                    Some(entry)
11550                })
11551                .collect::<Vec<_>>();
11552            let primary_range = primary_range?;
11553            let primary_message = primary_message?;
11554
11555            let blocks = display_map
11556                .insert_blocks(
11557                    diagnostic_group.iter().map(|entry| {
11558                        let diagnostic = entry.diagnostic.clone();
11559                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11560                        BlockProperties {
11561                            style: BlockStyle::Fixed,
11562                            placement: BlockPlacement::Below(
11563                                buffer.anchor_after(entry.range.start),
11564                            ),
11565                            height: message_height,
11566                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11567                            priority: 0,
11568                        }
11569                    }),
11570                    cx,
11571                )
11572                .into_iter()
11573                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11574                .collect();
11575
11576            Some(ActiveDiagnosticGroup {
11577                primary_range: buffer.anchor_before(primary_range.start)
11578                    ..buffer.anchor_after(primary_range.end),
11579                primary_message,
11580                group_id,
11581                blocks,
11582                is_valid: true,
11583            })
11584        });
11585    }
11586
11587    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11588        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11589            self.display_map.update(cx, |display_map, cx| {
11590                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11591            });
11592            cx.notify();
11593        }
11594    }
11595
11596    pub fn set_selections_from_remote(
11597        &mut self,
11598        selections: Vec<Selection<Anchor>>,
11599        pending_selection: Option<Selection<Anchor>>,
11600        window: &mut Window,
11601        cx: &mut Context<Self>,
11602    ) {
11603        let old_cursor_position = self.selections.newest_anchor().head();
11604        self.selections.change_with(cx, |s| {
11605            s.select_anchors(selections);
11606            if let Some(pending_selection) = pending_selection {
11607                s.set_pending(pending_selection, SelectMode::Character);
11608            } else {
11609                s.clear_pending();
11610            }
11611        });
11612        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11613    }
11614
11615    fn push_to_selection_history(&mut self) {
11616        self.selection_history.push(SelectionHistoryEntry {
11617            selections: self.selections.disjoint_anchors(),
11618            select_next_state: self.select_next_state.clone(),
11619            select_prev_state: self.select_prev_state.clone(),
11620            add_selections_state: self.add_selections_state.clone(),
11621        });
11622    }
11623
11624    pub fn transact(
11625        &mut self,
11626        window: &mut Window,
11627        cx: &mut Context<Self>,
11628        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11629    ) -> Option<TransactionId> {
11630        self.start_transaction_at(Instant::now(), window, cx);
11631        update(self, window, cx);
11632        self.end_transaction_at(Instant::now(), cx)
11633    }
11634
11635    pub fn start_transaction_at(
11636        &mut self,
11637        now: Instant,
11638        window: &mut Window,
11639        cx: &mut Context<Self>,
11640    ) {
11641        self.end_selection(window, cx);
11642        if let Some(tx_id) = self
11643            .buffer
11644            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11645        {
11646            self.selection_history
11647                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11648            cx.emit(EditorEvent::TransactionBegun {
11649                transaction_id: tx_id,
11650            })
11651        }
11652    }
11653
11654    pub fn end_transaction_at(
11655        &mut self,
11656        now: Instant,
11657        cx: &mut Context<Self>,
11658    ) -> Option<TransactionId> {
11659        if let Some(transaction_id) = self
11660            .buffer
11661            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11662        {
11663            if let Some((_, end_selections)) =
11664                self.selection_history.transaction_mut(transaction_id)
11665            {
11666                *end_selections = Some(self.selections.disjoint_anchors());
11667            } else {
11668                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11669            }
11670
11671            cx.emit(EditorEvent::Edited { transaction_id });
11672            Some(transaction_id)
11673        } else {
11674            None
11675        }
11676    }
11677
11678    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11679        if self.selection_mark_mode {
11680            self.change_selections(None, window, cx, |s| {
11681                s.move_with(|_, sel| {
11682                    sel.collapse_to(sel.head(), SelectionGoal::None);
11683                });
11684            })
11685        }
11686        self.selection_mark_mode = true;
11687        cx.notify();
11688    }
11689
11690    pub fn swap_selection_ends(
11691        &mut self,
11692        _: &actions::SwapSelectionEnds,
11693        window: &mut Window,
11694        cx: &mut Context<Self>,
11695    ) {
11696        self.change_selections(None, window, cx, |s| {
11697            s.move_with(|_, sel| {
11698                if sel.start != sel.end {
11699                    sel.reversed = !sel.reversed
11700                }
11701            });
11702        });
11703        self.request_autoscroll(Autoscroll::newest(), cx);
11704        cx.notify();
11705    }
11706
11707    pub fn toggle_fold(
11708        &mut self,
11709        _: &actions::ToggleFold,
11710        window: &mut Window,
11711        cx: &mut Context<Self>,
11712    ) {
11713        if self.is_singleton(cx) {
11714            let selection = self.selections.newest::<Point>(cx);
11715
11716            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11717            let range = if selection.is_empty() {
11718                let point = selection.head().to_display_point(&display_map);
11719                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11720                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11721                    .to_point(&display_map);
11722                start..end
11723            } else {
11724                selection.range()
11725            };
11726            if display_map.folds_in_range(range).next().is_some() {
11727                self.unfold_lines(&Default::default(), window, cx)
11728            } else {
11729                self.fold(&Default::default(), window, cx)
11730            }
11731        } else {
11732            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11733            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11734                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11735                .map(|(snapshot, _, _)| snapshot.remote_id())
11736                .collect();
11737
11738            for buffer_id in buffer_ids {
11739                if self.is_buffer_folded(buffer_id, cx) {
11740                    self.unfold_buffer(buffer_id, cx);
11741                } else {
11742                    self.fold_buffer(buffer_id, cx);
11743                }
11744            }
11745        }
11746    }
11747
11748    pub fn toggle_fold_recursive(
11749        &mut self,
11750        _: &actions::ToggleFoldRecursive,
11751        window: &mut Window,
11752        cx: &mut Context<Self>,
11753    ) {
11754        let selection = self.selections.newest::<Point>(cx);
11755
11756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11757        let range = if selection.is_empty() {
11758            let point = selection.head().to_display_point(&display_map);
11759            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11760            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11761                .to_point(&display_map);
11762            start..end
11763        } else {
11764            selection.range()
11765        };
11766        if display_map.folds_in_range(range).next().is_some() {
11767            self.unfold_recursive(&Default::default(), window, cx)
11768        } else {
11769            self.fold_recursive(&Default::default(), window, cx)
11770        }
11771    }
11772
11773    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11774        if self.is_singleton(cx) {
11775            let mut to_fold = Vec::new();
11776            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11777            let selections = self.selections.all_adjusted(cx);
11778
11779            for selection in selections {
11780                let range = selection.range().sorted();
11781                let buffer_start_row = range.start.row;
11782
11783                if range.start.row != range.end.row {
11784                    let mut found = false;
11785                    let mut row = range.start.row;
11786                    while row <= range.end.row {
11787                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11788                        {
11789                            found = true;
11790                            row = crease.range().end.row + 1;
11791                            to_fold.push(crease);
11792                        } else {
11793                            row += 1
11794                        }
11795                    }
11796                    if found {
11797                        continue;
11798                    }
11799                }
11800
11801                for row in (0..=range.start.row).rev() {
11802                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11803                        if crease.range().end.row >= buffer_start_row {
11804                            to_fold.push(crease);
11805                            if row <= range.start.row {
11806                                break;
11807                            }
11808                        }
11809                    }
11810                }
11811            }
11812
11813            self.fold_creases(to_fold, true, window, cx);
11814        } else {
11815            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11816
11817            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11818                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11819                .map(|(snapshot, _, _)| snapshot.remote_id())
11820                .collect();
11821            for buffer_id in buffer_ids {
11822                self.fold_buffer(buffer_id, cx);
11823            }
11824        }
11825    }
11826
11827    fn fold_at_level(
11828        &mut self,
11829        fold_at: &FoldAtLevel,
11830        window: &mut Window,
11831        cx: &mut Context<Self>,
11832    ) {
11833        if !self.buffer.read(cx).is_singleton() {
11834            return;
11835        }
11836
11837        let fold_at_level = fold_at.0;
11838        let snapshot = self.buffer.read(cx).snapshot(cx);
11839        let mut to_fold = Vec::new();
11840        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11841
11842        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11843            while start_row < end_row {
11844                match self
11845                    .snapshot(window, cx)
11846                    .crease_for_buffer_row(MultiBufferRow(start_row))
11847                {
11848                    Some(crease) => {
11849                        let nested_start_row = crease.range().start.row + 1;
11850                        let nested_end_row = crease.range().end.row;
11851
11852                        if current_level < fold_at_level {
11853                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11854                        } else if current_level == fold_at_level {
11855                            to_fold.push(crease);
11856                        }
11857
11858                        start_row = nested_end_row + 1;
11859                    }
11860                    None => start_row += 1,
11861                }
11862            }
11863        }
11864
11865        self.fold_creases(to_fold, true, window, cx);
11866    }
11867
11868    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11869        if self.buffer.read(cx).is_singleton() {
11870            let mut fold_ranges = Vec::new();
11871            let snapshot = self.buffer.read(cx).snapshot(cx);
11872
11873            for row in 0..snapshot.max_row().0 {
11874                if let Some(foldable_range) = self
11875                    .snapshot(window, cx)
11876                    .crease_for_buffer_row(MultiBufferRow(row))
11877                {
11878                    fold_ranges.push(foldable_range);
11879                }
11880            }
11881
11882            self.fold_creases(fold_ranges, true, window, cx);
11883        } else {
11884            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11885                editor
11886                    .update_in(&mut cx, |editor, _, cx| {
11887                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11888                            editor.fold_buffer(buffer_id, cx);
11889                        }
11890                    })
11891                    .ok();
11892            });
11893        }
11894    }
11895
11896    pub fn fold_function_bodies(
11897        &mut self,
11898        _: &actions::FoldFunctionBodies,
11899        window: &mut Window,
11900        cx: &mut Context<Self>,
11901    ) {
11902        let snapshot = self.buffer.read(cx).snapshot(cx);
11903
11904        let ranges = snapshot
11905            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11906            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11907            .collect::<Vec<_>>();
11908
11909        let creases = ranges
11910            .into_iter()
11911            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11912            .collect();
11913
11914        self.fold_creases(creases, true, window, cx);
11915    }
11916
11917    pub fn fold_recursive(
11918        &mut self,
11919        _: &actions::FoldRecursive,
11920        window: &mut Window,
11921        cx: &mut Context<Self>,
11922    ) {
11923        let mut to_fold = Vec::new();
11924        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11925        let selections = self.selections.all_adjusted(cx);
11926
11927        for selection in selections {
11928            let range = selection.range().sorted();
11929            let buffer_start_row = range.start.row;
11930
11931            if range.start.row != range.end.row {
11932                let mut found = false;
11933                for row in range.start.row..=range.end.row {
11934                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11935                        found = true;
11936                        to_fold.push(crease);
11937                    }
11938                }
11939                if found {
11940                    continue;
11941                }
11942            }
11943
11944            for row in (0..=range.start.row).rev() {
11945                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11946                    if crease.range().end.row >= buffer_start_row {
11947                        to_fold.push(crease);
11948                    } else {
11949                        break;
11950                    }
11951                }
11952            }
11953        }
11954
11955        self.fold_creases(to_fold, true, window, cx);
11956    }
11957
11958    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11959        let buffer_row = fold_at.buffer_row;
11960        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11961
11962        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11963            let autoscroll = self
11964                .selections
11965                .all::<Point>(cx)
11966                .iter()
11967                .any(|selection| crease.range().overlaps(&selection.range()));
11968
11969            self.fold_creases(vec![crease], autoscroll, window, cx);
11970        }
11971    }
11972
11973    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11974        if self.is_singleton(cx) {
11975            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11976            let buffer = &display_map.buffer_snapshot;
11977            let selections = self.selections.all::<Point>(cx);
11978            let ranges = selections
11979                .iter()
11980                .map(|s| {
11981                    let range = s.display_range(&display_map).sorted();
11982                    let mut start = range.start.to_point(&display_map);
11983                    let mut end = range.end.to_point(&display_map);
11984                    start.column = 0;
11985                    end.column = buffer.line_len(MultiBufferRow(end.row));
11986                    start..end
11987                })
11988                .collect::<Vec<_>>();
11989
11990            self.unfold_ranges(&ranges, true, true, cx);
11991        } else {
11992            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11993            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11994                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11995                .map(|(snapshot, _, _)| snapshot.remote_id())
11996                .collect();
11997            for buffer_id in buffer_ids {
11998                self.unfold_buffer(buffer_id, cx);
11999            }
12000        }
12001    }
12002
12003    pub fn unfold_recursive(
12004        &mut self,
12005        _: &UnfoldRecursive,
12006        _window: &mut Window,
12007        cx: &mut Context<Self>,
12008    ) {
12009        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12010        let selections = self.selections.all::<Point>(cx);
12011        let ranges = selections
12012            .iter()
12013            .map(|s| {
12014                let mut range = s.display_range(&display_map).sorted();
12015                *range.start.column_mut() = 0;
12016                *range.end.column_mut() = display_map.line_len(range.end.row());
12017                let start = range.start.to_point(&display_map);
12018                let end = range.end.to_point(&display_map);
12019                start..end
12020            })
12021            .collect::<Vec<_>>();
12022
12023        self.unfold_ranges(&ranges, true, true, cx);
12024    }
12025
12026    pub fn unfold_at(
12027        &mut self,
12028        unfold_at: &UnfoldAt,
12029        _window: &mut Window,
12030        cx: &mut Context<Self>,
12031    ) {
12032        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12033
12034        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12035            ..Point::new(
12036                unfold_at.buffer_row.0,
12037                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12038            );
12039
12040        let autoscroll = self
12041            .selections
12042            .all::<Point>(cx)
12043            .iter()
12044            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12045
12046        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12047    }
12048
12049    pub fn unfold_all(
12050        &mut self,
12051        _: &actions::UnfoldAll,
12052        _window: &mut Window,
12053        cx: &mut Context<Self>,
12054    ) {
12055        if self.buffer.read(cx).is_singleton() {
12056            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12057            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12058        } else {
12059            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12060                editor
12061                    .update(&mut cx, |editor, cx| {
12062                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12063                            editor.unfold_buffer(buffer_id, cx);
12064                        }
12065                    })
12066                    .ok();
12067            });
12068        }
12069    }
12070
12071    pub fn fold_selected_ranges(
12072        &mut self,
12073        _: &FoldSelectedRanges,
12074        window: &mut Window,
12075        cx: &mut Context<Self>,
12076    ) {
12077        let selections = self.selections.all::<Point>(cx);
12078        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12079        let line_mode = self.selections.line_mode;
12080        let ranges = selections
12081            .into_iter()
12082            .map(|s| {
12083                if line_mode {
12084                    let start = Point::new(s.start.row, 0);
12085                    let end = Point::new(
12086                        s.end.row,
12087                        display_map
12088                            .buffer_snapshot
12089                            .line_len(MultiBufferRow(s.end.row)),
12090                    );
12091                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12092                } else {
12093                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12094                }
12095            })
12096            .collect::<Vec<_>>();
12097        self.fold_creases(ranges, true, window, cx);
12098    }
12099
12100    pub fn fold_ranges<T: ToOffset + Clone>(
12101        &mut self,
12102        ranges: Vec<Range<T>>,
12103        auto_scroll: bool,
12104        window: &mut Window,
12105        cx: &mut Context<Self>,
12106    ) {
12107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12108        let ranges = ranges
12109            .into_iter()
12110            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12111            .collect::<Vec<_>>();
12112        self.fold_creases(ranges, auto_scroll, window, cx);
12113    }
12114
12115    pub fn fold_creases<T: ToOffset + Clone>(
12116        &mut self,
12117        creases: Vec<Crease<T>>,
12118        auto_scroll: bool,
12119        window: &mut Window,
12120        cx: &mut Context<Self>,
12121    ) {
12122        if creases.is_empty() {
12123            return;
12124        }
12125
12126        let mut buffers_affected = HashSet::default();
12127        let multi_buffer = self.buffer().read(cx);
12128        for crease in &creases {
12129            if let Some((_, buffer, _)) =
12130                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12131            {
12132                buffers_affected.insert(buffer.read(cx).remote_id());
12133            };
12134        }
12135
12136        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12137
12138        if auto_scroll {
12139            self.request_autoscroll(Autoscroll::fit(), cx);
12140        }
12141
12142        cx.notify();
12143
12144        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12145            // Clear diagnostics block when folding a range that contains it.
12146            let snapshot = self.snapshot(window, cx);
12147            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12148                drop(snapshot);
12149                self.active_diagnostics = Some(active_diagnostics);
12150                self.dismiss_diagnostics(cx);
12151            } else {
12152                self.active_diagnostics = Some(active_diagnostics);
12153            }
12154        }
12155
12156        self.scrollbar_marker_state.dirty = true;
12157    }
12158
12159    /// Removes any folds whose ranges intersect any of the given ranges.
12160    pub fn unfold_ranges<T: ToOffset + Clone>(
12161        &mut self,
12162        ranges: &[Range<T>],
12163        inclusive: bool,
12164        auto_scroll: bool,
12165        cx: &mut Context<Self>,
12166    ) {
12167        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12168            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12169        });
12170    }
12171
12172    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12173        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12174            return;
12175        }
12176        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12177        self.display_map
12178            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12179        cx.emit(EditorEvent::BufferFoldToggled {
12180            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12181            folded: true,
12182        });
12183        cx.notify();
12184    }
12185
12186    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12187        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12188            return;
12189        }
12190        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12191        self.display_map.update(cx, |display_map, cx| {
12192            display_map.unfold_buffer(buffer_id, cx);
12193        });
12194        cx.emit(EditorEvent::BufferFoldToggled {
12195            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12196            folded: false,
12197        });
12198        cx.notify();
12199    }
12200
12201    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12202        self.display_map.read(cx).is_buffer_folded(buffer)
12203    }
12204
12205    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12206        self.display_map.read(cx).folded_buffers()
12207    }
12208
12209    /// Removes any folds with the given ranges.
12210    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12211        &mut self,
12212        ranges: &[Range<T>],
12213        type_id: TypeId,
12214        auto_scroll: bool,
12215        cx: &mut Context<Self>,
12216    ) {
12217        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12218            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12219        });
12220    }
12221
12222    fn remove_folds_with<T: ToOffset + Clone>(
12223        &mut self,
12224        ranges: &[Range<T>],
12225        auto_scroll: bool,
12226        cx: &mut Context<Self>,
12227        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12228    ) {
12229        if ranges.is_empty() {
12230            return;
12231        }
12232
12233        let mut buffers_affected = HashSet::default();
12234        let multi_buffer = self.buffer().read(cx);
12235        for range in ranges {
12236            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12237                buffers_affected.insert(buffer.read(cx).remote_id());
12238            };
12239        }
12240
12241        self.display_map.update(cx, update);
12242
12243        if auto_scroll {
12244            self.request_autoscroll(Autoscroll::fit(), cx);
12245        }
12246
12247        cx.notify();
12248        self.scrollbar_marker_state.dirty = true;
12249        self.active_indent_guides_state.dirty = true;
12250    }
12251
12252    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12253        self.display_map.read(cx).fold_placeholder.clone()
12254    }
12255
12256    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12257        self.buffer.update(cx, |buffer, cx| {
12258            buffer.set_all_diff_hunks_expanded(cx);
12259        });
12260    }
12261
12262    pub fn expand_all_diff_hunks(
12263        &mut self,
12264        _: &ExpandAllHunkDiffs,
12265        _window: &mut Window,
12266        cx: &mut Context<Self>,
12267    ) {
12268        self.buffer.update(cx, |buffer, cx| {
12269            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12270        });
12271    }
12272
12273    pub fn toggle_selected_diff_hunks(
12274        &mut self,
12275        _: &ToggleSelectedDiffHunks,
12276        _window: &mut Window,
12277        cx: &mut Context<Self>,
12278    ) {
12279        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12280        self.toggle_diff_hunks_in_ranges(ranges, cx);
12281    }
12282
12283    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12284        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12285        self.buffer
12286            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12287    }
12288
12289    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12290        self.buffer.update(cx, |buffer, cx| {
12291            let ranges = vec![Anchor::min()..Anchor::max()];
12292            if !buffer.all_diff_hunks_expanded()
12293                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12294            {
12295                buffer.collapse_diff_hunks(ranges, cx);
12296                true
12297            } else {
12298                false
12299            }
12300        })
12301    }
12302
12303    fn toggle_diff_hunks_in_ranges(
12304        &mut self,
12305        ranges: Vec<Range<Anchor>>,
12306        cx: &mut Context<'_, Editor>,
12307    ) {
12308        self.buffer.update(cx, |buffer, cx| {
12309            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12310            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12311        })
12312    }
12313
12314    fn toggle_diff_hunks_in_ranges_narrow(
12315        &mut self,
12316        ranges: Vec<Range<Anchor>>,
12317        cx: &mut Context<'_, Editor>,
12318    ) {
12319        self.buffer.update(cx, |buffer, cx| {
12320            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12321            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12322        })
12323    }
12324
12325    pub(crate) fn apply_all_diff_hunks(
12326        &mut self,
12327        _: &ApplyAllDiffHunks,
12328        window: &mut Window,
12329        cx: &mut Context<Self>,
12330    ) {
12331        let buffers = self.buffer.read(cx).all_buffers();
12332        for branch_buffer in buffers {
12333            branch_buffer.update(cx, |branch_buffer, cx| {
12334                branch_buffer.merge_into_base(Vec::new(), cx);
12335            });
12336        }
12337
12338        if let Some(project) = self.project.clone() {
12339            self.save(true, project, window, cx).detach_and_log_err(cx);
12340        }
12341    }
12342
12343    pub(crate) fn apply_selected_diff_hunks(
12344        &mut self,
12345        _: &ApplyDiffHunk,
12346        window: &mut Window,
12347        cx: &mut Context<Self>,
12348    ) {
12349        let snapshot = self.snapshot(window, cx);
12350        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12351        let mut ranges_by_buffer = HashMap::default();
12352        self.transact(window, cx, |editor, _window, cx| {
12353            for hunk in hunks {
12354                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12355                    ranges_by_buffer
12356                        .entry(buffer.clone())
12357                        .or_insert_with(Vec::new)
12358                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12359                }
12360            }
12361
12362            for (buffer, ranges) in ranges_by_buffer {
12363                buffer.update(cx, |buffer, cx| {
12364                    buffer.merge_into_base(ranges, cx);
12365                });
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 fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12375        if hovered != self.gutter_hovered {
12376            self.gutter_hovered = hovered;
12377            cx.notify();
12378        }
12379    }
12380
12381    pub fn insert_blocks(
12382        &mut self,
12383        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12384        autoscroll: Option<Autoscroll>,
12385        cx: &mut Context<Self>,
12386    ) -> Vec<CustomBlockId> {
12387        let blocks = self
12388            .display_map
12389            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12390        if let Some(autoscroll) = autoscroll {
12391            self.request_autoscroll(autoscroll, cx);
12392        }
12393        cx.notify();
12394        blocks
12395    }
12396
12397    pub fn resize_blocks(
12398        &mut self,
12399        heights: HashMap<CustomBlockId, u32>,
12400        autoscroll: Option<Autoscroll>,
12401        cx: &mut Context<Self>,
12402    ) {
12403        self.display_map
12404            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12405        if let Some(autoscroll) = autoscroll {
12406            self.request_autoscroll(autoscroll, cx);
12407        }
12408        cx.notify();
12409    }
12410
12411    pub fn replace_blocks(
12412        &mut self,
12413        renderers: HashMap<CustomBlockId, RenderBlock>,
12414        autoscroll: Option<Autoscroll>,
12415        cx: &mut Context<Self>,
12416    ) {
12417        self.display_map
12418            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12419        if let Some(autoscroll) = autoscroll {
12420            self.request_autoscroll(autoscroll, cx);
12421        }
12422        cx.notify();
12423    }
12424
12425    pub fn remove_blocks(
12426        &mut self,
12427        block_ids: HashSet<CustomBlockId>,
12428        autoscroll: Option<Autoscroll>,
12429        cx: &mut Context<Self>,
12430    ) {
12431        self.display_map.update(cx, |display_map, cx| {
12432            display_map.remove_blocks(block_ids, cx)
12433        });
12434        if let Some(autoscroll) = autoscroll {
12435            self.request_autoscroll(autoscroll, cx);
12436        }
12437        cx.notify();
12438    }
12439
12440    pub fn row_for_block(
12441        &self,
12442        block_id: CustomBlockId,
12443        cx: &mut Context<Self>,
12444    ) -> Option<DisplayRow> {
12445        self.display_map
12446            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12447    }
12448
12449    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12450        self.focused_block = Some(focused_block);
12451    }
12452
12453    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12454        self.focused_block.take()
12455    }
12456
12457    pub fn insert_creases(
12458        &mut self,
12459        creases: impl IntoIterator<Item = Crease<Anchor>>,
12460        cx: &mut Context<Self>,
12461    ) -> Vec<CreaseId> {
12462        self.display_map
12463            .update(cx, |map, cx| map.insert_creases(creases, cx))
12464    }
12465
12466    pub fn remove_creases(
12467        &mut self,
12468        ids: impl IntoIterator<Item = CreaseId>,
12469        cx: &mut Context<Self>,
12470    ) {
12471        self.display_map
12472            .update(cx, |map, cx| map.remove_creases(ids, cx));
12473    }
12474
12475    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12476        self.display_map
12477            .update(cx, |map, cx| map.snapshot(cx))
12478            .longest_row()
12479    }
12480
12481    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12482        self.display_map
12483            .update(cx, |map, cx| map.snapshot(cx))
12484            .max_point()
12485    }
12486
12487    pub fn text(&self, cx: &App) -> String {
12488        self.buffer.read(cx).read(cx).text()
12489    }
12490
12491    pub fn is_empty(&self, cx: &App) -> bool {
12492        self.buffer.read(cx).read(cx).is_empty()
12493    }
12494
12495    pub fn text_option(&self, cx: &App) -> Option<String> {
12496        let text = self.text(cx);
12497        let text = text.trim();
12498
12499        if text.is_empty() {
12500            return None;
12501        }
12502
12503        Some(text.to_string())
12504    }
12505
12506    pub fn set_text(
12507        &mut self,
12508        text: impl Into<Arc<str>>,
12509        window: &mut Window,
12510        cx: &mut Context<Self>,
12511    ) {
12512        self.transact(window, cx, |this, _, cx| {
12513            this.buffer
12514                .read(cx)
12515                .as_singleton()
12516                .expect("you can only call set_text on editors for singleton buffers")
12517                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12518        });
12519    }
12520
12521    pub fn display_text(&self, cx: &mut App) -> String {
12522        self.display_map
12523            .update(cx, |map, cx| map.snapshot(cx))
12524            .text()
12525    }
12526
12527    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12528        let mut wrap_guides = smallvec::smallvec![];
12529
12530        if self.show_wrap_guides == Some(false) {
12531            return wrap_guides;
12532        }
12533
12534        let settings = self.buffer.read(cx).settings_at(0, cx);
12535        if settings.show_wrap_guides {
12536            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12537                wrap_guides.push((soft_wrap as usize, true));
12538            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12539                wrap_guides.push((soft_wrap as usize, true));
12540            }
12541            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12542        }
12543
12544        wrap_guides
12545    }
12546
12547    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12548        let settings = self.buffer.read(cx).settings_at(0, cx);
12549        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12550        match mode {
12551            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12552                SoftWrap::None
12553            }
12554            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12555            language_settings::SoftWrap::PreferredLineLength => {
12556                SoftWrap::Column(settings.preferred_line_length)
12557            }
12558            language_settings::SoftWrap::Bounded => {
12559                SoftWrap::Bounded(settings.preferred_line_length)
12560            }
12561        }
12562    }
12563
12564    pub fn set_soft_wrap_mode(
12565        &mut self,
12566        mode: language_settings::SoftWrap,
12567
12568        cx: &mut Context<Self>,
12569    ) {
12570        self.soft_wrap_mode_override = Some(mode);
12571        cx.notify();
12572    }
12573
12574    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12575        self.text_style_refinement = Some(style);
12576    }
12577
12578    /// called by the Element so we know what style we were most recently rendered with.
12579    pub(crate) fn set_style(
12580        &mut self,
12581        style: EditorStyle,
12582        window: &mut Window,
12583        cx: &mut Context<Self>,
12584    ) {
12585        let rem_size = window.rem_size();
12586        self.display_map.update(cx, |map, cx| {
12587            map.set_font(
12588                style.text.font(),
12589                style.text.font_size.to_pixels(rem_size),
12590                cx,
12591            )
12592        });
12593        self.style = Some(style);
12594    }
12595
12596    pub fn style(&self) -> Option<&EditorStyle> {
12597        self.style.as_ref()
12598    }
12599
12600    // Called by the element. This method is not designed to be called outside of the editor
12601    // element's layout code because it does not notify when rewrapping is computed synchronously.
12602    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12603        self.display_map
12604            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12605    }
12606
12607    pub fn set_soft_wrap(&mut self) {
12608        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12609    }
12610
12611    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12612        if self.soft_wrap_mode_override.is_some() {
12613            self.soft_wrap_mode_override.take();
12614        } else {
12615            let soft_wrap = match self.soft_wrap_mode(cx) {
12616                SoftWrap::GitDiff => return,
12617                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12618                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12619                    language_settings::SoftWrap::None
12620                }
12621            };
12622            self.soft_wrap_mode_override = Some(soft_wrap);
12623        }
12624        cx.notify();
12625    }
12626
12627    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12628        let Some(workspace) = self.workspace() else {
12629            return;
12630        };
12631        let fs = workspace.read(cx).app_state().fs.clone();
12632        let current_show = TabBarSettings::get_global(cx).show;
12633        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12634            setting.show = Some(!current_show);
12635        });
12636    }
12637
12638    pub fn toggle_indent_guides(
12639        &mut self,
12640        _: &ToggleIndentGuides,
12641        _: &mut Window,
12642        cx: &mut Context<Self>,
12643    ) {
12644        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12645            self.buffer
12646                .read(cx)
12647                .settings_at(0, cx)
12648                .indent_guides
12649                .enabled
12650        });
12651        self.show_indent_guides = Some(!currently_enabled);
12652        cx.notify();
12653    }
12654
12655    fn should_show_indent_guides(&self) -> Option<bool> {
12656        self.show_indent_guides
12657    }
12658
12659    pub fn toggle_line_numbers(
12660        &mut self,
12661        _: &ToggleLineNumbers,
12662        _: &mut Window,
12663        cx: &mut Context<Self>,
12664    ) {
12665        let mut editor_settings = EditorSettings::get_global(cx).clone();
12666        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12667        EditorSettings::override_global(editor_settings, cx);
12668    }
12669
12670    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12671        self.use_relative_line_numbers
12672            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12673    }
12674
12675    pub fn toggle_relative_line_numbers(
12676        &mut self,
12677        _: &ToggleRelativeLineNumbers,
12678        _: &mut Window,
12679        cx: &mut Context<Self>,
12680    ) {
12681        let is_relative = self.should_use_relative_line_numbers(cx);
12682        self.set_relative_line_number(Some(!is_relative), cx)
12683    }
12684
12685    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12686        self.use_relative_line_numbers = is_relative;
12687        cx.notify();
12688    }
12689
12690    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12691        self.show_gutter = show_gutter;
12692        cx.notify();
12693    }
12694
12695    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12696        self.show_scrollbars = show_scrollbars;
12697        cx.notify();
12698    }
12699
12700    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12701        self.show_line_numbers = Some(show_line_numbers);
12702        cx.notify();
12703    }
12704
12705    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12706        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12707        cx.notify();
12708    }
12709
12710    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12711        self.show_code_actions = Some(show_code_actions);
12712        cx.notify();
12713    }
12714
12715    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12716        self.show_runnables = Some(show_runnables);
12717        cx.notify();
12718    }
12719
12720    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12721        if self.display_map.read(cx).masked != masked {
12722            self.display_map.update(cx, |map, _| map.masked = masked);
12723        }
12724        cx.notify()
12725    }
12726
12727    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12728        self.show_wrap_guides = Some(show_wrap_guides);
12729        cx.notify();
12730    }
12731
12732    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12733        self.show_indent_guides = Some(show_indent_guides);
12734        cx.notify();
12735    }
12736
12737    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12738        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12739            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12740                if let Some(dir) = file.abs_path(cx).parent() {
12741                    return Some(dir.to_owned());
12742                }
12743            }
12744
12745            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12746                return Some(project_path.path.to_path_buf());
12747            }
12748        }
12749
12750        None
12751    }
12752
12753    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12754        self.active_excerpt(cx)?
12755            .1
12756            .read(cx)
12757            .file()
12758            .and_then(|f| f.as_local())
12759    }
12760
12761    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12762        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12763            let project_path = buffer.read(cx).project_path(cx)?;
12764            let project = self.project.as_ref()?.read(cx);
12765            project.absolute_path(&project_path, cx)
12766        })
12767    }
12768
12769    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12770        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12771            let project_path = buffer.read(cx).project_path(cx)?;
12772            let project = self.project.as_ref()?.read(cx);
12773            let entry = project.entry_for_path(&project_path, cx)?;
12774            let path = entry.path.to_path_buf();
12775            Some(path)
12776        })
12777    }
12778
12779    pub fn reveal_in_finder(
12780        &mut self,
12781        _: &RevealInFileManager,
12782        _window: &mut Window,
12783        cx: &mut Context<Self>,
12784    ) {
12785        if let Some(target) = self.target_file(cx) {
12786            cx.reveal_path(&target.abs_path(cx));
12787        }
12788    }
12789
12790    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12791        if let Some(path) = self.target_file_abs_path(cx) {
12792            if let Some(path) = path.to_str() {
12793                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12794            }
12795        }
12796    }
12797
12798    pub fn copy_relative_path(
12799        &mut self,
12800        _: &CopyRelativePath,
12801        _window: &mut Window,
12802        cx: &mut Context<Self>,
12803    ) {
12804        if let Some(path) = self.target_file_path(cx) {
12805            if let Some(path) = path.to_str() {
12806                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12807            }
12808        }
12809    }
12810
12811    pub fn toggle_git_blame(
12812        &mut self,
12813        _: &ToggleGitBlame,
12814        window: &mut Window,
12815        cx: &mut Context<Self>,
12816    ) {
12817        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12818
12819        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12820            self.start_git_blame(true, window, cx);
12821        }
12822
12823        cx.notify();
12824    }
12825
12826    pub fn toggle_git_blame_inline(
12827        &mut self,
12828        _: &ToggleGitBlameInline,
12829        window: &mut Window,
12830        cx: &mut Context<Self>,
12831    ) {
12832        self.toggle_git_blame_inline_internal(true, window, cx);
12833        cx.notify();
12834    }
12835
12836    pub fn git_blame_inline_enabled(&self) -> bool {
12837        self.git_blame_inline_enabled
12838    }
12839
12840    pub fn toggle_selection_menu(
12841        &mut self,
12842        _: &ToggleSelectionMenu,
12843        _: &mut Window,
12844        cx: &mut Context<Self>,
12845    ) {
12846        self.show_selection_menu = self
12847            .show_selection_menu
12848            .map(|show_selections_menu| !show_selections_menu)
12849            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12850
12851        cx.notify();
12852    }
12853
12854    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12855        self.show_selection_menu
12856            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12857    }
12858
12859    fn start_git_blame(
12860        &mut self,
12861        user_triggered: bool,
12862        window: &mut Window,
12863        cx: &mut Context<Self>,
12864    ) {
12865        if let Some(project) = self.project.as_ref() {
12866            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12867                return;
12868            };
12869
12870            if buffer.read(cx).file().is_none() {
12871                return;
12872            }
12873
12874            let focused = self.focus_handle(cx).contains_focused(window, cx);
12875
12876            let project = project.clone();
12877            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12878            self.blame_subscription =
12879                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12880            self.blame = Some(blame);
12881        }
12882    }
12883
12884    fn toggle_git_blame_inline_internal(
12885        &mut self,
12886        user_triggered: bool,
12887        window: &mut Window,
12888        cx: &mut Context<Self>,
12889    ) {
12890        if self.git_blame_inline_enabled {
12891            self.git_blame_inline_enabled = false;
12892            self.show_git_blame_inline = false;
12893            self.show_git_blame_inline_delay_task.take();
12894        } else {
12895            self.git_blame_inline_enabled = true;
12896            self.start_git_blame_inline(user_triggered, window, cx);
12897        }
12898
12899        cx.notify();
12900    }
12901
12902    fn start_git_blame_inline(
12903        &mut self,
12904        user_triggered: bool,
12905        window: &mut Window,
12906        cx: &mut Context<Self>,
12907    ) {
12908        self.start_git_blame(user_triggered, window, cx);
12909
12910        if ProjectSettings::get_global(cx)
12911            .git
12912            .inline_blame_delay()
12913            .is_some()
12914        {
12915            self.start_inline_blame_timer(window, cx);
12916        } else {
12917            self.show_git_blame_inline = true
12918        }
12919    }
12920
12921    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12922        self.blame.as_ref()
12923    }
12924
12925    pub fn show_git_blame_gutter(&self) -> bool {
12926        self.show_git_blame_gutter
12927    }
12928
12929    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12930        self.show_git_blame_gutter && self.has_blame_entries(cx)
12931    }
12932
12933    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12934        self.show_git_blame_inline
12935            && self.focus_handle.is_focused(window)
12936            && !self.newest_selection_head_on_empty_line(cx)
12937            && self.has_blame_entries(cx)
12938    }
12939
12940    fn has_blame_entries(&self, cx: &App) -> bool {
12941        self.blame()
12942            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12943    }
12944
12945    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12946        let cursor_anchor = self.selections.newest_anchor().head();
12947
12948        let snapshot = self.buffer.read(cx).snapshot(cx);
12949        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12950
12951        snapshot.line_len(buffer_row) == 0
12952    }
12953
12954    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12955        let buffer_and_selection = maybe!({
12956            let selection = self.selections.newest::<Point>(cx);
12957            let selection_range = selection.range();
12958
12959            let multi_buffer = self.buffer().read(cx);
12960            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12961            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12962
12963            let (buffer, range, _) = if selection.reversed {
12964                buffer_ranges.first()
12965            } else {
12966                buffer_ranges.last()
12967            }?;
12968
12969            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12970                ..text::ToPoint::to_point(&range.end, &buffer).row;
12971            Some((
12972                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12973                selection,
12974            ))
12975        });
12976
12977        let Some((buffer, selection)) = buffer_and_selection else {
12978            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12979        };
12980
12981        let Some(project) = self.project.as_ref() else {
12982            return Task::ready(Err(anyhow!("editor does not have project")));
12983        };
12984
12985        project.update(cx, |project, cx| {
12986            project.get_permalink_to_line(&buffer, selection, cx)
12987        })
12988    }
12989
12990    pub fn copy_permalink_to_line(
12991        &mut self,
12992        _: &CopyPermalinkToLine,
12993        window: &mut Window,
12994        cx: &mut Context<Self>,
12995    ) {
12996        let permalink_task = self.get_permalink_to_line(cx);
12997        let workspace = self.workspace();
12998
12999        cx.spawn_in(window, |_, mut cx| async move {
13000            match permalink_task.await {
13001                Ok(permalink) => {
13002                    cx.update(|_, cx| {
13003                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13004                    })
13005                    .ok();
13006                }
13007                Err(err) => {
13008                    let message = format!("Failed to copy permalink: {err}");
13009
13010                    Err::<(), anyhow::Error>(err).log_err();
13011
13012                    if let Some(workspace) = workspace {
13013                        workspace
13014                            .update_in(&mut cx, |workspace, _, cx| {
13015                                struct CopyPermalinkToLine;
13016
13017                                workspace.show_toast(
13018                                    Toast::new(
13019                                        NotificationId::unique::<CopyPermalinkToLine>(),
13020                                        message,
13021                                    ),
13022                                    cx,
13023                                )
13024                            })
13025                            .ok();
13026                    }
13027                }
13028            }
13029        })
13030        .detach();
13031    }
13032
13033    pub fn copy_file_location(
13034        &mut self,
13035        _: &CopyFileLocation,
13036        _: &mut Window,
13037        cx: &mut Context<Self>,
13038    ) {
13039        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13040        if let Some(file) = self.target_file(cx) {
13041            if let Some(path) = file.path().to_str() {
13042                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13043            }
13044        }
13045    }
13046
13047    pub fn open_permalink_to_line(
13048        &mut self,
13049        _: &OpenPermalinkToLine,
13050        window: &mut Window,
13051        cx: &mut Context<Self>,
13052    ) {
13053        let permalink_task = self.get_permalink_to_line(cx);
13054        let workspace = self.workspace();
13055
13056        cx.spawn_in(window, |_, mut cx| async move {
13057            match permalink_task.await {
13058                Ok(permalink) => {
13059                    cx.update(|_, cx| {
13060                        cx.open_url(permalink.as_ref());
13061                    })
13062                    .ok();
13063                }
13064                Err(err) => {
13065                    let message = format!("Failed to open permalink: {err}");
13066
13067                    Err::<(), anyhow::Error>(err).log_err();
13068
13069                    if let Some(workspace) = workspace {
13070                        workspace
13071                            .update(&mut cx, |workspace, cx| {
13072                                struct OpenPermalinkToLine;
13073
13074                                workspace.show_toast(
13075                                    Toast::new(
13076                                        NotificationId::unique::<OpenPermalinkToLine>(),
13077                                        message,
13078                                    ),
13079                                    cx,
13080                                )
13081                            })
13082                            .ok();
13083                    }
13084                }
13085            }
13086        })
13087        .detach();
13088    }
13089
13090    pub fn insert_uuid_v4(
13091        &mut self,
13092        _: &InsertUuidV4,
13093        window: &mut Window,
13094        cx: &mut Context<Self>,
13095    ) {
13096        self.insert_uuid(UuidVersion::V4, window, cx);
13097    }
13098
13099    pub fn insert_uuid_v7(
13100        &mut self,
13101        _: &InsertUuidV7,
13102        window: &mut Window,
13103        cx: &mut Context<Self>,
13104    ) {
13105        self.insert_uuid(UuidVersion::V7, window, cx);
13106    }
13107
13108    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13109        self.transact(window, cx, |this, window, cx| {
13110            let edits = this
13111                .selections
13112                .all::<Point>(cx)
13113                .into_iter()
13114                .map(|selection| {
13115                    let uuid = match version {
13116                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13117                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13118                    };
13119
13120                    (selection.range(), uuid.to_string())
13121                });
13122            this.edit(edits, cx);
13123            this.refresh_inline_completion(true, false, window, cx);
13124        });
13125    }
13126
13127    pub fn open_selections_in_multibuffer(
13128        &mut self,
13129        _: &OpenSelectionsInMultibuffer,
13130        window: &mut Window,
13131        cx: &mut Context<Self>,
13132    ) {
13133        let multibuffer = self.buffer.read(cx);
13134
13135        let Some(buffer) = multibuffer.as_singleton() else {
13136            return;
13137        };
13138
13139        let Some(workspace) = self.workspace() else {
13140            return;
13141        };
13142
13143        let locations = self
13144            .selections
13145            .disjoint_anchors()
13146            .iter()
13147            .map(|range| Location {
13148                buffer: buffer.clone(),
13149                range: range.start.text_anchor..range.end.text_anchor,
13150            })
13151            .collect::<Vec<_>>();
13152
13153        let title = multibuffer.title(cx).to_string();
13154
13155        cx.spawn_in(window, |_, mut cx| async move {
13156            workspace.update_in(&mut cx, |workspace, window, cx| {
13157                Self::open_locations_in_multibuffer(
13158                    workspace,
13159                    locations,
13160                    format!("Selections for '{title}'"),
13161                    false,
13162                    MultibufferSelectionMode::All,
13163                    window,
13164                    cx,
13165                );
13166            })
13167        })
13168        .detach();
13169    }
13170
13171    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13172    /// last highlight added will be used.
13173    ///
13174    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13175    pub fn highlight_rows<T: 'static>(
13176        &mut self,
13177        range: Range<Anchor>,
13178        color: Hsla,
13179        should_autoscroll: bool,
13180        cx: &mut Context<Self>,
13181    ) {
13182        let snapshot = self.buffer().read(cx).snapshot(cx);
13183        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13184        let ix = row_highlights.binary_search_by(|highlight| {
13185            Ordering::Equal
13186                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13187                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13188        });
13189
13190        if let Err(mut ix) = ix {
13191            let index = post_inc(&mut self.highlight_order);
13192
13193            // If this range intersects with the preceding highlight, then merge it with
13194            // the preceding highlight. Otherwise insert a new highlight.
13195            let mut merged = false;
13196            if ix > 0 {
13197                let prev_highlight = &mut row_highlights[ix - 1];
13198                if prev_highlight
13199                    .range
13200                    .end
13201                    .cmp(&range.start, &snapshot)
13202                    .is_ge()
13203                {
13204                    ix -= 1;
13205                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13206                        prev_highlight.range.end = range.end;
13207                    }
13208                    merged = true;
13209                    prev_highlight.index = index;
13210                    prev_highlight.color = color;
13211                    prev_highlight.should_autoscroll = should_autoscroll;
13212                }
13213            }
13214
13215            if !merged {
13216                row_highlights.insert(
13217                    ix,
13218                    RowHighlight {
13219                        range: range.clone(),
13220                        index,
13221                        color,
13222                        should_autoscroll,
13223                    },
13224                );
13225            }
13226
13227            // If any of the following highlights intersect with this one, merge them.
13228            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13229                let highlight = &row_highlights[ix];
13230                if next_highlight
13231                    .range
13232                    .start
13233                    .cmp(&highlight.range.end, &snapshot)
13234                    .is_le()
13235                {
13236                    if next_highlight
13237                        .range
13238                        .end
13239                        .cmp(&highlight.range.end, &snapshot)
13240                        .is_gt()
13241                    {
13242                        row_highlights[ix].range.end = next_highlight.range.end;
13243                    }
13244                    row_highlights.remove(ix + 1);
13245                } else {
13246                    break;
13247                }
13248            }
13249        }
13250    }
13251
13252    /// Remove any highlighted row ranges of the given type that intersect the
13253    /// given ranges.
13254    pub fn remove_highlighted_rows<T: 'static>(
13255        &mut self,
13256        ranges_to_remove: Vec<Range<Anchor>>,
13257        cx: &mut Context<Self>,
13258    ) {
13259        let snapshot = self.buffer().read(cx).snapshot(cx);
13260        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13261        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13262        row_highlights.retain(|highlight| {
13263            while let Some(range_to_remove) = ranges_to_remove.peek() {
13264                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13265                    Ordering::Less | Ordering::Equal => {
13266                        ranges_to_remove.next();
13267                    }
13268                    Ordering::Greater => {
13269                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13270                            Ordering::Less | Ordering::Equal => {
13271                                return false;
13272                            }
13273                            Ordering::Greater => break,
13274                        }
13275                    }
13276                }
13277            }
13278
13279            true
13280        })
13281    }
13282
13283    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13284    pub fn clear_row_highlights<T: 'static>(&mut self) {
13285        self.highlighted_rows.remove(&TypeId::of::<T>());
13286    }
13287
13288    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13289    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13290        self.highlighted_rows
13291            .get(&TypeId::of::<T>())
13292            .map_or(&[] as &[_], |vec| vec.as_slice())
13293            .iter()
13294            .map(|highlight| (highlight.range.clone(), highlight.color))
13295    }
13296
13297    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13298    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13299    /// Allows to ignore certain kinds of highlights.
13300    pub fn highlighted_display_rows(
13301        &self,
13302        window: &mut Window,
13303        cx: &mut App,
13304    ) -> BTreeMap<DisplayRow, Hsla> {
13305        let snapshot = self.snapshot(window, cx);
13306        let mut used_highlight_orders = HashMap::default();
13307        self.highlighted_rows
13308            .iter()
13309            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13310            .fold(
13311                BTreeMap::<DisplayRow, Hsla>::new(),
13312                |mut unique_rows, highlight| {
13313                    let start = highlight.range.start.to_display_point(&snapshot);
13314                    let end = highlight.range.end.to_display_point(&snapshot);
13315                    let start_row = start.row().0;
13316                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13317                        && end.column() == 0
13318                    {
13319                        end.row().0.saturating_sub(1)
13320                    } else {
13321                        end.row().0
13322                    };
13323                    for row in start_row..=end_row {
13324                        let used_index =
13325                            used_highlight_orders.entry(row).or_insert(highlight.index);
13326                        if highlight.index >= *used_index {
13327                            *used_index = highlight.index;
13328                            unique_rows.insert(DisplayRow(row), highlight.color);
13329                        }
13330                    }
13331                    unique_rows
13332                },
13333            )
13334    }
13335
13336    pub fn highlighted_display_row_for_autoscroll(
13337        &self,
13338        snapshot: &DisplaySnapshot,
13339    ) -> Option<DisplayRow> {
13340        self.highlighted_rows
13341            .values()
13342            .flat_map(|highlighted_rows| highlighted_rows.iter())
13343            .filter_map(|highlight| {
13344                if highlight.should_autoscroll {
13345                    Some(highlight.range.start.to_display_point(snapshot).row())
13346                } else {
13347                    None
13348                }
13349            })
13350            .min()
13351    }
13352
13353    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13354        self.highlight_background::<SearchWithinRange>(
13355            ranges,
13356            |colors| colors.editor_document_highlight_read_background,
13357            cx,
13358        )
13359    }
13360
13361    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13362        self.breadcrumb_header = Some(new_header);
13363    }
13364
13365    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13366        self.clear_background_highlights::<SearchWithinRange>(cx);
13367    }
13368
13369    pub fn highlight_background<T: 'static>(
13370        &mut self,
13371        ranges: &[Range<Anchor>],
13372        color_fetcher: fn(&ThemeColors) -> Hsla,
13373        cx: &mut Context<Self>,
13374    ) {
13375        self.background_highlights
13376            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13377        self.scrollbar_marker_state.dirty = true;
13378        cx.notify();
13379    }
13380
13381    pub fn clear_background_highlights<T: 'static>(
13382        &mut self,
13383        cx: &mut Context<Self>,
13384    ) -> Option<BackgroundHighlight> {
13385        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13386        if !text_highlights.1.is_empty() {
13387            self.scrollbar_marker_state.dirty = true;
13388            cx.notify();
13389        }
13390        Some(text_highlights)
13391    }
13392
13393    pub fn highlight_gutter<T: 'static>(
13394        &mut self,
13395        ranges: &[Range<Anchor>],
13396        color_fetcher: fn(&App) -> Hsla,
13397        cx: &mut Context<Self>,
13398    ) {
13399        self.gutter_highlights
13400            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13401        cx.notify();
13402    }
13403
13404    pub fn clear_gutter_highlights<T: 'static>(
13405        &mut self,
13406        cx: &mut Context<Self>,
13407    ) -> Option<GutterHighlight> {
13408        cx.notify();
13409        self.gutter_highlights.remove(&TypeId::of::<T>())
13410    }
13411
13412    #[cfg(feature = "test-support")]
13413    pub fn all_text_background_highlights(
13414        &self,
13415        window: &mut Window,
13416        cx: &mut Context<Self>,
13417    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13418        let snapshot = self.snapshot(window, cx);
13419        let buffer = &snapshot.buffer_snapshot;
13420        let start = buffer.anchor_before(0);
13421        let end = buffer.anchor_after(buffer.len());
13422        let theme = cx.theme().colors();
13423        self.background_highlights_in_range(start..end, &snapshot, theme)
13424    }
13425
13426    #[cfg(feature = "test-support")]
13427    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13428        let snapshot = self.buffer().read(cx).snapshot(cx);
13429
13430        let highlights = self
13431            .background_highlights
13432            .get(&TypeId::of::<items::BufferSearchHighlights>());
13433
13434        if let Some((_color, ranges)) = highlights {
13435            ranges
13436                .iter()
13437                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13438                .collect_vec()
13439        } else {
13440            vec![]
13441        }
13442    }
13443
13444    fn document_highlights_for_position<'a>(
13445        &'a self,
13446        position: Anchor,
13447        buffer: &'a MultiBufferSnapshot,
13448    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13449        let read_highlights = self
13450            .background_highlights
13451            .get(&TypeId::of::<DocumentHighlightRead>())
13452            .map(|h| &h.1);
13453        let write_highlights = self
13454            .background_highlights
13455            .get(&TypeId::of::<DocumentHighlightWrite>())
13456            .map(|h| &h.1);
13457        let left_position = position.bias_left(buffer);
13458        let right_position = position.bias_right(buffer);
13459        read_highlights
13460            .into_iter()
13461            .chain(write_highlights)
13462            .flat_map(move |ranges| {
13463                let start_ix = match ranges.binary_search_by(|probe| {
13464                    let cmp = probe.end.cmp(&left_position, buffer);
13465                    if cmp.is_ge() {
13466                        Ordering::Greater
13467                    } else {
13468                        Ordering::Less
13469                    }
13470                }) {
13471                    Ok(i) | Err(i) => i,
13472                };
13473
13474                ranges[start_ix..]
13475                    .iter()
13476                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13477            })
13478    }
13479
13480    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13481        self.background_highlights
13482            .get(&TypeId::of::<T>())
13483            .map_or(false, |(_, highlights)| !highlights.is_empty())
13484    }
13485
13486    pub fn background_highlights_in_range(
13487        &self,
13488        search_range: Range<Anchor>,
13489        display_snapshot: &DisplaySnapshot,
13490        theme: &ThemeColors,
13491    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13492        let mut results = Vec::new();
13493        for (color_fetcher, ranges) in self.background_highlights.values() {
13494            let color = color_fetcher(theme);
13495            let start_ix = match ranges.binary_search_by(|probe| {
13496                let cmp = probe
13497                    .end
13498                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13499                if cmp.is_gt() {
13500                    Ordering::Greater
13501                } else {
13502                    Ordering::Less
13503                }
13504            }) {
13505                Ok(i) | Err(i) => i,
13506            };
13507            for range in &ranges[start_ix..] {
13508                if range
13509                    .start
13510                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13511                    .is_ge()
13512                {
13513                    break;
13514                }
13515
13516                let start = range.start.to_display_point(display_snapshot);
13517                let end = range.end.to_display_point(display_snapshot);
13518                results.push((start..end, color))
13519            }
13520        }
13521        results
13522    }
13523
13524    pub fn background_highlight_row_ranges<T: 'static>(
13525        &self,
13526        search_range: Range<Anchor>,
13527        display_snapshot: &DisplaySnapshot,
13528        count: usize,
13529    ) -> Vec<RangeInclusive<DisplayPoint>> {
13530        let mut results = Vec::new();
13531        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13532            return vec![];
13533        };
13534
13535        let start_ix = match ranges.binary_search_by(|probe| {
13536            let cmp = probe
13537                .end
13538                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13539            if cmp.is_gt() {
13540                Ordering::Greater
13541            } else {
13542                Ordering::Less
13543            }
13544        }) {
13545            Ok(i) | Err(i) => i,
13546        };
13547        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13548            if let (Some(start_display), Some(end_display)) = (start, end) {
13549                results.push(
13550                    start_display.to_display_point(display_snapshot)
13551                        ..=end_display.to_display_point(display_snapshot),
13552                );
13553            }
13554        };
13555        let mut start_row: Option<Point> = None;
13556        let mut end_row: Option<Point> = None;
13557        if ranges.len() > count {
13558            return Vec::new();
13559        }
13560        for range in &ranges[start_ix..] {
13561            if range
13562                .start
13563                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13564                .is_ge()
13565            {
13566                break;
13567            }
13568            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13569            if let Some(current_row) = &end_row {
13570                if end.row == current_row.row {
13571                    continue;
13572                }
13573            }
13574            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13575            if start_row.is_none() {
13576                assert_eq!(end_row, None);
13577                start_row = Some(start);
13578                end_row = Some(end);
13579                continue;
13580            }
13581            if let Some(current_end) = end_row.as_mut() {
13582                if start.row > current_end.row + 1 {
13583                    push_region(start_row, end_row);
13584                    start_row = Some(start);
13585                    end_row = Some(end);
13586                } else {
13587                    // Merge two hunks.
13588                    *current_end = end;
13589                }
13590            } else {
13591                unreachable!();
13592            }
13593        }
13594        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13595        push_region(start_row, end_row);
13596        results
13597    }
13598
13599    pub fn gutter_highlights_in_range(
13600        &self,
13601        search_range: Range<Anchor>,
13602        display_snapshot: &DisplaySnapshot,
13603        cx: &App,
13604    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13605        let mut results = Vec::new();
13606        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13607            let color = color_fetcher(cx);
13608            let start_ix = match ranges.binary_search_by(|probe| {
13609                let cmp = probe
13610                    .end
13611                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13612                if cmp.is_gt() {
13613                    Ordering::Greater
13614                } else {
13615                    Ordering::Less
13616                }
13617            }) {
13618                Ok(i) | Err(i) => i,
13619            };
13620            for range in &ranges[start_ix..] {
13621                if range
13622                    .start
13623                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13624                    .is_ge()
13625                {
13626                    break;
13627                }
13628
13629                let start = range.start.to_display_point(display_snapshot);
13630                let end = range.end.to_display_point(display_snapshot);
13631                results.push((start..end, color))
13632            }
13633        }
13634        results
13635    }
13636
13637    /// Get the text ranges corresponding to the redaction query
13638    pub fn redacted_ranges(
13639        &self,
13640        search_range: Range<Anchor>,
13641        display_snapshot: &DisplaySnapshot,
13642        cx: &App,
13643    ) -> Vec<Range<DisplayPoint>> {
13644        display_snapshot
13645            .buffer_snapshot
13646            .redacted_ranges(search_range, |file| {
13647                if let Some(file) = file {
13648                    file.is_private()
13649                        && EditorSettings::get(
13650                            Some(SettingsLocation {
13651                                worktree_id: file.worktree_id(cx),
13652                                path: file.path().as_ref(),
13653                            }),
13654                            cx,
13655                        )
13656                        .redact_private_values
13657                } else {
13658                    false
13659                }
13660            })
13661            .map(|range| {
13662                range.start.to_display_point(display_snapshot)
13663                    ..range.end.to_display_point(display_snapshot)
13664            })
13665            .collect()
13666    }
13667
13668    pub fn highlight_text<T: 'static>(
13669        &mut self,
13670        ranges: Vec<Range<Anchor>>,
13671        style: HighlightStyle,
13672        cx: &mut Context<Self>,
13673    ) {
13674        self.display_map.update(cx, |map, _| {
13675            map.highlight_text(TypeId::of::<T>(), ranges, style)
13676        });
13677        cx.notify();
13678    }
13679
13680    pub(crate) fn highlight_inlays<T: 'static>(
13681        &mut self,
13682        highlights: Vec<InlayHighlight>,
13683        style: HighlightStyle,
13684        cx: &mut Context<Self>,
13685    ) {
13686        self.display_map.update(cx, |map, _| {
13687            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13688        });
13689        cx.notify();
13690    }
13691
13692    pub fn text_highlights<'a, T: 'static>(
13693        &'a self,
13694        cx: &'a App,
13695    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13696        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13697    }
13698
13699    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13700        let cleared = self
13701            .display_map
13702            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13703        if cleared {
13704            cx.notify();
13705        }
13706    }
13707
13708    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13709        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13710            && self.focus_handle.is_focused(window)
13711    }
13712
13713    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13714        self.show_cursor_when_unfocused = is_enabled;
13715        cx.notify();
13716    }
13717
13718    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13719        self.project
13720            .as_ref()
13721            .map(|project| project.read(cx).lsp_store())
13722    }
13723
13724    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13725        cx.notify();
13726    }
13727
13728    fn on_buffer_event(
13729        &mut self,
13730        multibuffer: &Entity<MultiBuffer>,
13731        event: &multi_buffer::Event,
13732        window: &mut Window,
13733        cx: &mut Context<Self>,
13734    ) {
13735        match event {
13736            multi_buffer::Event::Edited {
13737                singleton_buffer_edited,
13738                edited_buffer: buffer_edited,
13739            } => {
13740                self.scrollbar_marker_state.dirty = true;
13741                self.active_indent_guides_state.dirty = true;
13742                self.refresh_active_diagnostics(cx);
13743                self.refresh_code_actions(window, cx);
13744                if self.has_active_inline_completion() {
13745                    self.update_visible_inline_completion(window, cx);
13746                }
13747                if let Some(buffer) = buffer_edited {
13748                    let buffer_id = buffer.read(cx).remote_id();
13749                    if !self.registered_buffers.contains_key(&buffer_id) {
13750                        if let Some(lsp_store) = self.lsp_store(cx) {
13751                            lsp_store.update(cx, |lsp_store, cx| {
13752                                self.registered_buffers.insert(
13753                                    buffer_id,
13754                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13755                                );
13756                            })
13757                        }
13758                    }
13759                }
13760                cx.emit(EditorEvent::BufferEdited);
13761                cx.emit(SearchEvent::MatchesInvalidated);
13762                if *singleton_buffer_edited {
13763                    if let Some(project) = &self.project {
13764                        let project = project.read(cx);
13765                        #[allow(clippy::mutable_key_type)]
13766                        let languages_affected = multibuffer
13767                            .read(cx)
13768                            .all_buffers()
13769                            .into_iter()
13770                            .filter_map(|buffer| {
13771                                let buffer = buffer.read(cx);
13772                                let language = buffer.language()?;
13773                                if project.is_local()
13774                                    && project
13775                                        .language_servers_for_local_buffer(buffer, cx)
13776                                        .count()
13777                                        == 0
13778                                {
13779                                    None
13780                                } else {
13781                                    Some(language)
13782                                }
13783                            })
13784                            .cloned()
13785                            .collect::<HashSet<_>>();
13786                        if !languages_affected.is_empty() {
13787                            self.refresh_inlay_hints(
13788                                InlayHintRefreshReason::BufferEdited(languages_affected),
13789                                cx,
13790                            );
13791                        }
13792                    }
13793                }
13794
13795                let Some(project) = &self.project else { return };
13796                let (telemetry, is_via_ssh) = {
13797                    let project = project.read(cx);
13798                    let telemetry = project.client().telemetry().clone();
13799                    let is_via_ssh = project.is_via_ssh();
13800                    (telemetry, is_via_ssh)
13801                };
13802                refresh_linked_ranges(self, window, cx);
13803                telemetry.log_edit_event("editor", is_via_ssh);
13804            }
13805            multi_buffer::Event::ExcerptsAdded {
13806                buffer,
13807                predecessor,
13808                excerpts,
13809            } => {
13810                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13811                let buffer_id = buffer.read(cx).remote_id();
13812                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13813                    if let Some(project) = &self.project {
13814                        get_uncommitted_diff_for_buffer(
13815                            project,
13816                            [buffer.clone()],
13817                            self.buffer.clone(),
13818                            cx,
13819                        );
13820                    }
13821                }
13822                cx.emit(EditorEvent::ExcerptsAdded {
13823                    buffer: buffer.clone(),
13824                    predecessor: *predecessor,
13825                    excerpts: excerpts.clone(),
13826                });
13827                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13828            }
13829            multi_buffer::Event::ExcerptsRemoved { ids } => {
13830                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13831                let buffer = self.buffer.read(cx);
13832                self.registered_buffers
13833                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13834                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13835            }
13836            multi_buffer::Event::ExcerptsEdited { ids } => {
13837                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13838            }
13839            multi_buffer::Event::ExcerptsExpanded { ids } => {
13840                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13841                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13842            }
13843            multi_buffer::Event::Reparsed(buffer_id) => {
13844                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13845
13846                cx.emit(EditorEvent::Reparsed(*buffer_id));
13847            }
13848            multi_buffer::Event::DiffHunksToggled => {
13849                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13850            }
13851            multi_buffer::Event::LanguageChanged(buffer_id) => {
13852                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13853                cx.emit(EditorEvent::Reparsed(*buffer_id));
13854                cx.notify();
13855            }
13856            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13857            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13858            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13859                cx.emit(EditorEvent::TitleChanged)
13860            }
13861            // multi_buffer::Event::DiffBaseChanged => {
13862            //     self.scrollbar_marker_state.dirty = true;
13863            //     cx.emit(EditorEvent::DiffBaseChanged);
13864            //     cx.notify();
13865            // }
13866            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13867            multi_buffer::Event::DiagnosticsUpdated => {
13868                self.refresh_active_diagnostics(cx);
13869                self.scrollbar_marker_state.dirty = true;
13870                cx.notify();
13871            }
13872            _ => {}
13873        };
13874    }
13875
13876    fn on_display_map_changed(
13877        &mut self,
13878        _: Entity<DisplayMap>,
13879        _: &mut Window,
13880        cx: &mut Context<Self>,
13881    ) {
13882        cx.notify();
13883    }
13884
13885    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13886        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13887        self.refresh_inline_completion(true, false, window, cx);
13888        self.refresh_inlay_hints(
13889            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13890                self.selections.newest_anchor().head(),
13891                &self.buffer.read(cx).snapshot(cx),
13892                cx,
13893            )),
13894            cx,
13895        );
13896
13897        let old_cursor_shape = self.cursor_shape;
13898
13899        {
13900            let editor_settings = EditorSettings::get_global(cx);
13901            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13902            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13903            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13904        }
13905
13906        if old_cursor_shape != self.cursor_shape {
13907            cx.emit(EditorEvent::CursorShapeChanged);
13908        }
13909
13910        let project_settings = ProjectSettings::get_global(cx);
13911        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13912
13913        if self.mode == EditorMode::Full {
13914            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13915            if self.git_blame_inline_enabled != inline_blame_enabled {
13916                self.toggle_git_blame_inline_internal(false, window, cx);
13917            }
13918        }
13919
13920        cx.notify();
13921    }
13922
13923    pub fn set_searchable(&mut self, searchable: bool) {
13924        self.searchable = searchable;
13925    }
13926
13927    pub fn searchable(&self) -> bool {
13928        self.searchable
13929    }
13930
13931    fn open_proposed_changes_editor(
13932        &mut self,
13933        _: &OpenProposedChangesEditor,
13934        window: &mut Window,
13935        cx: &mut Context<Self>,
13936    ) {
13937        let Some(workspace) = self.workspace() else {
13938            cx.propagate();
13939            return;
13940        };
13941
13942        let selections = self.selections.all::<usize>(cx);
13943        let multi_buffer = self.buffer.read(cx);
13944        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13945        let mut new_selections_by_buffer = HashMap::default();
13946        for selection in selections {
13947            for (buffer, range, _) in
13948                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13949            {
13950                let mut range = range.to_point(buffer);
13951                range.start.column = 0;
13952                range.end.column = buffer.line_len(range.end.row);
13953                new_selections_by_buffer
13954                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13955                    .or_insert(Vec::new())
13956                    .push(range)
13957            }
13958        }
13959
13960        let proposed_changes_buffers = new_selections_by_buffer
13961            .into_iter()
13962            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13963            .collect::<Vec<_>>();
13964        let proposed_changes_editor = cx.new(|cx| {
13965            ProposedChangesEditor::new(
13966                "Proposed changes",
13967                proposed_changes_buffers,
13968                self.project.clone(),
13969                window,
13970                cx,
13971            )
13972        });
13973
13974        window.defer(cx, move |window, cx| {
13975            workspace.update(cx, |workspace, cx| {
13976                workspace.active_pane().update(cx, |pane, cx| {
13977                    pane.add_item(
13978                        Box::new(proposed_changes_editor),
13979                        true,
13980                        true,
13981                        None,
13982                        window,
13983                        cx,
13984                    );
13985                });
13986            });
13987        });
13988    }
13989
13990    pub fn open_excerpts_in_split(
13991        &mut self,
13992        _: &OpenExcerptsSplit,
13993        window: &mut Window,
13994        cx: &mut Context<Self>,
13995    ) {
13996        self.open_excerpts_common(None, true, window, cx)
13997    }
13998
13999    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14000        self.open_excerpts_common(None, false, window, cx)
14001    }
14002
14003    fn open_excerpts_common(
14004        &mut self,
14005        jump_data: Option<JumpData>,
14006        split: bool,
14007        window: &mut Window,
14008        cx: &mut Context<Self>,
14009    ) {
14010        let Some(workspace) = self.workspace() else {
14011            cx.propagate();
14012            return;
14013        };
14014
14015        if self.buffer.read(cx).is_singleton() {
14016            cx.propagate();
14017            return;
14018        }
14019
14020        let mut new_selections_by_buffer = HashMap::default();
14021        match &jump_data {
14022            Some(JumpData::MultiBufferPoint {
14023                excerpt_id,
14024                position,
14025                anchor,
14026                line_offset_from_top,
14027            }) => {
14028                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14029                if let Some(buffer) = multi_buffer_snapshot
14030                    .buffer_id_for_excerpt(*excerpt_id)
14031                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14032                {
14033                    let buffer_snapshot = buffer.read(cx).snapshot();
14034                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14035                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14036                    } else {
14037                        buffer_snapshot.clip_point(*position, Bias::Left)
14038                    };
14039                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14040                    new_selections_by_buffer.insert(
14041                        buffer,
14042                        (
14043                            vec![jump_to_offset..jump_to_offset],
14044                            Some(*line_offset_from_top),
14045                        ),
14046                    );
14047                }
14048            }
14049            Some(JumpData::MultiBufferRow {
14050                row,
14051                line_offset_from_top,
14052            }) => {
14053                let point = MultiBufferPoint::new(row.0, 0);
14054                if let Some((buffer, buffer_point, _)) =
14055                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14056                {
14057                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14058                    new_selections_by_buffer
14059                        .entry(buffer)
14060                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14061                        .0
14062                        .push(buffer_offset..buffer_offset)
14063                }
14064            }
14065            None => {
14066                let selections = self.selections.all::<usize>(cx);
14067                let multi_buffer = self.buffer.read(cx);
14068                for selection in selections {
14069                    for (buffer, mut range, _) in multi_buffer
14070                        .snapshot(cx)
14071                        .range_to_buffer_ranges(selection.range())
14072                    {
14073                        // When editing branch buffers, jump to the corresponding location
14074                        // in their base buffer.
14075                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14076                        let buffer = buffer_handle.read(cx);
14077                        if let Some(base_buffer) = buffer.base_buffer() {
14078                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14079                            buffer_handle = base_buffer;
14080                        }
14081
14082                        if selection.reversed {
14083                            mem::swap(&mut range.start, &mut range.end);
14084                        }
14085                        new_selections_by_buffer
14086                            .entry(buffer_handle)
14087                            .or_insert((Vec::new(), None))
14088                            .0
14089                            .push(range)
14090                    }
14091                }
14092            }
14093        }
14094
14095        if new_selections_by_buffer.is_empty() {
14096            return;
14097        }
14098
14099        // We defer the pane interaction because we ourselves are a workspace item
14100        // and activating a new item causes the pane to call a method on us reentrantly,
14101        // which panics if we're on the stack.
14102        window.defer(cx, move |window, cx| {
14103            workspace.update(cx, |workspace, cx| {
14104                let pane = if split {
14105                    workspace.adjacent_pane(window, cx)
14106                } else {
14107                    workspace.active_pane().clone()
14108                };
14109
14110                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14111                    let editor = buffer
14112                        .read(cx)
14113                        .file()
14114                        .is_none()
14115                        .then(|| {
14116                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14117                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14118                            // Instead, we try to activate the existing editor in the pane first.
14119                            let (editor, pane_item_index) =
14120                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14121                                    let editor = item.downcast::<Editor>()?;
14122                                    let singleton_buffer =
14123                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14124                                    if singleton_buffer == buffer {
14125                                        Some((editor, i))
14126                                    } else {
14127                                        None
14128                                    }
14129                                })?;
14130                            pane.update(cx, |pane, cx| {
14131                                pane.activate_item(pane_item_index, true, true, window, cx)
14132                            });
14133                            Some(editor)
14134                        })
14135                        .flatten()
14136                        .unwrap_or_else(|| {
14137                            workspace.open_project_item::<Self>(
14138                                pane.clone(),
14139                                buffer,
14140                                true,
14141                                true,
14142                                window,
14143                                cx,
14144                            )
14145                        });
14146
14147                    editor.update(cx, |editor, cx| {
14148                        let autoscroll = match scroll_offset {
14149                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14150                            None => Autoscroll::newest(),
14151                        };
14152                        let nav_history = editor.nav_history.take();
14153                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14154                            s.select_ranges(ranges);
14155                        });
14156                        editor.nav_history = nav_history;
14157                    });
14158                }
14159            })
14160        });
14161    }
14162
14163    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14164        let snapshot = self.buffer.read(cx).read(cx);
14165        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14166        Some(
14167            ranges
14168                .iter()
14169                .map(move |range| {
14170                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14171                })
14172                .collect(),
14173        )
14174    }
14175
14176    fn selection_replacement_ranges(
14177        &self,
14178        range: Range<OffsetUtf16>,
14179        cx: &mut App,
14180    ) -> Vec<Range<OffsetUtf16>> {
14181        let selections = self.selections.all::<OffsetUtf16>(cx);
14182        let newest_selection = selections
14183            .iter()
14184            .max_by_key(|selection| selection.id)
14185            .unwrap();
14186        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14187        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14188        let snapshot = self.buffer.read(cx).read(cx);
14189        selections
14190            .into_iter()
14191            .map(|mut selection| {
14192                selection.start.0 =
14193                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14194                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14195                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14196                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14197            })
14198            .collect()
14199    }
14200
14201    fn report_editor_event(
14202        &self,
14203        event_type: &'static str,
14204        file_extension: Option<String>,
14205        cx: &App,
14206    ) {
14207        if cfg!(any(test, feature = "test-support")) {
14208            return;
14209        }
14210
14211        let Some(project) = &self.project else { return };
14212
14213        // If None, we are in a file without an extension
14214        let file = self
14215            .buffer
14216            .read(cx)
14217            .as_singleton()
14218            .and_then(|b| b.read(cx).file());
14219        let file_extension = file_extension.or(file
14220            .as_ref()
14221            .and_then(|file| Path::new(file.file_name(cx)).extension())
14222            .and_then(|e| e.to_str())
14223            .map(|a| a.to_string()));
14224
14225        let vim_mode = cx
14226            .global::<SettingsStore>()
14227            .raw_user_settings()
14228            .get("vim_mode")
14229            == Some(&serde_json::Value::Bool(true));
14230
14231        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14232        let copilot_enabled = edit_predictions_provider
14233            == language::language_settings::EditPredictionProvider::Copilot;
14234        let copilot_enabled_for_language = self
14235            .buffer
14236            .read(cx)
14237            .settings_at(0, cx)
14238            .show_edit_predictions;
14239
14240        let project = project.read(cx);
14241        telemetry::event!(
14242            event_type,
14243            file_extension,
14244            vim_mode,
14245            copilot_enabled,
14246            copilot_enabled_for_language,
14247            edit_predictions_provider,
14248            is_via_ssh = project.is_via_ssh(),
14249        );
14250    }
14251
14252    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14253    /// with each line being an array of {text, highlight} objects.
14254    fn copy_highlight_json(
14255        &mut self,
14256        _: &CopyHighlightJson,
14257        window: &mut Window,
14258        cx: &mut Context<Self>,
14259    ) {
14260        #[derive(Serialize)]
14261        struct Chunk<'a> {
14262            text: String,
14263            highlight: Option<&'a str>,
14264        }
14265
14266        let snapshot = self.buffer.read(cx).snapshot(cx);
14267        let range = self
14268            .selected_text_range(false, window, cx)
14269            .and_then(|selection| {
14270                if selection.range.is_empty() {
14271                    None
14272                } else {
14273                    Some(selection.range)
14274                }
14275            })
14276            .unwrap_or_else(|| 0..snapshot.len());
14277
14278        let chunks = snapshot.chunks(range, true);
14279        let mut lines = Vec::new();
14280        let mut line: VecDeque<Chunk> = VecDeque::new();
14281
14282        let Some(style) = self.style.as_ref() else {
14283            return;
14284        };
14285
14286        for chunk in chunks {
14287            let highlight = chunk
14288                .syntax_highlight_id
14289                .and_then(|id| id.name(&style.syntax));
14290            let mut chunk_lines = chunk.text.split('\n').peekable();
14291            while let Some(text) = chunk_lines.next() {
14292                let mut merged_with_last_token = false;
14293                if let Some(last_token) = line.back_mut() {
14294                    if last_token.highlight == highlight {
14295                        last_token.text.push_str(text);
14296                        merged_with_last_token = true;
14297                    }
14298                }
14299
14300                if !merged_with_last_token {
14301                    line.push_back(Chunk {
14302                        text: text.into(),
14303                        highlight,
14304                    });
14305                }
14306
14307                if chunk_lines.peek().is_some() {
14308                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14309                        line.pop_front();
14310                    }
14311                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14312                        line.pop_back();
14313                    }
14314
14315                    lines.push(mem::take(&mut line));
14316                }
14317            }
14318        }
14319
14320        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14321            return;
14322        };
14323        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14324    }
14325
14326    pub fn open_context_menu(
14327        &mut self,
14328        _: &OpenContextMenu,
14329        window: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        self.request_autoscroll(Autoscroll::newest(), cx);
14333        let position = self.selections.newest_display(cx).start;
14334        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14335    }
14336
14337    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14338        &self.inlay_hint_cache
14339    }
14340
14341    pub fn replay_insert_event(
14342        &mut self,
14343        text: &str,
14344        relative_utf16_range: Option<Range<isize>>,
14345        window: &mut Window,
14346        cx: &mut Context<Self>,
14347    ) {
14348        if !self.input_enabled {
14349            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14350            return;
14351        }
14352        if let Some(relative_utf16_range) = relative_utf16_range {
14353            let selections = self.selections.all::<OffsetUtf16>(cx);
14354            self.change_selections(None, window, cx, |s| {
14355                let new_ranges = selections.into_iter().map(|range| {
14356                    let start = OffsetUtf16(
14357                        range
14358                            .head()
14359                            .0
14360                            .saturating_add_signed(relative_utf16_range.start),
14361                    );
14362                    let end = OffsetUtf16(
14363                        range
14364                            .head()
14365                            .0
14366                            .saturating_add_signed(relative_utf16_range.end),
14367                    );
14368                    start..end
14369                });
14370                s.select_ranges(new_ranges);
14371            });
14372        }
14373
14374        self.handle_input(text, window, cx);
14375    }
14376
14377    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14378        let Some(provider) = self.semantics_provider.as_ref() else {
14379            return false;
14380        };
14381
14382        let mut supports = false;
14383        self.buffer().read(cx).for_each_buffer(|buffer| {
14384            supports |= provider.supports_inlay_hints(buffer, cx);
14385        });
14386        supports
14387    }
14388    pub fn is_focused(&self, window: &mut Window) -> bool {
14389        self.focus_handle.is_focused(window)
14390    }
14391
14392    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14393        cx.emit(EditorEvent::Focused);
14394
14395        if let Some(descendant) = self
14396            .last_focused_descendant
14397            .take()
14398            .and_then(|descendant| descendant.upgrade())
14399        {
14400            window.focus(&descendant);
14401        } else {
14402            if let Some(blame) = self.blame.as_ref() {
14403                blame.update(cx, GitBlame::focus)
14404            }
14405
14406            self.blink_manager.update(cx, BlinkManager::enable);
14407            self.show_cursor_names(window, cx);
14408            self.buffer.update(cx, |buffer, cx| {
14409                buffer.finalize_last_transaction(cx);
14410                if self.leader_peer_id.is_none() {
14411                    buffer.set_active_selections(
14412                        &self.selections.disjoint_anchors(),
14413                        self.selections.line_mode,
14414                        self.cursor_shape,
14415                        cx,
14416                    );
14417                }
14418            });
14419        }
14420    }
14421
14422    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14423        cx.emit(EditorEvent::FocusedIn)
14424    }
14425
14426    fn handle_focus_out(
14427        &mut self,
14428        event: FocusOutEvent,
14429        _window: &mut Window,
14430        _cx: &mut Context<Self>,
14431    ) {
14432        if event.blurred != self.focus_handle {
14433            self.last_focused_descendant = Some(event.blurred);
14434        }
14435    }
14436
14437    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14438        self.blink_manager.update(cx, BlinkManager::disable);
14439        self.buffer
14440            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14441
14442        if let Some(blame) = self.blame.as_ref() {
14443            blame.update(cx, GitBlame::blur)
14444        }
14445        if !self.hover_state.focused(window, cx) {
14446            hide_hover(self, cx);
14447        }
14448
14449        self.hide_context_menu(window, cx);
14450        cx.emit(EditorEvent::Blurred);
14451        cx.notify();
14452    }
14453
14454    pub fn register_action<A: Action>(
14455        &mut self,
14456        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14457    ) -> Subscription {
14458        let id = self.next_editor_action_id.post_inc();
14459        let listener = Arc::new(listener);
14460        self.editor_actions.borrow_mut().insert(
14461            id,
14462            Box::new(move |window, _| {
14463                let listener = listener.clone();
14464                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14465                    let action = action.downcast_ref().unwrap();
14466                    if phase == DispatchPhase::Bubble {
14467                        listener(action, window, cx)
14468                    }
14469                })
14470            }),
14471        );
14472
14473        let editor_actions = self.editor_actions.clone();
14474        Subscription::new(move || {
14475            editor_actions.borrow_mut().remove(&id);
14476        })
14477    }
14478
14479    pub fn file_header_size(&self) -> u32 {
14480        FILE_HEADER_HEIGHT
14481    }
14482
14483    pub fn revert(
14484        &mut self,
14485        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14486        window: &mut Window,
14487        cx: &mut Context<Self>,
14488    ) {
14489        self.buffer().update(cx, |multi_buffer, cx| {
14490            for (buffer_id, changes) in revert_changes {
14491                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14492                    buffer.update(cx, |buffer, cx| {
14493                        buffer.edit(
14494                            changes.into_iter().map(|(range, text)| {
14495                                (range, text.to_string().map(Arc::<str>::from))
14496                            }),
14497                            None,
14498                            cx,
14499                        );
14500                    });
14501                }
14502            }
14503        });
14504        self.change_selections(None, window, cx, |selections| selections.refresh());
14505    }
14506
14507    pub fn to_pixel_point(
14508        &self,
14509        source: multi_buffer::Anchor,
14510        editor_snapshot: &EditorSnapshot,
14511        window: &mut Window,
14512    ) -> Option<gpui::Point<Pixels>> {
14513        let source_point = source.to_display_point(editor_snapshot);
14514        self.display_to_pixel_point(source_point, editor_snapshot, window)
14515    }
14516
14517    pub fn display_to_pixel_point(
14518        &self,
14519        source: DisplayPoint,
14520        editor_snapshot: &EditorSnapshot,
14521        window: &mut Window,
14522    ) -> Option<gpui::Point<Pixels>> {
14523        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14524        let text_layout_details = self.text_layout_details(window);
14525        let scroll_top = text_layout_details
14526            .scroll_anchor
14527            .scroll_position(editor_snapshot)
14528            .y;
14529
14530        if source.row().as_f32() < scroll_top.floor() {
14531            return None;
14532        }
14533        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14534        let source_y = line_height * (source.row().as_f32() - scroll_top);
14535        Some(gpui::Point::new(source_x, source_y))
14536    }
14537
14538    pub fn has_visible_completions_menu(&self) -> bool {
14539        !self.previewing_inline_completion
14540            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14541                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14542            })
14543    }
14544
14545    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14546        self.addons
14547            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14548    }
14549
14550    pub fn unregister_addon<T: Addon>(&mut self) {
14551        self.addons.remove(&std::any::TypeId::of::<T>());
14552    }
14553
14554    pub fn addon<T: Addon>(&self) -> Option<&T> {
14555        let type_id = std::any::TypeId::of::<T>();
14556        self.addons
14557            .get(&type_id)
14558            .and_then(|item| item.to_any().downcast_ref::<T>())
14559    }
14560
14561    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14562        let text_layout_details = self.text_layout_details(window);
14563        let style = &text_layout_details.editor_style;
14564        let font_id = window.text_system().resolve_font(&style.text.font());
14565        let font_size = style.text.font_size.to_pixels(window.rem_size());
14566        let line_height = style.text.line_height_in_pixels(window.rem_size());
14567        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14568
14569        gpui::Size::new(em_width, line_height)
14570    }
14571}
14572
14573fn get_uncommitted_diff_for_buffer(
14574    project: &Entity<Project>,
14575    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14576    buffer: Entity<MultiBuffer>,
14577    cx: &mut App,
14578) {
14579    let mut tasks = Vec::new();
14580    project.update(cx, |project, cx| {
14581        for buffer in buffers {
14582            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14583        }
14584    });
14585    cx.spawn(|mut cx| async move {
14586        let diffs = futures::future::join_all(tasks).await;
14587        buffer
14588            .update(&mut cx, |buffer, cx| {
14589                for diff in diffs.into_iter().flatten() {
14590                    buffer.add_diff(diff, cx);
14591                }
14592            })
14593            .ok();
14594    })
14595    .detach();
14596}
14597
14598fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14599    let tab_size = tab_size.get() as usize;
14600    let mut width = offset;
14601
14602    for ch in text.chars() {
14603        width += if ch == '\t' {
14604            tab_size - (width % tab_size)
14605        } else {
14606            1
14607        };
14608    }
14609
14610    width - offset
14611}
14612
14613#[cfg(test)]
14614mod tests {
14615    use super::*;
14616
14617    #[test]
14618    fn test_string_size_with_expanded_tabs() {
14619        let nz = |val| NonZeroU32::new(val).unwrap();
14620        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14621        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14622        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14623        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14624        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14625        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14626        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14627        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14628    }
14629}
14630
14631/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14632struct WordBreakingTokenizer<'a> {
14633    input: &'a str,
14634}
14635
14636impl<'a> WordBreakingTokenizer<'a> {
14637    fn new(input: &'a str) -> Self {
14638        Self { input }
14639    }
14640}
14641
14642fn is_char_ideographic(ch: char) -> bool {
14643    use unicode_script::Script::*;
14644    use unicode_script::UnicodeScript;
14645    matches!(ch.script(), Han | Tangut | Yi)
14646}
14647
14648fn is_grapheme_ideographic(text: &str) -> bool {
14649    text.chars().any(is_char_ideographic)
14650}
14651
14652fn is_grapheme_whitespace(text: &str) -> bool {
14653    text.chars().any(|x| x.is_whitespace())
14654}
14655
14656fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14657    text.chars().next().map_or(false, |ch| {
14658        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14659    })
14660}
14661
14662#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14663struct WordBreakToken<'a> {
14664    token: &'a str,
14665    grapheme_len: usize,
14666    is_whitespace: bool,
14667}
14668
14669impl<'a> Iterator for WordBreakingTokenizer<'a> {
14670    /// Yields a span, the count of graphemes in the token, and whether it was
14671    /// whitespace. Note that it also breaks at word boundaries.
14672    type Item = WordBreakToken<'a>;
14673
14674    fn next(&mut self) -> Option<Self::Item> {
14675        use unicode_segmentation::UnicodeSegmentation;
14676        if self.input.is_empty() {
14677            return None;
14678        }
14679
14680        let mut iter = self.input.graphemes(true).peekable();
14681        let mut offset = 0;
14682        let mut graphemes = 0;
14683        if let Some(first_grapheme) = iter.next() {
14684            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14685            offset += first_grapheme.len();
14686            graphemes += 1;
14687            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14688                if let Some(grapheme) = iter.peek().copied() {
14689                    if should_stay_with_preceding_ideograph(grapheme) {
14690                        offset += grapheme.len();
14691                        graphemes += 1;
14692                    }
14693                }
14694            } else {
14695                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14696                let mut next_word_bound = words.peek().copied();
14697                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14698                    next_word_bound = words.next();
14699                }
14700                while let Some(grapheme) = iter.peek().copied() {
14701                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14702                        break;
14703                    };
14704                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14705                        break;
14706                    };
14707                    offset += grapheme.len();
14708                    graphemes += 1;
14709                    iter.next();
14710                }
14711            }
14712            let token = &self.input[..offset];
14713            self.input = &self.input[offset..];
14714            if is_whitespace {
14715                Some(WordBreakToken {
14716                    token: " ",
14717                    grapheme_len: 1,
14718                    is_whitespace: true,
14719                })
14720            } else {
14721                Some(WordBreakToken {
14722                    token,
14723                    grapheme_len: graphemes,
14724                    is_whitespace: false,
14725                })
14726            }
14727        } else {
14728            None
14729        }
14730    }
14731}
14732
14733#[test]
14734fn test_word_breaking_tokenizer() {
14735    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14736        ("", &[]),
14737        ("  ", &[(" ", 1, true)]),
14738        ("Ʒ", &[("Ʒ", 1, false)]),
14739        ("Ǽ", &[("Ǽ", 1, false)]),
14740        ("", &[("", 1, false)]),
14741        ("⋑⋑", &[("⋑⋑", 2, false)]),
14742        (
14743            "原理,进而",
14744            &[
14745                ("", 1, false),
14746                ("理,", 2, false),
14747                ("", 1, false),
14748                ("", 1, false),
14749            ],
14750        ),
14751        (
14752            "hello world",
14753            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14754        ),
14755        (
14756            "hello, world",
14757            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14758        ),
14759        (
14760            "  hello world",
14761            &[
14762                (" ", 1, true),
14763                ("hello", 5, false),
14764                (" ", 1, true),
14765                ("world", 5, false),
14766            ],
14767        ),
14768        (
14769            "这是什么 \n 钢笔",
14770            &[
14771                ("", 1, false),
14772                ("", 1, false),
14773                ("", 1, false),
14774                ("", 1, false),
14775                (" ", 1, true),
14776                ("", 1, false),
14777                ("", 1, false),
14778            ],
14779        ),
14780        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14781    ];
14782
14783    for (input, result) in tests {
14784        assert_eq!(
14785            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14786            result
14787                .iter()
14788                .copied()
14789                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14790                    token,
14791                    grapheme_len,
14792                    is_whitespace,
14793                })
14794                .collect::<Vec<_>>()
14795        );
14796    }
14797}
14798
14799fn wrap_with_prefix(
14800    line_prefix: String,
14801    unwrapped_text: String,
14802    wrap_column: usize,
14803    tab_size: NonZeroU32,
14804) -> String {
14805    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14806    let mut wrapped_text = String::new();
14807    let mut current_line = line_prefix.clone();
14808
14809    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14810    let mut current_line_len = line_prefix_len;
14811    for WordBreakToken {
14812        token,
14813        grapheme_len,
14814        is_whitespace,
14815    } in tokenizer
14816    {
14817        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14818            wrapped_text.push_str(current_line.trim_end());
14819            wrapped_text.push('\n');
14820            current_line.truncate(line_prefix.len());
14821            current_line_len = line_prefix_len;
14822            if !is_whitespace {
14823                current_line.push_str(token);
14824                current_line_len += grapheme_len;
14825            }
14826        } else if !is_whitespace {
14827            current_line.push_str(token);
14828            current_line_len += grapheme_len;
14829        } else if current_line_len != line_prefix_len {
14830            current_line.push(' ');
14831            current_line_len += 1;
14832        }
14833    }
14834
14835    if !current_line.is_empty() {
14836        wrapped_text.push_str(&current_line);
14837    }
14838    wrapped_text
14839}
14840
14841#[test]
14842fn test_wrap_with_prefix() {
14843    assert_eq!(
14844        wrap_with_prefix(
14845            "# ".to_string(),
14846            "abcdefg".to_string(),
14847            4,
14848            NonZeroU32::new(4).unwrap()
14849        ),
14850        "# abcdefg"
14851    );
14852    assert_eq!(
14853        wrap_with_prefix(
14854            "".to_string(),
14855            "\thello world".to_string(),
14856            8,
14857            NonZeroU32::new(4).unwrap()
14858        ),
14859        "hello\nworld"
14860    );
14861    assert_eq!(
14862        wrap_with_prefix(
14863            "// ".to_string(),
14864            "xx \nyy zz aa bb cc".to_string(),
14865            12,
14866            NonZeroU32::new(4).unwrap()
14867        ),
14868        "// xx yy zz\n// aa bb cc"
14869    );
14870    assert_eq!(
14871        wrap_with_prefix(
14872            String::new(),
14873            "这是什么 \n 钢笔".to_string(),
14874            3,
14875            NonZeroU32::new(4).unwrap()
14876        ),
14877        "这是什\n么 钢\n"
14878    );
14879}
14880
14881pub trait CollaborationHub {
14882    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14883    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14884    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14885}
14886
14887impl CollaborationHub for Entity<Project> {
14888    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14889        self.read(cx).collaborators()
14890    }
14891
14892    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14893        self.read(cx).user_store().read(cx).participant_indices()
14894    }
14895
14896    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14897        let this = self.read(cx);
14898        let user_ids = this.collaborators().values().map(|c| c.user_id);
14899        this.user_store().read_with(cx, |user_store, cx| {
14900            user_store.participant_names(user_ids, cx)
14901        })
14902    }
14903}
14904
14905pub trait SemanticsProvider {
14906    fn hover(
14907        &self,
14908        buffer: &Entity<Buffer>,
14909        position: text::Anchor,
14910        cx: &mut App,
14911    ) -> Option<Task<Vec<project::Hover>>>;
14912
14913    fn inlay_hints(
14914        &self,
14915        buffer_handle: Entity<Buffer>,
14916        range: Range<text::Anchor>,
14917        cx: &mut App,
14918    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14919
14920    fn resolve_inlay_hint(
14921        &self,
14922        hint: InlayHint,
14923        buffer_handle: Entity<Buffer>,
14924        server_id: LanguageServerId,
14925        cx: &mut App,
14926    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14927
14928    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14929
14930    fn document_highlights(
14931        &self,
14932        buffer: &Entity<Buffer>,
14933        position: text::Anchor,
14934        cx: &mut App,
14935    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14936
14937    fn definitions(
14938        &self,
14939        buffer: &Entity<Buffer>,
14940        position: text::Anchor,
14941        kind: GotoDefinitionKind,
14942        cx: &mut App,
14943    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14944
14945    fn range_for_rename(
14946        &self,
14947        buffer: &Entity<Buffer>,
14948        position: text::Anchor,
14949        cx: &mut App,
14950    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14951
14952    fn perform_rename(
14953        &self,
14954        buffer: &Entity<Buffer>,
14955        position: text::Anchor,
14956        new_name: String,
14957        cx: &mut App,
14958    ) -> Option<Task<Result<ProjectTransaction>>>;
14959}
14960
14961pub trait CompletionProvider {
14962    fn completions(
14963        &self,
14964        buffer: &Entity<Buffer>,
14965        buffer_position: text::Anchor,
14966        trigger: CompletionContext,
14967        window: &mut Window,
14968        cx: &mut Context<Editor>,
14969    ) -> Task<Result<Vec<Completion>>>;
14970
14971    fn resolve_completions(
14972        &self,
14973        buffer: Entity<Buffer>,
14974        completion_indices: Vec<usize>,
14975        completions: Rc<RefCell<Box<[Completion]>>>,
14976        cx: &mut Context<Editor>,
14977    ) -> Task<Result<bool>>;
14978
14979    fn apply_additional_edits_for_completion(
14980        &self,
14981        _buffer: Entity<Buffer>,
14982        _completions: Rc<RefCell<Box<[Completion]>>>,
14983        _completion_index: usize,
14984        _push_to_history: bool,
14985        _cx: &mut Context<Editor>,
14986    ) -> Task<Result<Option<language::Transaction>>> {
14987        Task::ready(Ok(None))
14988    }
14989
14990    fn is_completion_trigger(
14991        &self,
14992        buffer: &Entity<Buffer>,
14993        position: language::Anchor,
14994        text: &str,
14995        trigger_in_words: bool,
14996        cx: &mut Context<Editor>,
14997    ) -> bool;
14998
14999    fn sort_completions(&self) -> bool {
15000        true
15001    }
15002}
15003
15004pub trait CodeActionProvider {
15005    fn id(&self) -> Arc<str>;
15006
15007    fn code_actions(
15008        &self,
15009        buffer: &Entity<Buffer>,
15010        range: Range<text::Anchor>,
15011        window: &mut Window,
15012        cx: &mut App,
15013    ) -> Task<Result<Vec<CodeAction>>>;
15014
15015    fn apply_code_action(
15016        &self,
15017        buffer_handle: Entity<Buffer>,
15018        action: CodeAction,
15019        excerpt_id: ExcerptId,
15020        push_to_history: bool,
15021        window: &mut Window,
15022        cx: &mut App,
15023    ) -> Task<Result<ProjectTransaction>>;
15024}
15025
15026impl CodeActionProvider for Entity<Project> {
15027    fn id(&self) -> Arc<str> {
15028        "project".into()
15029    }
15030
15031    fn code_actions(
15032        &self,
15033        buffer: &Entity<Buffer>,
15034        range: Range<text::Anchor>,
15035        _window: &mut Window,
15036        cx: &mut App,
15037    ) -> Task<Result<Vec<CodeAction>>> {
15038        self.update(cx, |project, cx| {
15039            project.code_actions(buffer, range, None, cx)
15040        })
15041    }
15042
15043    fn apply_code_action(
15044        &self,
15045        buffer_handle: Entity<Buffer>,
15046        action: CodeAction,
15047        _excerpt_id: ExcerptId,
15048        push_to_history: bool,
15049        _window: &mut Window,
15050        cx: &mut App,
15051    ) -> Task<Result<ProjectTransaction>> {
15052        self.update(cx, |project, cx| {
15053            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15054        })
15055    }
15056}
15057
15058fn snippet_completions(
15059    project: &Project,
15060    buffer: &Entity<Buffer>,
15061    buffer_position: text::Anchor,
15062    cx: &mut App,
15063) -> Task<Result<Vec<Completion>>> {
15064    let language = buffer.read(cx).language_at(buffer_position);
15065    let language_name = language.as_ref().map(|language| language.lsp_id());
15066    let snippet_store = project.snippets().read(cx);
15067    let snippets = snippet_store.snippets_for(language_name, cx);
15068
15069    if snippets.is_empty() {
15070        return Task::ready(Ok(vec![]));
15071    }
15072    let snapshot = buffer.read(cx).text_snapshot();
15073    let chars: String = snapshot
15074        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15075        .collect();
15076
15077    let scope = language.map(|language| language.default_scope());
15078    let executor = cx.background_executor().clone();
15079
15080    cx.background_executor().spawn(async move {
15081        let classifier = CharClassifier::new(scope).for_completion(true);
15082        let mut last_word = chars
15083            .chars()
15084            .take_while(|c| classifier.is_word(*c))
15085            .collect::<String>();
15086        last_word = last_word.chars().rev().collect();
15087
15088        if last_word.is_empty() {
15089            return Ok(vec![]);
15090        }
15091
15092        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15093        let to_lsp = |point: &text::Anchor| {
15094            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15095            point_to_lsp(end)
15096        };
15097        let lsp_end = to_lsp(&buffer_position);
15098
15099        let candidates = snippets
15100            .iter()
15101            .enumerate()
15102            .flat_map(|(ix, snippet)| {
15103                snippet
15104                    .prefix
15105                    .iter()
15106                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15107            })
15108            .collect::<Vec<StringMatchCandidate>>();
15109
15110        let mut matches = fuzzy::match_strings(
15111            &candidates,
15112            &last_word,
15113            last_word.chars().any(|c| c.is_uppercase()),
15114            100,
15115            &Default::default(),
15116            executor,
15117        )
15118        .await;
15119
15120        // Remove all candidates where the query's start does not match the start of any word in the candidate
15121        if let Some(query_start) = last_word.chars().next() {
15122            matches.retain(|string_match| {
15123                split_words(&string_match.string).any(|word| {
15124                    // Check that the first codepoint of the word as lowercase matches the first
15125                    // codepoint of the query as lowercase
15126                    word.chars()
15127                        .flat_map(|codepoint| codepoint.to_lowercase())
15128                        .zip(query_start.to_lowercase())
15129                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15130                })
15131            });
15132        }
15133
15134        let matched_strings = matches
15135            .into_iter()
15136            .map(|m| m.string)
15137            .collect::<HashSet<_>>();
15138
15139        let result: Vec<Completion> = snippets
15140            .into_iter()
15141            .filter_map(|snippet| {
15142                let matching_prefix = snippet
15143                    .prefix
15144                    .iter()
15145                    .find(|prefix| matched_strings.contains(*prefix))?;
15146                let start = as_offset - last_word.len();
15147                let start = snapshot.anchor_before(start);
15148                let range = start..buffer_position;
15149                let lsp_start = to_lsp(&start);
15150                let lsp_range = lsp::Range {
15151                    start: lsp_start,
15152                    end: lsp_end,
15153                };
15154                Some(Completion {
15155                    old_range: range,
15156                    new_text: snippet.body.clone(),
15157                    resolved: false,
15158                    label: CodeLabel {
15159                        text: matching_prefix.clone(),
15160                        runs: vec![],
15161                        filter_range: 0..matching_prefix.len(),
15162                    },
15163                    server_id: LanguageServerId(usize::MAX),
15164                    documentation: snippet
15165                        .description
15166                        .clone()
15167                        .map(CompletionDocumentation::SingleLine),
15168                    lsp_completion: lsp::CompletionItem {
15169                        label: snippet.prefix.first().unwrap().clone(),
15170                        kind: Some(CompletionItemKind::SNIPPET),
15171                        label_details: snippet.description.as_ref().map(|description| {
15172                            lsp::CompletionItemLabelDetails {
15173                                detail: Some(description.clone()),
15174                                description: None,
15175                            }
15176                        }),
15177                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15178                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15179                            lsp::InsertReplaceEdit {
15180                                new_text: snippet.body.clone(),
15181                                insert: lsp_range,
15182                                replace: lsp_range,
15183                            },
15184                        )),
15185                        filter_text: Some(snippet.body.clone()),
15186                        sort_text: Some(char::MAX.to_string()),
15187                        ..Default::default()
15188                    },
15189                    confirm: None,
15190                })
15191            })
15192            .collect();
15193
15194        Ok(result)
15195    })
15196}
15197
15198impl CompletionProvider for Entity<Project> {
15199    fn completions(
15200        &self,
15201        buffer: &Entity<Buffer>,
15202        buffer_position: text::Anchor,
15203        options: CompletionContext,
15204        _window: &mut Window,
15205        cx: &mut Context<Editor>,
15206    ) -> Task<Result<Vec<Completion>>> {
15207        self.update(cx, |project, cx| {
15208            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15209            let project_completions = project.completions(buffer, buffer_position, options, cx);
15210            cx.background_executor().spawn(async move {
15211                let mut completions = project_completions.await?;
15212                let snippets_completions = snippets.await?;
15213                completions.extend(snippets_completions);
15214                Ok(completions)
15215            })
15216        })
15217    }
15218
15219    fn resolve_completions(
15220        &self,
15221        buffer: Entity<Buffer>,
15222        completion_indices: Vec<usize>,
15223        completions: Rc<RefCell<Box<[Completion]>>>,
15224        cx: &mut Context<Editor>,
15225    ) -> Task<Result<bool>> {
15226        self.update(cx, |project, cx| {
15227            project.lsp_store().update(cx, |lsp_store, cx| {
15228                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15229            })
15230        })
15231    }
15232
15233    fn apply_additional_edits_for_completion(
15234        &self,
15235        buffer: Entity<Buffer>,
15236        completions: Rc<RefCell<Box<[Completion]>>>,
15237        completion_index: usize,
15238        push_to_history: bool,
15239        cx: &mut Context<Editor>,
15240    ) -> Task<Result<Option<language::Transaction>>> {
15241        self.update(cx, |project, cx| {
15242            project.lsp_store().update(cx, |lsp_store, cx| {
15243                lsp_store.apply_additional_edits_for_completion(
15244                    buffer,
15245                    completions,
15246                    completion_index,
15247                    push_to_history,
15248                    cx,
15249                )
15250            })
15251        })
15252    }
15253
15254    fn is_completion_trigger(
15255        &self,
15256        buffer: &Entity<Buffer>,
15257        position: language::Anchor,
15258        text: &str,
15259        trigger_in_words: bool,
15260        cx: &mut Context<Editor>,
15261    ) -> bool {
15262        let mut chars = text.chars();
15263        let char = if let Some(char) = chars.next() {
15264            char
15265        } else {
15266            return false;
15267        };
15268        if chars.next().is_some() {
15269            return false;
15270        }
15271
15272        let buffer = buffer.read(cx);
15273        let snapshot = buffer.snapshot();
15274        if !snapshot.settings_at(position, cx).show_completions_on_input {
15275            return false;
15276        }
15277        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15278        if trigger_in_words && classifier.is_word(char) {
15279            return true;
15280        }
15281
15282        buffer.completion_triggers().contains(text)
15283    }
15284}
15285
15286impl SemanticsProvider for Entity<Project> {
15287    fn hover(
15288        &self,
15289        buffer: &Entity<Buffer>,
15290        position: text::Anchor,
15291        cx: &mut App,
15292    ) -> Option<Task<Vec<project::Hover>>> {
15293        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15294    }
15295
15296    fn document_highlights(
15297        &self,
15298        buffer: &Entity<Buffer>,
15299        position: text::Anchor,
15300        cx: &mut App,
15301    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15302        Some(self.update(cx, |project, cx| {
15303            project.document_highlights(buffer, position, cx)
15304        }))
15305    }
15306
15307    fn definitions(
15308        &self,
15309        buffer: &Entity<Buffer>,
15310        position: text::Anchor,
15311        kind: GotoDefinitionKind,
15312        cx: &mut App,
15313    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15314        Some(self.update(cx, |project, cx| match kind {
15315            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15316            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15317            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15318            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15319        }))
15320    }
15321
15322    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15323        // TODO: make this work for remote projects
15324        self.read(cx)
15325            .language_servers_for_local_buffer(buffer.read(cx), cx)
15326            .any(
15327                |(_, server)| match server.capabilities().inlay_hint_provider {
15328                    Some(lsp::OneOf::Left(enabled)) => enabled,
15329                    Some(lsp::OneOf::Right(_)) => true,
15330                    None => false,
15331                },
15332            )
15333    }
15334
15335    fn inlay_hints(
15336        &self,
15337        buffer_handle: Entity<Buffer>,
15338        range: Range<text::Anchor>,
15339        cx: &mut App,
15340    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15341        Some(self.update(cx, |project, cx| {
15342            project.inlay_hints(buffer_handle, range, cx)
15343        }))
15344    }
15345
15346    fn resolve_inlay_hint(
15347        &self,
15348        hint: InlayHint,
15349        buffer_handle: Entity<Buffer>,
15350        server_id: LanguageServerId,
15351        cx: &mut App,
15352    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15353        Some(self.update(cx, |project, cx| {
15354            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15355        }))
15356    }
15357
15358    fn range_for_rename(
15359        &self,
15360        buffer: &Entity<Buffer>,
15361        position: text::Anchor,
15362        cx: &mut App,
15363    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15364        Some(self.update(cx, |project, cx| {
15365            let buffer = buffer.clone();
15366            let task = project.prepare_rename(buffer.clone(), position, cx);
15367            cx.spawn(|_, mut cx| async move {
15368                Ok(match task.await? {
15369                    PrepareRenameResponse::Success(range) => Some(range),
15370                    PrepareRenameResponse::InvalidPosition => None,
15371                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15372                        // Fallback on using TreeSitter info to determine identifier range
15373                        buffer.update(&mut cx, |buffer, _| {
15374                            let snapshot = buffer.snapshot();
15375                            let (range, kind) = snapshot.surrounding_word(position);
15376                            if kind != Some(CharKind::Word) {
15377                                return None;
15378                            }
15379                            Some(
15380                                snapshot.anchor_before(range.start)
15381                                    ..snapshot.anchor_after(range.end),
15382                            )
15383                        })?
15384                    }
15385                })
15386            })
15387        }))
15388    }
15389
15390    fn perform_rename(
15391        &self,
15392        buffer: &Entity<Buffer>,
15393        position: text::Anchor,
15394        new_name: String,
15395        cx: &mut App,
15396    ) -> Option<Task<Result<ProjectTransaction>>> {
15397        Some(self.update(cx, |project, cx| {
15398            project.perform_rename(buffer.clone(), position, new_name, cx)
15399        }))
15400    }
15401}
15402
15403fn inlay_hint_settings(
15404    location: Anchor,
15405    snapshot: &MultiBufferSnapshot,
15406    cx: &mut Context<Editor>,
15407) -> InlayHintSettings {
15408    let file = snapshot.file_at(location);
15409    let language = snapshot.language_at(location).map(|l| l.name());
15410    language_settings(language, file, cx).inlay_hints
15411}
15412
15413fn consume_contiguous_rows(
15414    contiguous_row_selections: &mut Vec<Selection<Point>>,
15415    selection: &Selection<Point>,
15416    display_map: &DisplaySnapshot,
15417    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15418) -> (MultiBufferRow, MultiBufferRow) {
15419    contiguous_row_selections.push(selection.clone());
15420    let start_row = MultiBufferRow(selection.start.row);
15421    let mut end_row = ending_row(selection, display_map);
15422
15423    while let Some(next_selection) = selections.peek() {
15424        if next_selection.start.row <= end_row.0 {
15425            end_row = ending_row(next_selection, display_map);
15426            contiguous_row_selections.push(selections.next().unwrap().clone());
15427        } else {
15428            break;
15429        }
15430    }
15431    (start_row, end_row)
15432}
15433
15434fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15435    if next_selection.end.column > 0 || next_selection.is_empty() {
15436        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15437    } else {
15438        MultiBufferRow(next_selection.end.row)
15439    }
15440}
15441
15442impl EditorSnapshot {
15443    pub fn remote_selections_in_range<'a>(
15444        &'a self,
15445        range: &'a Range<Anchor>,
15446        collaboration_hub: &dyn CollaborationHub,
15447        cx: &'a App,
15448    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15449        let participant_names = collaboration_hub.user_names(cx);
15450        let participant_indices = collaboration_hub.user_participant_indices(cx);
15451        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15452        let collaborators_by_replica_id = collaborators_by_peer_id
15453            .iter()
15454            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15455            .collect::<HashMap<_, _>>();
15456        self.buffer_snapshot
15457            .selections_in_range(range, false)
15458            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15459                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15460                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15461                let user_name = participant_names.get(&collaborator.user_id).cloned();
15462                Some(RemoteSelection {
15463                    replica_id,
15464                    selection,
15465                    cursor_shape,
15466                    line_mode,
15467                    participant_index,
15468                    peer_id: collaborator.peer_id,
15469                    user_name,
15470                })
15471            })
15472    }
15473
15474    pub fn hunks_for_ranges(
15475        &self,
15476        ranges: impl Iterator<Item = Range<Point>>,
15477    ) -> Vec<MultiBufferDiffHunk> {
15478        let mut hunks = Vec::new();
15479        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15480            HashMap::default();
15481        for query_range in ranges {
15482            let query_rows =
15483                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15484            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15485                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15486            ) {
15487                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15488                // when the caret is just above or just below the deleted hunk.
15489                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15490                let related_to_selection = if allow_adjacent {
15491                    hunk.row_range.overlaps(&query_rows)
15492                        || hunk.row_range.start == query_rows.end
15493                        || hunk.row_range.end == query_rows.start
15494                } else {
15495                    hunk.row_range.overlaps(&query_rows)
15496                };
15497                if related_to_selection {
15498                    if !processed_buffer_rows
15499                        .entry(hunk.buffer_id)
15500                        .or_default()
15501                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15502                    {
15503                        continue;
15504                    }
15505                    hunks.push(hunk);
15506                }
15507            }
15508        }
15509
15510        hunks
15511    }
15512
15513    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15514        self.display_snapshot.buffer_snapshot.language_at(position)
15515    }
15516
15517    pub fn is_focused(&self) -> bool {
15518        self.is_focused
15519    }
15520
15521    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15522        self.placeholder_text.as_ref()
15523    }
15524
15525    pub fn scroll_position(&self) -> gpui::Point<f32> {
15526        self.scroll_anchor.scroll_position(&self.display_snapshot)
15527    }
15528
15529    fn gutter_dimensions(
15530        &self,
15531        font_id: FontId,
15532        font_size: Pixels,
15533        max_line_number_width: Pixels,
15534        cx: &App,
15535    ) -> Option<GutterDimensions> {
15536        if !self.show_gutter {
15537            return None;
15538        }
15539
15540        let descent = cx.text_system().descent(font_id, font_size);
15541        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15542        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15543
15544        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15545            matches!(
15546                ProjectSettings::get_global(cx).git.git_gutter,
15547                Some(GitGutterSetting::TrackedFiles)
15548            )
15549        });
15550        let gutter_settings = EditorSettings::get_global(cx).gutter;
15551        let show_line_numbers = self
15552            .show_line_numbers
15553            .unwrap_or(gutter_settings.line_numbers);
15554        let line_gutter_width = if show_line_numbers {
15555            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15556            let min_width_for_number_on_gutter = em_advance * 4.0;
15557            max_line_number_width.max(min_width_for_number_on_gutter)
15558        } else {
15559            0.0.into()
15560        };
15561
15562        let show_code_actions = self
15563            .show_code_actions
15564            .unwrap_or(gutter_settings.code_actions);
15565
15566        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15567
15568        let git_blame_entries_width =
15569            self.git_blame_gutter_max_author_length
15570                .map(|max_author_length| {
15571                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15572
15573                    /// The number of characters to dedicate to gaps and margins.
15574                    const SPACING_WIDTH: usize = 4;
15575
15576                    let max_char_count = max_author_length
15577                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15578                        + ::git::SHORT_SHA_LENGTH
15579                        + MAX_RELATIVE_TIMESTAMP.len()
15580                        + SPACING_WIDTH;
15581
15582                    em_advance * max_char_count
15583                });
15584
15585        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15586        left_padding += if show_code_actions || show_runnables {
15587            em_width * 3.0
15588        } else if show_git_gutter && show_line_numbers {
15589            em_width * 2.0
15590        } else if show_git_gutter || show_line_numbers {
15591            em_width
15592        } else {
15593            px(0.)
15594        };
15595
15596        let right_padding = if gutter_settings.folds && show_line_numbers {
15597            em_width * 4.0
15598        } else if gutter_settings.folds {
15599            em_width * 3.0
15600        } else if show_line_numbers {
15601            em_width
15602        } else {
15603            px(0.)
15604        };
15605
15606        Some(GutterDimensions {
15607            left_padding,
15608            right_padding,
15609            width: line_gutter_width + left_padding + right_padding,
15610            margin: -descent,
15611            git_blame_entries_width,
15612        })
15613    }
15614
15615    pub fn render_crease_toggle(
15616        &self,
15617        buffer_row: MultiBufferRow,
15618        row_contains_cursor: bool,
15619        editor: Entity<Editor>,
15620        window: &mut Window,
15621        cx: &mut App,
15622    ) -> Option<AnyElement> {
15623        let folded = self.is_line_folded(buffer_row);
15624        let mut is_foldable = false;
15625
15626        if let Some(crease) = self
15627            .crease_snapshot
15628            .query_row(buffer_row, &self.buffer_snapshot)
15629        {
15630            is_foldable = true;
15631            match crease {
15632                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15633                    if let Some(render_toggle) = render_toggle {
15634                        let toggle_callback =
15635                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15636                                if folded {
15637                                    editor.update(cx, |editor, cx| {
15638                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15639                                    });
15640                                } else {
15641                                    editor.update(cx, |editor, cx| {
15642                                        editor.unfold_at(
15643                                            &crate::UnfoldAt { buffer_row },
15644                                            window,
15645                                            cx,
15646                                        )
15647                                    });
15648                                }
15649                            });
15650                        return Some((render_toggle)(
15651                            buffer_row,
15652                            folded,
15653                            toggle_callback,
15654                            window,
15655                            cx,
15656                        ));
15657                    }
15658                }
15659            }
15660        }
15661
15662        is_foldable |= self.starts_indent(buffer_row);
15663
15664        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15665            Some(
15666                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15667                    .toggle_state(folded)
15668                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15669                        if folded {
15670                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15671                        } else {
15672                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15673                        }
15674                    }))
15675                    .into_any_element(),
15676            )
15677        } else {
15678            None
15679        }
15680    }
15681
15682    pub fn render_crease_trailer(
15683        &self,
15684        buffer_row: MultiBufferRow,
15685        window: &mut Window,
15686        cx: &mut App,
15687    ) -> Option<AnyElement> {
15688        let folded = self.is_line_folded(buffer_row);
15689        if let Crease::Inline { render_trailer, .. } = self
15690            .crease_snapshot
15691            .query_row(buffer_row, &self.buffer_snapshot)?
15692        {
15693            let render_trailer = render_trailer.as_ref()?;
15694            Some(render_trailer(buffer_row, folded, window, cx))
15695        } else {
15696            None
15697        }
15698    }
15699}
15700
15701impl Deref for EditorSnapshot {
15702    type Target = DisplaySnapshot;
15703
15704    fn deref(&self) -> &Self::Target {
15705        &self.display_snapshot
15706    }
15707}
15708
15709#[derive(Clone, Debug, PartialEq, Eq)]
15710pub enum EditorEvent {
15711    InputIgnored {
15712        text: Arc<str>,
15713    },
15714    InputHandled {
15715        utf16_range_to_replace: Option<Range<isize>>,
15716        text: Arc<str>,
15717    },
15718    ExcerptsAdded {
15719        buffer: Entity<Buffer>,
15720        predecessor: ExcerptId,
15721        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15722    },
15723    ExcerptsRemoved {
15724        ids: Vec<ExcerptId>,
15725    },
15726    BufferFoldToggled {
15727        ids: Vec<ExcerptId>,
15728        folded: bool,
15729    },
15730    ExcerptsEdited {
15731        ids: Vec<ExcerptId>,
15732    },
15733    ExcerptsExpanded {
15734        ids: Vec<ExcerptId>,
15735    },
15736    BufferEdited,
15737    Edited {
15738        transaction_id: clock::Lamport,
15739    },
15740    Reparsed(BufferId),
15741    Focused,
15742    FocusedIn,
15743    Blurred,
15744    DirtyChanged,
15745    Saved,
15746    TitleChanged,
15747    DiffBaseChanged,
15748    SelectionsChanged {
15749        local: bool,
15750    },
15751    ScrollPositionChanged {
15752        local: bool,
15753        autoscroll: bool,
15754    },
15755    Closed,
15756    TransactionUndone {
15757        transaction_id: clock::Lamport,
15758    },
15759    TransactionBegun {
15760        transaction_id: clock::Lamport,
15761    },
15762    Reloaded,
15763    CursorShapeChanged,
15764}
15765
15766impl EventEmitter<EditorEvent> for Editor {}
15767
15768impl Focusable for Editor {
15769    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15770        self.focus_handle.clone()
15771    }
15772}
15773
15774impl Render for Editor {
15775    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15776        let settings = ThemeSettings::get_global(cx);
15777
15778        let mut text_style = match self.mode {
15779            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15780                color: cx.theme().colors().editor_foreground,
15781                font_family: settings.ui_font.family.clone(),
15782                font_features: settings.ui_font.features.clone(),
15783                font_fallbacks: settings.ui_font.fallbacks.clone(),
15784                font_size: rems(0.875).into(),
15785                font_weight: settings.ui_font.weight,
15786                line_height: relative(settings.buffer_line_height.value()),
15787                ..Default::default()
15788            },
15789            EditorMode::Full => TextStyle {
15790                color: cx.theme().colors().editor_foreground,
15791                font_family: settings.buffer_font.family.clone(),
15792                font_features: settings.buffer_font.features.clone(),
15793                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15794                font_size: settings.buffer_font_size().into(),
15795                font_weight: settings.buffer_font.weight,
15796                line_height: relative(settings.buffer_line_height.value()),
15797                ..Default::default()
15798            },
15799        };
15800        if let Some(text_style_refinement) = &self.text_style_refinement {
15801            text_style.refine(text_style_refinement)
15802        }
15803
15804        let background = match self.mode {
15805            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15806            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15807            EditorMode::Full => cx.theme().colors().editor_background,
15808        };
15809
15810        EditorElement::new(
15811            &cx.entity(),
15812            EditorStyle {
15813                background,
15814                local_player: cx.theme().players().local(),
15815                text: text_style,
15816                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15817                syntax: cx.theme().syntax().clone(),
15818                status: cx.theme().status().clone(),
15819                inlay_hints_style: make_inlay_hints_style(cx),
15820                inline_completion_styles: make_suggestion_styles(cx),
15821                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15822            },
15823        )
15824    }
15825}
15826
15827impl EntityInputHandler for Editor {
15828    fn text_for_range(
15829        &mut self,
15830        range_utf16: Range<usize>,
15831        adjusted_range: &mut Option<Range<usize>>,
15832        _: &mut Window,
15833        cx: &mut Context<Self>,
15834    ) -> Option<String> {
15835        let snapshot = self.buffer.read(cx).read(cx);
15836        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15837        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15838        if (start.0..end.0) != range_utf16 {
15839            adjusted_range.replace(start.0..end.0);
15840        }
15841        Some(snapshot.text_for_range(start..end).collect())
15842    }
15843
15844    fn selected_text_range(
15845        &mut self,
15846        ignore_disabled_input: bool,
15847        _: &mut Window,
15848        cx: &mut Context<Self>,
15849    ) -> Option<UTF16Selection> {
15850        // Prevent the IME menu from appearing when holding down an alphabetic key
15851        // while input is disabled.
15852        if !ignore_disabled_input && !self.input_enabled {
15853            return None;
15854        }
15855
15856        let selection = self.selections.newest::<OffsetUtf16>(cx);
15857        let range = selection.range();
15858
15859        Some(UTF16Selection {
15860            range: range.start.0..range.end.0,
15861            reversed: selection.reversed,
15862        })
15863    }
15864
15865    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15866        let snapshot = self.buffer.read(cx).read(cx);
15867        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15868        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15869    }
15870
15871    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15872        self.clear_highlights::<InputComposition>(cx);
15873        self.ime_transaction.take();
15874    }
15875
15876    fn replace_text_in_range(
15877        &mut self,
15878        range_utf16: Option<Range<usize>>,
15879        text: &str,
15880        window: &mut Window,
15881        cx: &mut Context<Self>,
15882    ) {
15883        if !self.input_enabled {
15884            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15885            return;
15886        }
15887
15888        self.transact(window, cx, |this, window, cx| {
15889            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15890                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15891                Some(this.selection_replacement_ranges(range_utf16, cx))
15892            } else {
15893                this.marked_text_ranges(cx)
15894            };
15895
15896            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15897                let newest_selection_id = this.selections.newest_anchor().id;
15898                this.selections
15899                    .all::<OffsetUtf16>(cx)
15900                    .iter()
15901                    .zip(ranges_to_replace.iter())
15902                    .find_map(|(selection, range)| {
15903                        if selection.id == newest_selection_id {
15904                            Some(
15905                                (range.start.0 as isize - selection.head().0 as isize)
15906                                    ..(range.end.0 as isize - selection.head().0 as isize),
15907                            )
15908                        } else {
15909                            None
15910                        }
15911                    })
15912            });
15913
15914            cx.emit(EditorEvent::InputHandled {
15915                utf16_range_to_replace: range_to_replace,
15916                text: text.into(),
15917            });
15918
15919            if let Some(new_selected_ranges) = new_selected_ranges {
15920                this.change_selections(None, window, cx, |selections| {
15921                    selections.select_ranges(new_selected_ranges)
15922                });
15923                this.backspace(&Default::default(), window, cx);
15924            }
15925
15926            this.handle_input(text, window, cx);
15927        });
15928
15929        if let Some(transaction) = self.ime_transaction {
15930            self.buffer.update(cx, |buffer, cx| {
15931                buffer.group_until_transaction(transaction, cx);
15932            });
15933        }
15934
15935        self.unmark_text(window, cx);
15936    }
15937
15938    fn replace_and_mark_text_in_range(
15939        &mut self,
15940        range_utf16: Option<Range<usize>>,
15941        text: &str,
15942        new_selected_range_utf16: Option<Range<usize>>,
15943        window: &mut Window,
15944        cx: &mut Context<Self>,
15945    ) {
15946        if !self.input_enabled {
15947            return;
15948        }
15949
15950        let transaction = self.transact(window, cx, |this, window, cx| {
15951            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15952                let snapshot = this.buffer.read(cx).read(cx);
15953                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15954                    for marked_range in &mut marked_ranges {
15955                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15956                        marked_range.start.0 += relative_range_utf16.start;
15957                        marked_range.start =
15958                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15959                        marked_range.end =
15960                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15961                    }
15962                }
15963                Some(marked_ranges)
15964            } else if let Some(range_utf16) = range_utf16 {
15965                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15966                Some(this.selection_replacement_ranges(range_utf16, cx))
15967            } else {
15968                None
15969            };
15970
15971            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15972                let newest_selection_id = this.selections.newest_anchor().id;
15973                this.selections
15974                    .all::<OffsetUtf16>(cx)
15975                    .iter()
15976                    .zip(ranges_to_replace.iter())
15977                    .find_map(|(selection, range)| {
15978                        if selection.id == newest_selection_id {
15979                            Some(
15980                                (range.start.0 as isize - selection.head().0 as isize)
15981                                    ..(range.end.0 as isize - selection.head().0 as isize),
15982                            )
15983                        } else {
15984                            None
15985                        }
15986                    })
15987            });
15988
15989            cx.emit(EditorEvent::InputHandled {
15990                utf16_range_to_replace: range_to_replace,
15991                text: text.into(),
15992            });
15993
15994            if let Some(ranges) = ranges_to_replace {
15995                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15996            }
15997
15998            let marked_ranges = {
15999                let snapshot = this.buffer.read(cx).read(cx);
16000                this.selections
16001                    .disjoint_anchors()
16002                    .iter()
16003                    .map(|selection| {
16004                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16005                    })
16006                    .collect::<Vec<_>>()
16007            };
16008
16009            if text.is_empty() {
16010                this.unmark_text(window, cx);
16011            } else {
16012                this.highlight_text::<InputComposition>(
16013                    marked_ranges.clone(),
16014                    HighlightStyle {
16015                        underline: Some(UnderlineStyle {
16016                            thickness: px(1.),
16017                            color: None,
16018                            wavy: false,
16019                        }),
16020                        ..Default::default()
16021                    },
16022                    cx,
16023                );
16024            }
16025
16026            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16027            let use_autoclose = this.use_autoclose;
16028            let use_auto_surround = this.use_auto_surround;
16029            this.set_use_autoclose(false);
16030            this.set_use_auto_surround(false);
16031            this.handle_input(text, window, cx);
16032            this.set_use_autoclose(use_autoclose);
16033            this.set_use_auto_surround(use_auto_surround);
16034
16035            if let Some(new_selected_range) = new_selected_range_utf16 {
16036                let snapshot = this.buffer.read(cx).read(cx);
16037                let new_selected_ranges = marked_ranges
16038                    .into_iter()
16039                    .map(|marked_range| {
16040                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16041                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16042                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16043                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16044                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16045                    })
16046                    .collect::<Vec<_>>();
16047
16048                drop(snapshot);
16049                this.change_selections(None, window, cx, |selections| {
16050                    selections.select_ranges(new_selected_ranges)
16051                });
16052            }
16053        });
16054
16055        self.ime_transaction = self.ime_transaction.or(transaction);
16056        if let Some(transaction) = self.ime_transaction {
16057            self.buffer.update(cx, |buffer, cx| {
16058                buffer.group_until_transaction(transaction, cx);
16059            });
16060        }
16061
16062        if self.text_highlights::<InputComposition>(cx).is_none() {
16063            self.ime_transaction.take();
16064        }
16065    }
16066
16067    fn bounds_for_range(
16068        &mut self,
16069        range_utf16: Range<usize>,
16070        element_bounds: gpui::Bounds<Pixels>,
16071        window: &mut Window,
16072        cx: &mut Context<Self>,
16073    ) -> Option<gpui::Bounds<Pixels>> {
16074        let text_layout_details = self.text_layout_details(window);
16075        let gpui::Size {
16076            width: em_width,
16077            height: line_height,
16078        } = self.character_size(window);
16079
16080        let snapshot = self.snapshot(window, cx);
16081        let scroll_position = snapshot.scroll_position();
16082        let scroll_left = scroll_position.x * em_width;
16083
16084        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16085        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16086            + self.gutter_dimensions.width
16087            + self.gutter_dimensions.margin;
16088        let y = line_height * (start.row().as_f32() - scroll_position.y);
16089
16090        Some(Bounds {
16091            origin: element_bounds.origin + point(x, y),
16092            size: size(em_width, line_height),
16093        })
16094    }
16095
16096    fn character_index_for_point(
16097        &mut self,
16098        point: gpui::Point<Pixels>,
16099        _window: &mut Window,
16100        _cx: &mut Context<Self>,
16101    ) -> Option<usize> {
16102        let position_map = self.last_position_map.as_ref()?;
16103        if !position_map.text_hitbox.contains(&point) {
16104            return None;
16105        }
16106        let display_point = position_map.point_for_position(point).previous_valid;
16107        let anchor = position_map
16108            .snapshot
16109            .display_point_to_anchor(display_point, Bias::Left);
16110        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16111        Some(utf16_offset.0)
16112    }
16113}
16114
16115trait SelectionExt {
16116    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16117    fn spanned_rows(
16118        &self,
16119        include_end_if_at_line_start: bool,
16120        map: &DisplaySnapshot,
16121    ) -> Range<MultiBufferRow>;
16122}
16123
16124impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16125    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16126        let start = self
16127            .start
16128            .to_point(&map.buffer_snapshot)
16129            .to_display_point(map);
16130        let end = self
16131            .end
16132            .to_point(&map.buffer_snapshot)
16133            .to_display_point(map);
16134        if self.reversed {
16135            end..start
16136        } else {
16137            start..end
16138        }
16139    }
16140
16141    fn spanned_rows(
16142        &self,
16143        include_end_if_at_line_start: bool,
16144        map: &DisplaySnapshot,
16145    ) -> Range<MultiBufferRow> {
16146        let start = self.start.to_point(&map.buffer_snapshot);
16147        let mut end = self.end.to_point(&map.buffer_snapshot);
16148        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16149            end.row -= 1;
16150        }
16151
16152        let buffer_start = map.prev_line_boundary(start).0;
16153        let buffer_end = map.next_line_boundary(end).0;
16154        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16155    }
16156}
16157
16158impl<T: InvalidationRegion> InvalidationStack<T> {
16159    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16160    where
16161        S: Clone + ToOffset,
16162    {
16163        while let Some(region) = self.last() {
16164            let all_selections_inside_invalidation_ranges =
16165                if selections.len() == region.ranges().len() {
16166                    selections
16167                        .iter()
16168                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16169                        .all(|(selection, invalidation_range)| {
16170                            let head = selection.head().to_offset(buffer);
16171                            invalidation_range.start <= head && invalidation_range.end >= head
16172                        })
16173                } else {
16174                    false
16175                };
16176
16177            if all_selections_inside_invalidation_ranges {
16178                break;
16179            } else {
16180                self.pop();
16181            }
16182        }
16183    }
16184}
16185
16186impl<T> Default for InvalidationStack<T> {
16187    fn default() -> Self {
16188        Self(Default::default())
16189    }
16190}
16191
16192impl<T> Deref for InvalidationStack<T> {
16193    type Target = Vec<T>;
16194
16195    fn deref(&self) -> &Self::Target {
16196        &self.0
16197    }
16198}
16199
16200impl<T> DerefMut for InvalidationStack<T> {
16201    fn deref_mut(&mut self) -> &mut Self::Target {
16202        &mut self.0
16203    }
16204}
16205
16206impl InvalidationRegion for SnippetState {
16207    fn ranges(&self) -> &[Range<Anchor>] {
16208        &self.ranges[self.active_index]
16209    }
16210}
16211
16212pub fn diagnostic_block_renderer(
16213    diagnostic: Diagnostic,
16214    max_message_rows: Option<u8>,
16215    allow_closing: bool,
16216    _is_valid: bool,
16217) -> RenderBlock {
16218    let (text_without_backticks, code_ranges) =
16219        highlight_diagnostic_message(&diagnostic, max_message_rows);
16220
16221    Arc::new(move |cx: &mut BlockContext| {
16222        let group_id: SharedString = cx.block_id.to_string().into();
16223
16224        let mut text_style = cx.window.text_style().clone();
16225        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16226        let theme_settings = ThemeSettings::get_global(cx);
16227        text_style.font_family = theme_settings.buffer_font.family.clone();
16228        text_style.font_style = theme_settings.buffer_font.style;
16229        text_style.font_features = theme_settings.buffer_font.features.clone();
16230        text_style.font_weight = theme_settings.buffer_font.weight;
16231
16232        let multi_line_diagnostic = diagnostic.message.contains('\n');
16233
16234        let buttons = |diagnostic: &Diagnostic| {
16235            if multi_line_diagnostic {
16236                v_flex()
16237            } else {
16238                h_flex()
16239            }
16240            .when(allow_closing, |div| {
16241                div.children(diagnostic.is_primary.then(|| {
16242                    IconButton::new("close-block", IconName::XCircle)
16243                        .icon_color(Color::Muted)
16244                        .size(ButtonSize::Compact)
16245                        .style(ButtonStyle::Transparent)
16246                        .visible_on_hover(group_id.clone())
16247                        .on_click(move |_click, window, cx| {
16248                            window.dispatch_action(Box::new(Cancel), cx)
16249                        })
16250                        .tooltip(|window, cx| {
16251                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16252                        })
16253                }))
16254            })
16255            .child(
16256                IconButton::new("copy-block", IconName::Copy)
16257                    .icon_color(Color::Muted)
16258                    .size(ButtonSize::Compact)
16259                    .style(ButtonStyle::Transparent)
16260                    .visible_on_hover(group_id.clone())
16261                    .on_click({
16262                        let message = diagnostic.message.clone();
16263                        move |_click, _, cx| {
16264                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16265                        }
16266                    })
16267                    .tooltip(Tooltip::text("Copy diagnostic message")),
16268            )
16269        };
16270
16271        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16272            AvailableSpace::min_size(),
16273            cx.window,
16274            cx.app,
16275        );
16276
16277        h_flex()
16278            .id(cx.block_id)
16279            .group(group_id.clone())
16280            .relative()
16281            .size_full()
16282            .block_mouse_down()
16283            .pl(cx.gutter_dimensions.width)
16284            .w(cx.max_width - cx.gutter_dimensions.full_width())
16285            .child(
16286                div()
16287                    .flex()
16288                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16289                    .flex_shrink(),
16290            )
16291            .child(buttons(&diagnostic))
16292            .child(div().flex().flex_shrink_0().child(
16293                StyledText::new(text_without_backticks.clone()).with_highlights(
16294                    &text_style,
16295                    code_ranges.iter().map(|range| {
16296                        (
16297                            range.clone(),
16298                            HighlightStyle {
16299                                font_weight: Some(FontWeight::BOLD),
16300                                ..Default::default()
16301                            },
16302                        )
16303                    }),
16304                ),
16305            ))
16306            .into_any_element()
16307    })
16308}
16309
16310fn inline_completion_edit_text(
16311    current_snapshot: &BufferSnapshot,
16312    edits: &[(Range<Anchor>, String)],
16313    edit_preview: &EditPreview,
16314    include_deletions: bool,
16315    cx: &App,
16316) -> HighlightedText {
16317    let edits = edits
16318        .iter()
16319        .map(|(anchor, text)| {
16320            (
16321                anchor.start.text_anchor..anchor.end.text_anchor,
16322                text.clone(),
16323            )
16324        })
16325        .collect::<Vec<_>>();
16326
16327    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16328}
16329
16330pub fn highlight_diagnostic_message(
16331    diagnostic: &Diagnostic,
16332    mut max_message_rows: Option<u8>,
16333) -> (SharedString, Vec<Range<usize>>) {
16334    let mut text_without_backticks = String::new();
16335    let mut code_ranges = Vec::new();
16336
16337    if let Some(source) = &diagnostic.source {
16338        text_without_backticks.push_str(source);
16339        code_ranges.push(0..source.len());
16340        text_without_backticks.push_str(": ");
16341    }
16342
16343    let mut prev_offset = 0;
16344    let mut in_code_block = false;
16345    let has_row_limit = max_message_rows.is_some();
16346    let mut newline_indices = diagnostic
16347        .message
16348        .match_indices('\n')
16349        .filter(|_| has_row_limit)
16350        .map(|(ix, _)| ix)
16351        .fuse()
16352        .peekable();
16353
16354    for (quote_ix, _) in diagnostic
16355        .message
16356        .match_indices('`')
16357        .chain([(diagnostic.message.len(), "")])
16358    {
16359        let mut first_newline_ix = None;
16360        let mut last_newline_ix = None;
16361        while let Some(newline_ix) = newline_indices.peek() {
16362            if *newline_ix < quote_ix {
16363                if first_newline_ix.is_none() {
16364                    first_newline_ix = Some(*newline_ix);
16365                }
16366                last_newline_ix = Some(*newline_ix);
16367
16368                if let Some(rows_left) = &mut max_message_rows {
16369                    if *rows_left == 0 {
16370                        break;
16371                    } else {
16372                        *rows_left -= 1;
16373                    }
16374                }
16375                let _ = newline_indices.next();
16376            } else {
16377                break;
16378            }
16379        }
16380        let prev_len = text_without_backticks.len();
16381        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16382        text_without_backticks.push_str(new_text);
16383        if in_code_block {
16384            code_ranges.push(prev_len..text_without_backticks.len());
16385        }
16386        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16387        in_code_block = !in_code_block;
16388        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16389            text_without_backticks.push_str("...");
16390            break;
16391        }
16392    }
16393
16394    (text_without_backticks.into(), code_ranges)
16395}
16396
16397fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16398    match severity {
16399        DiagnosticSeverity::ERROR => colors.error,
16400        DiagnosticSeverity::WARNING => colors.warning,
16401        DiagnosticSeverity::INFORMATION => colors.info,
16402        DiagnosticSeverity::HINT => colors.info,
16403        _ => colors.ignored,
16404    }
16405}
16406
16407pub fn styled_runs_for_code_label<'a>(
16408    label: &'a CodeLabel,
16409    syntax_theme: &'a theme::SyntaxTheme,
16410) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16411    let fade_out = HighlightStyle {
16412        fade_out: Some(0.35),
16413        ..Default::default()
16414    };
16415
16416    let mut prev_end = label.filter_range.end;
16417    label
16418        .runs
16419        .iter()
16420        .enumerate()
16421        .flat_map(move |(ix, (range, highlight_id))| {
16422            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16423                style
16424            } else {
16425                return Default::default();
16426            };
16427            let mut muted_style = style;
16428            muted_style.highlight(fade_out);
16429
16430            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16431            if range.start >= label.filter_range.end {
16432                if range.start > prev_end {
16433                    runs.push((prev_end..range.start, fade_out));
16434                }
16435                runs.push((range.clone(), muted_style));
16436            } else if range.end <= label.filter_range.end {
16437                runs.push((range.clone(), style));
16438            } else {
16439                runs.push((range.start..label.filter_range.end, style));
16440                runs.push((label.filter_range.end..range.end, muted_style));
16441            }
16442            prev_end = cmp::max(prev_end, range.end);
16443
16444            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16445                runs.push((prev_end..label.text.len(), fade_out));
16446            }
16447
16448            runs
16449        })
16450}
16451
16452pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16453    let mut prev_index = 0;
16454    let mut prev_codepoint: Option<char> = None;
16455    text.char_indices()
16456        .chain([(text.len(), '\0')])
16457        .filter_map(move |(index, codepoint)| {
16458            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16459            let is_boundary = index == text.len()
16460                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16461                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16462            if is_boundary {
16463                let chunk = &text[prev_index..index];
16464                prev_index = index;
16465                Some(chunk)
16466            } else {
16467                None
16468            }
16469        })
16470}
16471
16472pub trait RangeToAnchorExt: Sized {
16473    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16474
16475    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16476        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16477        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16478    }
16479}
16480
16481impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16482    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16483        let start_offset = self.start.to_offset(snapshot);
16484        let end_offset = self.end.to_offset(snapshot);
16485        if start_offset == end_offset {
16486            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16487        } else {
16488            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16489        }
16490    }
16491}
16492
16493pub trait RowExt {
16494    fn as_f32(&self) -> f32;
16495
16496    fn next_row(&self) -> Self;
16497
16498    fn previous_row(&self) -> Self;
16499
16500    fn minus(&self, other: Self) -> u32;
16501}
16502
16503impl RowExt for DisplayRow {
16504    fn as_f32(&self) -> f32 {
16505        self.0 as f32
16506    }
16507
16508    fn next_row(&self) -> Self {
16509        Self(self.0 + 1)
16510    }
16511
16512    fn previous_row(&self) -> Self {
16513        Self(self.0.saturating_sub(1))
16514    }
16515
16516    fn minus(&self, other: Self) -> u32 {
16517        self.0 - other.0
16518    }
16519}
16520
16521impl RowExt for MultiBufferRow {
16522    fn as_f32(&self) -> f32 {
16523        self.0 as f32
16524    }
16525
16526    fn next_row(&self) -> Self {
16527        Self(self.0 + 1)
16528    }
16529
16530    fn previous_row(&self) -> Self {
16531        Self(self.0.saturating_sub(1))
16532    }
16533
16534    fn minus(&self, other: Self) -> u32 {
16535        self.0 - other.0
16536    }
16537}
16538
16539trait RowRangeExt {
16540    type Row;
16541
16542    fn len(&self) -> usize;
16543
16544    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16545}
16546
16547impl RowRangeExt for Range<MultiBufferRow> {
16548    type Row = MultiBufferRow;
16549
16550    fn len(&self) -> usize {
16551        (self.end.0 - self.start.0) as usize
16552    }
16553
16554    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16555        (self.start.0..self.end.0).map(MultiBufferRow)
16556    }
16557}
16558
16559impl RowRangeExt for Range<DisplayRow> {
16560    type Row = DisplayRow;
16561
16562    fn len(&self) -> usize {
16563        (self.end.0 - self.start.0) as usize
16564    }
16565
16566    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16567        (self.start.0..self.end.0).map(DisplayRow)
16568    }
16569}
16570
16571/// If select range has more than one line, we
16572/// just point the cursor to range.start.
16573fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16574    if range.start.row == range.end.row {
16575        range
16576    } else {
16577        range.start..range.start
16578    }
16579}
16580pub struct KillRing(ClipboardItem);
16581impl Global for KillRing {}
16582
16583const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16584
16585fn all_edits_insertions_or_deletions(
16586    edits: &Vec<(Range<Anchor>, String)>,
16587    snapshot: &MultiBufferSnapshot,
16588) -> bool {
16589    let mut all_insertions = true;
16590    let mut all_deletions = true;
16591
16592    for (range, new_text) in edits.iter() {
16593        let range_is_empty = range.to_offset(&snapshot).is_empty();
16594        let text_is_empty = new_text.is_empty();
16595
16596        if range_is_empty != text_is_empty {
16597            if range_is_empty {
16598                all_deletions = false;
16599            } else {
16600                all_insertions = false;
16601            }
16602        } else {
16603            return false;
16604        }
16605
16606        if !all_insertions && !all_deletions {
16607            return false;
16608        }
16609    }
16610    all_insertions || all_deletions
16611}