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::*;
   65pub use element::{
   66    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   67};
   68use element::{LineWithInvisibles, PositionMap};
   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 fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakEntity<Workspace>>,
  198    cx: &mut App,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(
  243        link_ranges,
  244        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace
  250                            .open_abs_path(path.clone(), false, window, cx)
  251                            .detach();
  252                    });
  253                }
  254            }
  255        },
  256    )
  257}
  258
  259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  260pub enum InlayId {
  261    InlineCompletion(usize),
  262    Hint(usize),
  263}
  264
  265impl InlayId {
  266    fn id(&self) -> usize {
  267        match self {
  268            Self::InlineCompletion(id) => *id,
  269            Self::Hint(id) => *id,
  270        }
  271    }
  272}
  273
  274enum DocumentHighlightRead {}
  275enum DocumentHighlightWrite {}
  276enum InputComposition {}
  277
  278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  279pub enum Navigated {
  280    Yes,
  281    No,
  282}
  283
  284impl Navigated {
  285    pub fn from_bool(yes: bool) -> Navigated {
  286        if yes {
  287            Navigated::Yes
  288        } else {
  289            Navigated::No
  290        }
  291    }
  292}
  293
  294pub fn init_settings(cx: &mut App) {
  295    EditorSettings::register(cx);
  296}
  297
  298pub fn init(cx: &mut App) {
  299    init_settings(cx);
  300
  301    workspace::register_project_item::<Editor>(cx);
  302    workspace::FollowableViewRegistry::register::<Editor>(cx);
  303    workspace::register_serializable_item::<Editor>(cx);
  304
  305    cx.observe_new(
  306        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  307            workspace.register_action(Editor::new_file);
  308            workspace.register_action(Editor::new_file_vertical);
  309            workspace.register_action(Editor::new_file_horizontal);
  310            workspace.register_action(Editor::cancel_language_server_work);
  311        },
  312    )
  313    .detach();
  314
  315    cx.on_action(move |_: &workspace::NewFile, cx| {
  316        let app_state = workspace::AppState::global(cx);
  317        if let Some(app_state) = app_state.upgrade() {
  318            workspace::open_new(
  319                Default::default(),
  320                app_state,
  321                cx,
  322                |workspace, window, cx| {
  323                    Editor::new_file(workspace, &Default::default(), window, cx)
  324                },
  325            )
  326            .detach();
  327        }
  328    });
  329    cx.on_action(move |_: &workspace::NewWindow, cx| {
  330        let app_state = workspace::AppState::global(cx);
  331        if let Some(app_state) = app_state.upgrade() {
  332            workspace::open_new(
  333                Default::default(),
  334                app_state,
  335                cx,
  336                |workspace, window, cx| {
  337                    cx.activate(true);
  338                    Editor::new_file(workspace, &Default::default(), window, cx)
  339                },
  340            )
  341            .detach();
  342        }
  343    });
  344}
  345
  346pub struct SearchWithinRange;
  347
  348trait InvalidationRegion {
  349    fn ranges(&self) -> &[Range<Anchor>];
  350}
  351
  352#[derive(Clone, Debug, PartialEq)]
  353pub enum SelectPhase {
  354    Begin {
  355        position: DisplayPoint,
  356        add: bool,
  357        click_count: usize,
  358    },
  359    BeginColumnar {
  360        position: DisplayPoint,
  361        reset: bool,
  362        goal_column: u32,
  363    },
  364    Extend {
  365        position: DisplayPoint,
  366        click_count: usize,
  367    },
  368    Update {
  369        position: DisplayPoint,
  370        goal_column: u32,
  371        scroll_delta: gpui::Point<f32>,
  372    },
  373    End,
  374}
  375
  376#[derive(Clone, Debug)]
  377pub enum SelectMode {
  378    Character,
  379    Word(Range<Anchor>),
  380    Line(Range<Anchor>),
  381    All,
  382}
  383
  384#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  385pub enum EditorMode {
  386    SingleLine { auto_width: bool },
  387    AutoHeight { max_lines: usize },
  388    Full,
  389}
  390
  391#[derive(Copy, Clone, Debug)]
  392pub enum SoftWrap {
  393    /// Prefer not to wrap at all.
  394    ///
  395    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  396    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  397    GitDiff,
  398    /// Prefer a single line generally, unless an overly long line is encountered.
  399    None,
  400    /// Soft wrap lines that exceed the editor width.
  401    EditorWidth,
  402    /// Soft wrap lines at the preferred line length.
  403    Column(u32),
  404    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  405    Bounded(u32),
  406}
  407
  408#[derive(Clone)]
  409pub struct EditorStyle {
  410    pub background: Hsla,
  411    pub local_player: PlayerColor,
  412    pub text: TextStyle,
  413    pub scrollbar_width: Pixels,
  414    pub syntax: Arc<SyntaxTheme>,
  415    pub status: StatusColors,
  416    pub inlay_hints_style: HighlightStyle,
  417    pub inline_completion_styles: InlineCompletionStyles,
  418    pub unnecessary_code_fade: f32,
  419}
  420
  421impl Default for EditorStyle {
  422    fn default() -> Self {
  423        Self {
  424            background: Hsla::default(),
  425            local_player: PlayerColor::default(),
  426            text: TextStyle::default(),
  427            scrollbar_width: Pixels::default(),
  428            syntax: Default::default(),
  429            // HACK: Status colors don't have a real default.
  430            // We should look into removing the status colors from the editor
  431            // style and retrieve them directly from the theme.
  432            status: StatusColors::dark(),
  433            inlay_hints_style: HighlightStyle::default(),
  434            inline_completion_styles: InlineCompletionStyles {
  435                insertion: HighlightStyle::default(),
  436                whitespace: HighlightStyle::default(),
  437            },
  438            unnecessary_code_fade: Default::default(),
  439        }
  440    }
  441}
  442
  443pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  444    let show_background = language_settings::language_settings(None, None, cx)
  445        .inlay_hints
  446        .show_background;
  447
  448    HighlightStyle {
  449        color: Some(cx.theme().status().hint),
  450        background_color: show_background.then(|| cx.theme().status().hint_background),
  451        ..HighlightStyle::default()
  452    }
  453}
  454
  455pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  456    InlineCompletionStyles {
  457        insertion: HighlightStyle {
  458            color: Some(cx.theme().status().predictive),
  459            ..HighlightStyle::default()
  460        },
  461        whitespace: HighlightStyle {
  462            background_color: Some(cx.theme().status().created_background),
  463            ..HighlightStyle::default()
  464        },
  465    }
  466}
  467
  468type CompletionId = usize;
  469
  470pub(crate) enum EditDisplayMode {
  471    TabAccept,
  472    DiffPopover,
  473    Inline,
  474}
  475
  476enum InlineCompletion {
  477    Edit {
  478        edits: Vec<(Range<Anchor>, String)>,
  479        edit_preview: Option<EditPreview>,
  480        display_mode: EditDisplayMode,
  481        snapshot: BufferSnapshot,
  482    },
  483    Move {
  484        target: Anchor,
  485        range_around_target: Range<text::Anchor>,
  486        snapshot: BufferSnapshot,
  487    },
  488}
  489
  490struct InlineCompletionState {
  491    inlay_ids: Vec<InlayId>,
  492    completion: InlineCompletion,
  493    completion_id: Option<SharedString>,
  494    invalidation_range: Range<Anchor>,
  495}
  496
  497enum InlineCompletionHighlight {}
  498
  499pub enum MenuInlineCompletionsPolicy {
  500    Never,
  501    ByProvider,
  502}
  503
  504#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  505struct EditorActionId(usize);
  506
  507impl EditorActionId {
  508    pub fn post_inc(&mut self) -> Self {
  509        let answer = self.0;
  510
  511        *self = Self(answer + 1);
  512
  513        Self(answer)
  514    }
  515}
  516
  517// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  518// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  519
  520type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  521type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  522
  523#[derive(Default)]
  524struct ScrollbarMarkerState {
  525    scrollbar_size: Size<Pixels>,
  526    dirty: bool,
  527    markers: Arc<[PaintQuad]>,
  528    pending_refresh: Option<Task<Result<()>>>,
  529}
  530
  531impl ScrollbarMarkerState {
  532    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  533        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  534    }
  535}
  536
  537#[derive(Clone, Debug)]
  538struct RunnableTasks {
  539    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  540    offset: MultiBufferOffset,
  541    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  542    column: u32,
  543    // Values of all named captures, including those starting with '_'
  544    extra_variables: HashMap<String, String>,
  545    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  546    context_range: Range<BufferOffset>,
  547}
  548
  549impl RunnableTasks {
  550    fn resolve<'a>(
  551        &'a self,
  552        cx: &'a task::TaskContext,
  553    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  554        self.templates.iter().filter_map(|(kind, template)| {
  555            template
  556                .resolve_task(&kind.to_id_base(), cx)
  557                .map(|task| (kind.clone(), task))
  558        })
  559    }
  560}
  561
  562#[derive(Clone)]
  563struct ResolvedTasks {
  564    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  565    position: Anchor,
  566}
  567#[derive(Copy, Clone, Debug)]
  568struct MultiBufferOffset(usize);
  569#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  570struct BufferOffset(usize);
  571
  572// Addons allow storing per-editor state in other crates (e.g. Vim)
  573pub trait Addon: 'static {
  574    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  575
  576    fn render_buffer_header_controls(
  577        &self,
  578        _: &ExcerptInfo,
  579        _: &Window,
  580        _: &App,
  581    ) -> Option<AnyElement> {
  582        None
  583    }
  584
  585    fn to_any(&self) -> &dyn std::any::Any;
  586}
  587
  588#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  589pub enum IsVimMode {
  590    Yes,
  591    No,
  592}
  593
  594/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  595///
  596/// See the [module level documentation](self) for more information.
  597pub struct Editor {
  598    focus_handle: FocusHandle,
  599    last_focused_descendant: Option<WeakFocusHandle>,
  600    /// The text buffer being edited
  601    buffer: Entity<MultiBuffer>,
  602    /// Map of how text in the buffer should be displayed.
  603    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  604    pub display_map: Entity<DisplayMap>,
  605    pub selections: SelectionsCollection,
  606    pub scroll_manager: ScrollManager,
  607    /// When inline assist editors are linked, they all render cursors because
  608    /// typing enters text into each of them, even the ones that aren't focused.
  609    pub(crate) show_cursor_when_unfocused: bool,
  610    columnar_selection_tail: Option<Anchor>,
  611    add_selections_state: Option<AddSelectionsState>,
  612    select_next_state: Option<SelectNextState>,
  613    select_prev_state: Option<SelectNextState>,
  614    selection_history: SelectionHistory,
  615    autoclose_regions: Vec<AutocloseRegion>,
  616    snippet_stack: InvalidationStack<SnippetState>,
  617    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  618    ime_transaction: Option<TransactionId>,
  619    active_diagnostics: Option<ActiveDiagnosticGroup>,
  620    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  621
  622    // TODO: make this a access method
  623    pub project: Option<Entity<Project>>,
  624    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  625    completion_provider: Option<Box<dyn CompletionProvider>>,
  626    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  627    blink_manager: Entity<BlinkManager>,
  628    show_cursor_names: bool,
  629    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  630    pub show_local_selections: bool,
  631    mode: EditorMode,
  632    show_breadcrumbs: bool,
  633    show_gutter: bool,
  634    show_scrollbars: bool,
  635    show_line_numbers: Option<bool>,
  636    use_relative_line_numbers: Option<bool>,
  637    show_git_diff_gutter: Option<bool>,
  638    show_code_actions: Option<bool>,
  639    show_runnables: Option<bool>,
  640    show_wrap_guides: Option<bool>,
  641    show_indent_guides: Option<bool>,
  642    placeholder_text: Option<Arc<str>>,
  643    highlight_order: usize,
  644    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  645    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  646    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  647    scrollbar_marker_state: ScrollbarMarkerState,
  648    active_indent_guides_state: ActiveIndentGuidesState,
  649    nav_history: Option<ItemNavHistory>,
  650    context_menu: RefCell<Option<CodeContextMenu>>,
  651    mouse_context_menu: Option<MouseContextMenu>,
  652    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  653    signature_help_state: SignatureHelpState,
  654    auto_signature_help: Option<bool>,
  655    find_all_references_task_sources: Vec<Anchor>,
  656    next_completion_id: CompletionId,
  657    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  658    code_actions_task: Option<Task<Result<()>>>,
  659    document_highlights_task: Option<Task<()>>,
  660    linked_editing_range_task: Option<Task<Option<()>>>,
  661    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  662    pending_rename: Option<RenameState>,
  663    searchable: bool,
  664    cursor_shape: CursorShape,
  665    current_line_highlight: Option<CurrentLineHighlight>,
  666    collapse_matches: bool,
  667    autoindent_mode: Option<AutoindentMode>,
  668    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  669    input_enabled: bool,
  670    use_modal_editing: bool,
  671    read_only: bool,
  672    leader_peer_id: Option<PeerId>,
  673    remote_id: Option<ViewId>,
  674    hover_state: HoverState,
  675    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  676    gutter_hovered: bool,
  677    hovered_link_state: Option<HoveredLinkState>,
  678    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  679    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  680    active_inline_completion: Option<InlineCompletionState>,
  681    /// Used to prevent flickering as the user types while the menu is open
  682    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  683    inline_completions_hidden_for_vim_mode: bool,
  684    show_inline_completions_override: Option<bool>,
  685    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  686    previewing_inline_completion: bool,
  687    inlay_hint_cache: InlayHintCache,
  688    next_inlay_id: usize,
  689    _subscriptions: Vec<Subscription>,
  690    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  691    gutter_dimensions: GutterDimensions,
  692    style: Option<EditorStyle>,
  693    text_style_refinement: Option<TextStyleRefinement>,
  694    next_editor_action_id: EditorActionId,
  695    editor_actions:
  696        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  697    use_autoclose: bool,
  698    use_auto_surround: bool,
  699    auto_replace_emoji_shortcode: bool,
  700    show_git_blame_gutter: bool,
  701    show_git_blame_inline: bool,
  702    show_git_blame_inline_delay_task: Option<Task<()>>,
  703    git_blame_inline_enabled: bool,
  704    serialize_dirty_buffers: bool,
  705    show_selection_menu: Option<bool>,
  706    blame: Option<Entity<GitBlame>>,
  707    blame_subscription: Option<Subscription>,
  708    custom_context_menu: Option<
  709        Box<
  710            dyn 'static
  711                + Fn(
  712                    &mut Self,
  713                    DisplayPoint,
  714                    &mut Window,
  715                    &mut Context<Self>,
  716                ) -> Option<Entity<ui::ContextMenu>>,
  717        >,
  718    >,
  719    last_bounds: Option<Bounds<Pixels>>,
  720    last_position_map: Option<Rc<PositionMap>>,
  721    expect_bounds_change: Option<Bounds<Pixels>>,
  722    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  723    tasks_update_task: Option<Task<()>>,
  724    in_project_search: bool,
  725    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  726    breadcrumb_header: Option<String>,
  727    focused_block: Option<FocusedBlock>,
  728    next_scroll_position: NextScrollCursorCenterTopBottom,
  729    addons: HashMap<TypeId, Box<dyn Addon>>,
  730    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  731    selection_mark_mode: bool,
  732    toggle_fold_multiple_buffers: Task<()>,
  733    _scroll_cursor_center_top_bottom_task: Task<()>,
  734}
  735
  736#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  737enum NextScrollCursorCenterTopBottom {
  738    #[default]
  739    Center,
  740    Top,
  741    Bottom,
  742}
  743
  744impl NextScrollCursorCenterTopBottom {
  745    fn next(&self) -> Self {
  746        match self {
  747            Self::Center => Self::Top,
  748            Self::Top => Self::Bottom,
  749            Self::Bottom => Self::Center,
  750        }
  751    }
  752}
  753
  754#[derive(Clone)]
  755pub struct EditorSnapshot {
  756    pub mode: EditorMode,
  757    show_gutter: bool,
  758    show_line_numbers: Option<bool>,
  759    show_git_diff_gutter: Option<bool>,
  760    show_code_actions: Option<bool>,
  761    show_runnables: Option<bool>,
  762    git_blame_gutter_max_author_length: Option<usize>,
  763    pub display_snapshot: DisplaySnapshot,
  764    pub placeholder_text: Option<Arc<str>>,
  765    is_focused: bool,
  766    scroll_anchor: ScrollAnchor,
  767    ongoing_scroll: OngoingScroll,
  768    current_line_highlight: CurrentLineHighlight,
  769    gutter_hovered: bool,
  770}
  771
  772const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  773
  774#[derive(Default, Debug, Clone, Copy)]
  775pub struct GutterDimensions {
  776    pub left_padding: Pixels,
  777    pub right_padding: Pixels,
  778    pub width: Pixels,
  779    pub margin: Pixels,
  780    pub git_blame_entries_width: Option<Pixels>,
  781}
  782
  783impl GutterDimensions {
  784    /// The full width of the space taken up by the gutter.
  785    pub fn full_width(&self) -> Pixels {
  786        self.margin + self.width
  787    }
  788
  789    /// The width of the space reserved for the fold indicators,
  790    /// use alongside 'justify_end' and `gutter_width` to
  791    /// right align content with the line numbers
  792    pub fn fold_area_width(&self) -> Pixels {
  793        self.margin + self.right_padding
  794    }
  795}
  796
  797#[derive(Debug)]
  798pub struct RemoteSelection {
  799    pub replica_id: ReplicaId,
  800    pub selection: Selection<Anchor>,
  801    pub cursor_shape: CursorShape,
  802    pub peer_id: PeerId,
  803    pub line_mode: bool,
  804    pub participant_index: Option<ParticipantIndex>,
  805    pub user_name: Option<SharedString>,
  806}
  807
  808#[derive(Clone, Debug)]
  809struct SelectionHistoryEntry {
  810    selections: Arc<[Selection<Anchor>]>,
  811    select_next_state: Option<SelectNextState>,
  812    select_prev_state: Option<SelectNextState>,
  813    add_selections_state: Option<AddSelectionsState>,
  814}
  815
  816enum SelectionHistoryMode {
  817    Normal,
  818    Undoing,
  819    Redoing,
  820}
  821
  822#[derive(Clone, PartialEq, Eq, Hash)]
  823struct HoveredCursor {
  824    replica_id: u16,
  825    selection_id: usize,
  826}
  827
  828impl Default for SelectionHistoryMode {
  829    fn default() -> Self {
  830        Self::Normal
  831    }
  832}
  833
  834#[derive(Default)]
  835struct SelectionHistory {
  836    #[allow(clippy::type_complexity)]
  837    selections_by_transaction:
  838        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  839    mode: SelectionHistoryMode,
  840    undo_stack: VecDeque<SelectionHistoryEntry>,
  841    redo_stack: VecDeque<SelectionHistoryEntry>,
  842}
  843
  844impl SelectionHistory {
  845    fn insert_transaction(
  846        &mut self,
  847        transaction_id: TransactionId,
  848        selections: Arc<[Selection<Anchor>]>,
  849    ) {
  850        self.selections_by_transaction
  851            .insert(transaction_id, (selections, None));
  852    }
  853
  854    #[allow(clippy::type_complexity)]
  855    fn transaction(
  856        &self,
  857        transaction_id: TransactionId,
  858    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  859        self.selections_by_transaction.get(&transaction_id)
  860    }
  861
  862    #[allow(clippy::type_complexity)]
  863    fn transaction_mut(
  864        &mut self,
  865        transaction_id: TransactionId,
  866    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  867        self.selections_by_transaction.get_mut(&transaction_id)
  868    }
  869
  870    fn push(&mut self, entry: SelectionHistoryEntry) {
  871        if !entry.selections.is_empty() {
  872            match self.mode {
  873                SelectionHistoryMode::Normal => {
  874                    self.push_undo(entry);
  875                    self.redo_stack.clear();
  876                }
  877                SelectionHistoryMode::Undoing => self.push_redo(entry),
  878                SelectionHistoryMode::Redoing => self.push_undo(entry),
  879            }
  880        }
  881    }
  882
  883    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  884        if self
  885            .undo_stack
  886            .back()
  887            .map_or(true, |e| e.selections != entry.selections)
  888        {
  889            self.undo_stack.push_back(entry);
  890            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  891                self.undo_stack.pop_front();
  892            }
  893        }
  894    }
  895
  896    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  897        if self
  898            .redo_stack
  899            .back()
  900            .map_or(true, |e| e.selections != entry.selections)
  901        {
  902            self.redo_stack.push_back(entry);
  903            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  904                self.redo_stack.pop_front();
  905            }
  906        }
  907    }
  908}
  909
  910struct RowHighlight {
  911    index: usize,
  912    range: Range<Anchor>,
  913    color: Hsla,
  914    should_autoscroll: bool,
  915}
  916
  917#[derive(Clone, Debug)]
  918struct AddSelectionsState {
  919    above: bool,
  920    stack: Vec<usize>,
  921}
  922
  923#[derive(Clone)]
  924struct SelectNextState {
  925    query: AhoCorasick,
  926    wordwise: bool,
  927    done: bool,
  928}
  929
  930impl std::fmt::Debug for SelectNextState {
  931    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  932        f.debug_struct(std::any::type_name::<Self>())
  933            .field("wordwise", &self.wordwise)
  934            .field("done", &self.done)
  935            .finish()
  936    }
  937}
  938
  939#[derive(Debug)]
  940struct AutocloseRegion {
  941    selection_id: usize,
  942    range: Range<Anchor>,
  943    pair: BracketPair,
  944}
  945
  946#[derive(Debug)]
  947struct SnippetState {
  948    ranges: Vec<Vec<Range<Anchor>>>,
  949    active_index: usize,
  950    choices: Vec<Option<Vec<String>>>,
  951}
  952
  953#[doc(hidden)]
  954pub struct RenameState {
  955    pub range: Range<Anchor>,
  956    pub old_name: Arc<str>,
  957    pub editor: Entity<Editor>,
  958    block_id: CustomBlockId,
  959}
  960
  961struct InvalidationStack<T>(Vec<T>);
  962
  963struct RegisteredInlineCompletionProvider {
  964    provider: Arc<dyn InlineCompletionProviderHandle>,
  965    _subscription: Subscription,
  966}
  967
  968#[derive(Debug)]
  969struct ActiveDiagnosticGroup {
  970    primary_range: Range<Anchor>,
  971    primary_message: String,
  972    group_id: usize,
  973    blocks: HashMap<CustomBlockId, Diagnostic>,
  974    is_valid: bool,
  975}
  976
  977#[derive(Serialize, Deserialize, Clone, Debug)]
  978pub struct ClipboardSelection {
  979    pub len: usize,
  980    pub is_entire_line: bool,
  981    pub first_line_indent: u32,
  982}
  983
  984#[derive(Debug)]
  985pub(crate) struct NavigationData {
  986    cursor_anchor: Anchor,
  987    cursor_position: Point,
  988    scroll_anchor: ScrollAnchor,
  989    scroll_top_row: u32,
  990}
  991
  992#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  993pub enum GotoDefinitionKind {
  994    Symbol,
  995    Declaration,
  996    Type,
  997    Implementation,
  998}
  999
 1000#[derive(Debug, Clone)]
 1001enum InlayHintRefreshReason {
 1002    Toggle(bool),
 1003    SettingsChange(InlayHintSettings),
 1004    NewLinesShown,
 1005    BufferEdited(HashSet<Arc<Language>>),
 1006    RefreshRequested,
 1007    ExcerptsRemoved(Vec<ExcerptId>),
 1008}
 1009
 1010impl InlayHintRefreshReason {
 1011    fn description(&self) -> &'static str {
 1012        match self {
 1013            Self::Toggle(_) => "toggle",
 1014            Self::SettingsChange(_) => "settings change",
 1015            Self::NewLinesShown => "new lines shown",
 1016            Self::BufferEdited(_) => "buffer edited",
 1017            Self::RefreshRequested => "refresh requested",
 1018            Self::ExcerptsRemoved(_) => "excerpts removed",
 1019        }
 1020    }
 1021}
 1022
 1023pub enum FormatTarget {
 1024    Buffers,
 1025    Ranges(Vec<Range<MultiBufferPoint>>),
 1026}
 1027
 1028pub(crate) struct FocusedBlock {
 1029    id: BlockId,
 1030    focus_handle: WeakFocusHandle,
 1031}
 1032
 1033#[derive(Clone)]
 1034enum JumpData {
 1035    MultiBufferRow {
 1036        row: MultiBufferRow,
 1037        line_offset_from_top: u32,
 1038    },
 1039    MultiBufferPoint {
 1040        excerpt_id: ExcerptId,
 1041        position: Point,
 1042        anchor: text::Anchor,
 1043        line_offset_from_top: u32,
 1044    },
 1045}
 1046
 1047pub enum MultibufferSelectionMode {
 1048    First,
 1049    All,
 1050}
 1051
 1052impl Editor {
 1053    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1054        let buffer = cx.new(|cx| Buffer::local("", cx));
 1055        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1056        Self::new(
 1057            EditorMode::SingleLine { auto_width: false },
 1058            buffer,
 1059            None,
 1060            false,
 1061            window,
 1062            cx,
 1063        )
 1064    }
 1065
 1066    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1067        let buffer = cx.new(|cx| Buffer::local("", cx));
 1068        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1069        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1070    }
 1071
 1072    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1073        let buffer = cx.new(|cx| Buffer::local("", cx));
 1074        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1075        Self::new(
 1076            EditorMode::SingleLine { auto_width: true },
 1077            buffer,
 1078            None,
 1079            false,
 1080            window,
 1081            cx,
 1082        )
 1083    }
 1084
 1085    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1086        let buffer = cx.new(|cx| Buffer::local("", cx));
 1087        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1088        Self::new(
 1089            EditorMode::AutoHeight { max_lines },
 1090            buffer,
 1091            None,
 1092            false,
 1093            window,
 1094            cx,
 1095        )
 1096    }
 1097
 1098    pub fn for_buffer(
 1099        buffer: Entity<Buffer>,
 1100        project: Option<Entity<Project>>,
 1101        window: &mut Window,
 1102        cx: &mut Context<Self>,
 1103    ) -> Self {
 1104        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1105        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1106    }
 1107
 1108    pub fn for_multibuffer(
 1109        buffer: Entity<MultiBuffer>,
 1110        project: Option<Entity<Project>>,
 1111        show_excerpt_controls: bool,
 1112        window: &mut Window,
 1113        cx: &mut Context<Self>,
 1114    ) -> Self {
 1115        Self::new(
 1116            EditorMode::Full,
 1117            buffer,
 1118            project,
 1119            show_excerpt_controls,
 1120            window,
 1121            cx,
 1122        )
 1123    }
 1124
 1125    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1126        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1127        let mut clone = Self::new(
 1128            self.mode,
 1129            self.buffer.clone(),
 1130            self.project.clone(),
 1131            show_excerpt_controls,
 1132            window,
 1133            cx,
 1134        );
 1135        self.display_map.update(cx, |display_map, cx| {
 1136            let snapshot = display_map.snapshot(cx);
 1137            clone.display_map.update(cx, |display_map, cx| {
 1138                display_map.set_state(&snapshot, cx);
 1139            });
 1140        });
 1141        clone.selections.clone_state(&self.selections);
 1142        clone.scroll_manager.clone_state(&self.scroll_manager);
 1143        clone.searchable = self.searchable;
 1144        clone
 1145    }
 1146
 1147    pub fn new(
 1148        mode: EditorMode,
 1149        buffer: Entity<MultiBuffer>,
 1150        project: Option<Entity<Project>>,
 1151        show_excerpt_controls: bool,
 1152        window: &mut Window,
 1153        cx: &mut Context<Self>,
 1154    ) -> Self {
 1155        let style = window.text_style();
 1156        let font_size = style.font_size.to_pixels(window.rem_size());
 1157        let editor = cx.entity().downgrade();
 1158        let fold_placeholder = FoldPlaceholder {
 1159            constrain_width: true,
 1160            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1161                let editor = editor.clone();
 1162                div()
 1163                    .id(fold_id)
 1164                    .bg(cx.theme().colors().ghost_element_background)
 1165                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1166                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1167                    .rounded_sm()
 1168                    .size_full()
 1169                    .cursor_pointer()
 1170                    .child("")
 1171                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1172                    .on_click(move |_, _window, cx| {
 1173                        editor
 1174                            .update(cx, |editor, cx| {
 1175                                editor.unfold_ranges(
 1176                                    &[fold_range.start..fold_range.end],
 1177                                    true,
 1178                                    false,
 1179                                    cx,
 1180                                );
 1181                                cx.stop_propagation();
 1182                            })
 1183                            .ok();
 1184                    })
 1185                    .into_any()
 1186            }),
 1187            merge_adjacent: true,
 1188            ..Default::default()
 1189        };
 1190        let display_map = cx.new(|cx| {
 1191            DisplayMap::new(
 1192                buffer.clone(),
 1193                style.font(),
 1194                font_size,
 1195                None,
 1196                show_excerpt_controls,
 1197                FILE_HEADER_HEIGHT,
 1198                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1199                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1200                fold_placeholder,
 1201                cx,
 1202            )
 1203        });
 1204
 1205        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1206
 1207        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1208
 1209        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1210            .then(|| language_settings::SoftWrap::None);
 1211
 1212        let mut project_subscriptions = Vec::new();
 1213        if mode == EditorMode::Full {
 1214            if let Some(project) = project.as_ref() {
 1215                if buffer.read(cx).is_singleton() {
 1216                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1217                        cx.emit(EditorEvent::TitleChanged);
 1218                    }));
 1219                }
 1220                project_subscriptions.push(cx.subscribe_in(
 1221                    project,
 1222                    window,
 1223                    |editor, _, event, window, cx| {
 1224                        if let project::Event::RefreshInlayHints = event {
 1225                            editor
 1226                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1227                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1228                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1229                                let focus_handle = editor.focus_handle(cx);
 1230                                if focus_handle.is_focused(window) {
 1231                                    let snapshot = buffer.read(cx).snapshot();
 1232                                    for (range, snippet) in snippet_edits {
 1233                                        let editor_range =
 1234                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1235                                        editor
 1236                                            .insert_snippet(
 1237                                                &[editor_range],
 1238                                                snippet.clone(),
 1239                                                window,
 1240                                                cx,
 1241                                            )
 1242                                            .ok();
 1243                                    }
 1244                                }
 1245                            }
 1246                        }
 1247                    },
 1248                ));
 1249                if let Some(task_inventory) = project
 1250                    .read(cx)
 1251                    .task_store()
 1252                    .read(cx)
 1253                    .task_inventory()
 1254                    .cloned()
 1255                {
 1256                    project_subscriptions.push(cx.observe_in(
 1257                        &task_inventory,
 1258                        window,
 1259                        |editor, _, window, cx| {
 1260                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1261                        },
 1262                    ));
 1263                }
 1264            }
 1265        }
 1266
 1267        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1268
 1269        let inlay_hint_settings =
 1270            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1271        let focus_handle = cx.focus_handle();
 1272        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1273            .detach();
 1274        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1275            .detach();
 1276        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1277            .detach();
 1278        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1279            .detach();
 1280
 1281        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1282            Some(false)
 1283        } else {
 1284            None
 1285        };
 1286
 1287        let mut code_action_providers = Vec::new();
 1288        if let Some(project) = project.clone() {
 1289            get_uncommitted_diff_for_buffer(
 1290                &project,
 1291                buffer.read(cx).all_buffers(),
 1292                buffer.clone(),
 1293                cx,
 1294            );
 1295            code_action_providers.push(Rc::new(project) as Rc<_>);
 1296        }
 1297
 1298        let mut this = Self {
 1299            focus_handle,
 1300            show_cursor_when_unfocused: false,
 1301            last_focused_descendant: None,
 1302            buffer: buffer.clone(),
 1303            display_map: display_map.clone(),
 1304            selections,
 1305            scroll_manager: ScrollManager::new(cx),
 1306            columnar_selection_tail: None,
 1307            add_selections_state: None,
 1308            select_next_state: None,
 1309            select_prev_state: None,
 1310            selection_history: Default::default(),
 1311            autoclose_regions: Default::default(),
 1312            snippet_stack: Default::default(),
 1313            select_larger_syntax_node_stack: Vec::new(),
 1314            ime_transaction: Default::default(),
 1315            active_diagnostics: None,
 1316            soft_wrap_mode_override,
 1317            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1318            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1319            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1320            project,
 1321            blink_manager: blink_manager.clone(),
 1322            show_local_selections: true,
 1323            show_scrollbars: true,
 1324            mode,
 1325            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1326            show_gutter: mode == EditorMode::Full,
 1327            show_line_numbers: None,
 1328            use_relative_line_numbers: None,
 1329            show_git_diff_gutter: None,
 1330            show_code_actions: None,
 1331            show_runnables: None,
 1332            show_wrap_guides: None,
 1333            show_indent_guides,
 1334            placeholder_text: None,
 1335            highlight_order: 0,
 1336            highlighted_rows: HashMap::default(),
 1337            background_highlights: Default::default(),
 1338            gutter_highlights: TreeMap::default(),
 1339            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1340            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1341            nav_history: None,
 1342            context_menu: RefCell::new(None),
 1343            mouse_context_menu: None,
 1344            completion_tasks: Default::default(),
 1345            signature_help_state: SignatureHelpState::default(),
 1346            auto_signature_help: None,
 1347            find_all_references_task_sources: Vec::new(),
 1348            next_completion_id: 0,
 1349            next_inlay_id: 0,
 1350            code_action_providers,
 1351            available_code_actions: Default::default(),
 1352            code_actions_task: Default::default(),
 1353            document_highlights_task: Default::default(),
 1354            linked_editing_range_task: Default::default(),
 1355            pending_rename: Default::default(),
 1356            searchable: true,
 1357            cursor_shape: EditorSettings::get_global(cx)
 1358                .cursor_shape
 1359                .unwrap_or_default(),
 1360            current_line_highlight: None,
 1361            autoindent_mode: Some(AutoindentMode::EachLine),
 1362            collapse_matches: false,
 1363            workspace: None,
 1364            input_enabled: true,
 1365            use_modal_editing: mode == EditorMode::Full,
 1366            read_only: false,
 1367            use_autoclose: true,
 1368            use_auto_surround: true,
 1369            auto_replace_emoji_shortcode: false,
 1370            leader_peer_id: None,
 1371            remote_id: None,
 1372            hover_state: Default::default(),
 1373            pending_mouse_down: None,
 1374            hovered_link_state: Default::default(),
 1375            edit_prediction_provider: None,
 1376            active_inline_completion: None,
 1377            stale_inline_completion_in_menu: None,
 1378            previewing_inline_completion: false,
 1379            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1380
 1381            gutter_hovered: false,
 1382            pixel_position_of_newest_cursor: None,
 1383            last_bounds: None,
 1384            last_position_map: None,
 1385            expect_bounds_change: None,
 1386            gutter_dimensions: GutterDimensions::default(),
 1387            style: None,
 1388            show_cursor_names: false,
 1389            hovered_cursors: Default::default(),
 1390            next_editor_action_id: EditorActionId::default(),
 1391            editor_actions: Rc::default(),
 1392            inline_completions_hidden_for_vim_mode: false,
 1393            show_inline_completions_override: None,
 1394            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1395            custom_context_menu: None,
 1396            show_git_blame_gutter: false,
 1397            show_git_blame_inline: false,
 1398            show_selection_menu: None,
 1399            show_git_blame_inline_delay_task: None,
 1400            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1401            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1402                .session
 1403                .restore_unsaved_buffers,
 1404            blame: None,
 1405            blame_subscription: None,
 1406            tasks: Default::default(),
 1407            _subscriptions: vec![
 1408                cx.observe(&buffer, Self::on_buffer_changed),
 1409                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1410                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1411                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1412                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1413                cx.observe_window_activation(window, |editor, window, cx| {
 1414                    let active = window.is_window_active();
 1415                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1416                        if active {
 1417                            blink_manager.enable(cx);
 1418                        } else {
 1419                            blink_manager.disable(cx);
 1420                        }
 1421                    });
 1422                }),
 1423            ],
 1424            tasks_update_task: None,
 1425            linked_edit_ranges: Default::default(),
 1426            in_project_search: false,
 1427            previous_search_ranges: None,
 1428            breadcrumb_header: None,
 1429            focused_block: None,
 1430            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1431            addons: HashMap::default(),
 1432            registered_buffers: HashMap::default(),
 1433            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1434            selection_mark_mode: false,
 1435            toggle_fold_multiple_buffers: Task::ready(()),
 1436            text_style_refinement: None,
 1437        };
 1438        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1439        this._subscriptions.extend(project_subscriptions);
 1440
 1441        this.end_selection(window, cx);
 1442        this.scroll_manager.show_scrollbar(window, cx);
 1443
 1444        if mode == EditorMode::Full {
 1445            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1446            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1447
 1448            if this.git_blame_inline_enabled {
 1449                this.git_blame_inline_enabled = true;
 1450                this.start_git_blame_inline(false, window, cx);
 1451            }
 1452
 1453            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1454                if let Some(project) = this.project.as_ref() {
 1455                    let lsp_store = project.read(cx).lsp_store();
 1456                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1457                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1458                    });
 1459                    this.registered_buffers
 1460                        .insert(buffer.read(cx).remote_id(), handle);
 1461                }
 1462            }
 1463        }
 1464
 1465        this.report_editor_event("Editor Opened", None, cx);
 1466        this
 1467    }
 1468
 1469    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1470        self.mouse_context_menu
 1471            .as_ref()
 1472            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1473    }
 1474
 1475    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1476        let mut key_context = KeyContext::new_with_defaults();
 1477        key_context.add("Editor");
 1478        let mode = match self.mode {
 1479            EditorMode::SingleLine { .. } => "single_line",
 1480            EditorMode::AutoHeight { .. } => "auto_height",
 1481            EditorMode::Full => "full",
 1482        };
 1483
 1484        if EditorSettings::jupyter_enabled(cx) {
 1485            key_context.add("jupyter");
 1486        }
 1487
 1488        key_context.set("mode", mode);
 1489        if self.pending_rename.is_some() {
 1490            key_context.add("renaming");
 1491        }
 1492
 1493        let mut showing_completions = false;
 1494
 1495        match self.context_menu.borrow().as_ref() {
 1496            Some(CodeContextMenu::Completions(_)) => {
 1497                key_context.add("menu");
 1498                key_context.add("showing_completions");
 1499                showing_completions = true;
 1500            }
 1501            Some(CodeContextMenu::CodeActions(_)) => {
 1502                key_context.add("menu");
 1503                key_context.add("showing_code_actions")
 1504            }
 1505            None => {}
 1506        }
 1507
 1508        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1509        if !self.focus_handle(cx).contains_focused(window, cx)
 1510            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1511        {
 1512            for addon in self.addons.values() {
 1513                addon.extend_key_context(&mut key_context, cx)
 1514            }
 1515        }
 1516
 1517        if let Some(extension) = self
 1518            .buffer
 1519            .read(cx)
 1520            .as_singleton()
 1521            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1522        {
 1523            key_context.set("extension", extension.to_string());
 1524        }
 1525
 1526        if self.has_active_inline_completion() {
 1527            key_context.add("copilot_suggestion");
 1528            key_context.add("edit_prediction");
 1529
 1530            if showing_completions || self.edit_prediction_requires_modifier(cx) {
 1531                key_context.add("edit_prediction_requires_modifier");
 1532            }
 1533        }
 1534
 1535        if self.selection_mark_mode {
 1536            key_context.add("selection_mode");
 1537        }
 1538
 1539        key_context
 1540    }
 1541
 1542    pub fn new_file(
 1543        workspace: &mut Workspace,
 1544        _: &workspace::NewFile,
 1545        window: &mut Window,
 1546        cx: &mut Context<Workspace>,
 1547    ) {
 1548        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1549            "Failed to create buffer",
 1550            window,
 1551            cx,
 1552            |e, _, _| match e.error_code() {
 1553                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1554                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1555                e.error_tag("required").unwrap_or("the latest version")
 1556            )),
 1557                _ => None,
 1558            },
 1559        );
 1560    }
 1561
 1562    pub fn new_in_workspace(
 1563        workspace: &mut Workspace,
 1564        window: &mut Window,
 1565        cx: &mut Context<Workspace>,
 1566    ) -> Task<Result<Entity<Editor>>> {
 1567        let project = workspace.project().clone();
 1568        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1569
 1570        cx.spawn_in(window, |workspace, mut cx| async move {
 1571            let buffer = create.await?;
 1572            workspace.update_in(&mut cx, |workspace, window, cx| {
 1573                let editor =
 1574                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1575                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1576                editor
 1577            })
 1578        })
 1579    }
 1580
 1581    fn new_file_vertical(
 1582        workspace: &mut Workspace,
 1583        _: &workspace::NewFileSplitVertical,
 1584        window: &mut Window,
 1585        cx: &mut Context<Workspace>,
 1586    ) {
 1587        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1588    }
 1589
 1590    fn new_file_horizontal(
 1591        workspace: &mut Workspace,
 1592        _: &workspace::NewFileSplitHorizontal,
 1593        window: &mut Window,
 1594        cx: &mut Context<Workspace>,
 1595    ) {
 1596        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1597    }
 1598
 1599    fn new_file_in_direction(
 1600        workspace: &mut Workspace,
 1601        direction: SplitDirection,
 1602        window: &mut Window,
 1603        cx: &mut Context<Workspace>,
 1604    ) {
 1605        let project = workspace.project().clone();
 1606        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1607
 1608        cx.spawn_in(window, |workspace, mut cx| async move {
 1609            let buffer = create.await?;
 1610            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1611                workspace.split_item(
 1612                    direction,
 1613                    Box::new(
 1614                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1615                    ),
 1616                    window,
 1617                    cx,
 1618                )
 1619            })?;
 1620            anyhow::Ok(())
 1621        })
 1622        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1623            match e.error_code() {
 1624                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1625                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1626                e.error_tag("required").unwrap_or("the latest version")
 1627            )),
 1628                _ => None,
 1629            }
 1630        });
 1631    }
 1632
 1633    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1634        self.leader_peer_id
 1635    }
 1636
 1637    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1638        &self.buffer
 1639    }
 1640
 1641    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1642        self.workspace.as_ref()?.0.upgrade()
 1643    }
 1644
 1645    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1646        self.buffer().read(cx).title(cx)
 1647    }
 1648
 1649    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1650        let git_blame_gutter_max_author_length = self
 1651            .render_git_blame_gutter(cx)
 1652            .then(|| {
 1653                if let Some(blame) = self.blame.as_ref() {
 1654                    let max_author_length =
 1655                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1656                    Some(max_author_length)
 1657                } else {
 1658                    None
 1659                }
 1660            })
 1661            .flatten();
 1662
 1663        EditorSnapshot {
 1664            mode: self.mode,
 1665            show_gutter: self.show_gutter,
 1666            show_line_numbers: self.show_line_numbers,
 1667            show_git_diff_gutter: self.show_git_diff_gutter,
 1668            show_code_actions: self.show_code_actions,
 1669            show_runnables: self.show_runnables,
 1670            git_blame_gutter_max_author_length,
 1671            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1672            scroll_anchor: self.scroll_manager.anchor(),
 1673            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1674            placeholder_text: self.placeholder_text.clone(),
 1675            is_focused: self.focus_handle.is_focused(window),
 1676            current_line_highlight: self
 1677                .current_line_highlight
 1678                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1679            gutter_hovered: self.gutter_hovered,
 1680        }
 1681    }
 1682
 1683    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1684        self.buffer.read(cx).language_at(point, cx)
 1685    }
 1686
 1687    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1688        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1689    }
 1690
 1691    pub fn active_excerpt(
 1692        &self,
 1693        cx: &App,
 1694    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1695        self.buffer
 1696            .read(cx)
 1697            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1698    }
 1699
 1700    pub fn mode(&self) -> EditorMode {
 1701        self.mode
 1702    }
 1703
 1704    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1705        self.collaboration_hub.as_deref()
 1706    }
 1707
 1708    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1709        self.collaboration_hub = Some(hub);
 1710    }
 1711
 1712    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1713        self.in_project_search = in_project_search;
 1714    }
 1715
 1716    pub fn set_custom_context_menu(
 1717        &mut self,
 1718        f: impl 'static
 1719            + Fn(
 1720                &mut Self,
 1721                DisplayPoint,
 1722                &mut Window,
 1723                &mut Context<Self>,
 1724            ) -> Option<Entity<ui::ContextMenu>>,
 1725    ) {
 1726        self.custom_context_menu = Some(Box::new(f))
 1727    }
 1728
 1729    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1730        self.completion_provider = provider;
 1731    }
 1732
 1733    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1734        self.semantics_provider.clone()
 1735    }
 1736
 1737    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1738        self.semantics_provider = provider;
 1739    }
 1740
 1741    pub fn set_edit_prediction_provider<T>(
 1742        &mut self,
 1743        provider: Option<Entity<T>>,
 1744        window: &mut Window,
 1745        cx: &mut Context<Self>,
 1746    ) where
 1747        T: EditPredictionProvider,
 1748    {
 1749        self.edit_prediction_provider =
 1750            provider.map(|provider| RegisteredInlineCompletionProvider {
 1751                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1752                    if this.focus_handle.is_focused(window) {
 1753                        this.update_visible_inline_completion(window, cx);
 1754                    }
 1755                }),
 1756                provider: Arc::new(provider),
 1757            });
 1758        self.refresh_inline_completion(false, false, window, cx);
 1759    }
 1760
 1761    pub fn placeholder_text(&self) -> Option<&str> {
 1762        self.placeholder_text.as_deref()
 1763    }
 1764
 1765    pub fn set_placeholder_text(
 1766        &mut self,
 1767        placeholder_text: impl Into<Arc<str>>,
 1768        cx: &mut Context<Self>,
 1769    ) {
 1770        let placeholder_text = Some(placeholder_text.into());
 1771        if self.placeholder_text != placeholder_text {
 1772            self.placeholder_text = placeholder_text;
 1773            cx.notify();
 1774        }
 1775    }
 1776
 1777    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1778        self.cursor_shape = cursor_shape;
 1779
 1780        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1781        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1782
 1783        cx.notify();
 1784    }
 1785
 1786    pub fn set_current_line_highlight(
 1787        &mut self,
 1788        current_line_highlight: Option<CurrentLineHighlight>,
 1789    ) {
 1790        self.current_line_highlight = current_line_highlight;
 1791    }
 1792
 1793    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1794        self.collapse_matches = collapse_matches;
 1795    }
 1796
 1797    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1798        let buffers = self.buffer.read(cx).all_buffers();
 1799        let Some(lsp_store) = self.lsp_store(cx) else {
 1800            return;
 1801        };
 1802        lsp_store.update(cx, |lsp_store, cx| {
 1803            for buffer in buffers {
 1804                self.registered_buffers
 1805                    .entry(buffer.read(cx).remote_id())
 1806                    .or_insert_with(|| {
 1807                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1808                    });
 1809            }
 1810        })
 1811    }
 1812
 1813    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1814        if self.collapse_matches {
 1815            return range.start..range.start;
 1816        }
 1817        range.clone()
 1818    }
 1819
 1820    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1821        if self.display_map.read(cx).clip_at_line_ends != clip {
 1822            self.display_map
 1823                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1824        }
 1825    }
 1826
 1827    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1828        self.input_enabled = input_enabled;
 1829    }
 1830
 1831    pub fn set_inline_completions_hidden_for_vim_mode(
 1832        &mut self,
 1833        hidden: bool,
 1834        window: &mut Window,
 1835        cx: &mut Context<Self>,
 1836    ) {
 1837        if hidden != self.inline_completions_hidden_for_vim_mode {
 1838            self.inline_completions_hidden_for_vim_mode = hidden;
 1839            if hidden {
 1840                self.update_visible_inline_completion(window, cx);
 1841            } else {
 1842                self.refresh_inline_completion(true, false, window, cx);
 1843            }
 1844        }
 1845    }
 1846
 1847    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1848        self.menu_inline_completions_policy = value;
 1849    }
 1850
 1851    pub fn set_autoindent(&mut self, autoindent: bool) {
 1852        if autoindent {
 1853            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1854        } else {
 1855            self.autoindent_mode = None;
 1856        }
 1857    }
 1858
 1859    pub fn read_only(&self, cx: &App) -> bool {
 1860        self.read_only || self.buffer.read(cx).read_only()
 1861    }
 1862
 1863    pub fn set_read_only(&mut self, read_only: bool) {
 1864        self.read_only = read_only;
 1865    }
 1866
 1867    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1868        self.use_autoclose = autoclose;
 1869    }
 1870
 1871    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1872        self.use_auto_surround = auto_surround;
 1873    }
 1874
 1875    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1876        self.auto_replace_emoji_shortcode = auto_replace;
 1877    }
 1878
 1879    pub fn toggle_inline_completions(
 1880        &mut self,
 1881        _: &ToggleEditPrediction,
 1882        window: &mut Window,
 1883        cx: &mut Context<Self>,
 1884    ) {
 1885        if self.show_inline_completions_override.is_some() {
 1886            self.set_show_inline_completions(None, window, cx);
 1887        } else {
 1888            let cursor = self.selections.newest_anchor().head();
 1889            if let Some((buffer, cursor_buffer_position)) =
 1890                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1891            {
 1892                let show_inline_completions = !self.should_show_inline_completions_in_buffer(
 1893                    &buffer,
 1894                    cursor_buffer_position,
 1895                    cx,
 1896                );
 1897                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1898            }
 1899        }
 1900    }
 1901
 1902    pub fn set_show_inline_completions(
 1903        &mut self,
 1904        show_edit_predictions: Option<bool>,
 1905        window: &mut Window,
 1906        cx: &mut Context<Self>,
 1907    ) {
 1908        self.show_inline_completions_override = show_edit_predictions;
 1909        self.refresh_inline_completion(false, true, window, cx);
 1910    }
 1911
 1912    pub fn inline_completion_start_anchor(&self) -> Option<Anchor> {
 1913        let active_completion = self.active_inline_completion.as_ref()?;
 1914        let result = match &active_completion.completion {
 1915            InlineCompletion::Edit { edits, .. } => edits.first()?.0.start,
 1916            InlineCompletion::Move { target, .. } => *target,
 1917        };
 1918        Some(result)
 1919    }
 1920
 1921    fn inline_completions_disabled_in_scope(
 1922        &self,
 1923        buffer: &Entity<Buffer>,
 1924        buffer_position: language::Anchor,
 1925        cx: &App,
 1926    ) -> bool {
 1927        let snapshot = buffer.read(cx).snapshot();
 1928        let settings = snapshot.settings_at(buffer_position, cx);
 1929
 1930        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1931            return false;
 1932        };
 1933
 1934        scope.override_name().map_or(false, |scope_name| {
 1935            settings
 1936                .edit_predictions_disabled_in
 1937                .iter()
 1938                .any(|s| s == scope_name)
 1939        })
 1940    }
 1941
 1942    pub fn set_use_modal_editing(&mut self, to: bool) {
 1943        self.use_modal_editing = to;
 1944    }
 1945
 1946    pub fn use_modal_editing(&self) -> bool {
 1947        self.use_modal_editing
 1948    }
 1949
 1950    fn selections_did_change(
 1951        &mut self,
 1952        local: bool,
 1953        old_cursor_position: &Anchor,
 1954        show_completions: bool,
 1955        window: &mut Window,
 1956        cx: &mut Context<Self>,
 1957    ) {
 1958        window.invalidate_character_coordinates();
 1959
 1960        // Copy selections to primary selection buffer
 1961        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1962        if local {
 1963            let selections = self.selections.all::<usize>(cx);
 1964            let buffer_handle = self.buffer.read(cx).read(cx);
 1965
 1966            let mut text = String::new();
 1967            for (index, selection) in selections.iter().enumerate() {
 1968                let text_for_selection = buffer_handle
 1969                    .text_for_range(selection.start..selection.end)
 1970                    .collect::<String>();
 1971
 1972                text.push_str(&text_for_selection);
 1973                if index != selections.len() - 1 {
 1974                    text.push('\n');
 1975                }
 1976            }
 1977
 1978            if !text.is_empty() {
 1979                cx.write_to_primary(ClipboardItem::new_string(text));
 1980            }
 1981        }
 1982
 1983        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1984            self.buffer.update(cx, |buffer, cx| {
 1985                buffer.set_active_selections(
 1986                    &self.selections.disjoint_anchors(),
 1987                    self.selections.line_mode,
 1988                    self.cursor_shape,
 1989                    cx,
 1990                )
 1991            });
 1992        }
 1993        let display_map = self
 1994            .display_map
 1995            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1996        let buffer = &display_map.buffer_snapshot;
 1997        self.add_selections_state = None;
 1998        self.select_next_state = None;
 1999        self.select_prev_state = None;
 2000        self.select_larger_syntax_node_stack.clear();
 2001        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2002        self.snippet_stack
 2003            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2004        self.take_rename(false, window, cx);
 2005
 2006        let new_cursor_position = self.selections.newest_anchor().head();
 2007
 2008        self.push_to_nav_history(
 2009            *old_cursor_position,
 2010            Some(new_cursor_position.to_point(buffer)),
 2011            cx,
 2012        );
 2013
 2014        if local {
 2015            let new_cursor_position = self.selections.newest_anchor().head();
 2016            let mut context_menu = self.context_menu.borrow_mut();
 2017            let completion_menu = match context_menu.as_ref() {
 2018                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2019                _ => {
 2020                    *context_menu = None;
 2021                    None
 2022                }
 2023            };
 2024            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2025                if !self.registered_buffers.contains_key(&buffer_id) {
 2026                    if let Some(lsp_store) = self.lsp_store(cx) {
 2027                        lsp_store.update(cx, |lsp_store, cx| {
 2028                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2029                                return;
 2030                            };
 2031                            self.registered_buffers.insert(
 2032                                buffer_id,
 2033                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2034                            );
 2035                        })
 2036                    }
 2037                }
 2038            }
 2039
 2040            if let Some(completion_menu) = completion_menu {
 2041                let cursor_position = new_cursor_position.to_offset(buffer);
 2042                let (word_range, kind) =
 2043                    buffer.surrounding_word(completion_menu.initial_position, true);
 2044                if kind == Some(CharKind::Word)
 2045                    && word_range.to_inclusive().contains(&cursor_position)
 2046                {
 2047                    let mut completion_menu = completion_menu.clone();
 2048                    drop(context_menu);
 2049
 2050                    let query = Self::completion_query(buffer, cursor_position);
 2051                    cx.spawn(move |this, mut cx| async move {
 2052                        completion_menu
 2053                            .filter(query.as_deref(), cx.background_executor().clone())
 2054                            .await;
 2055
 2056                        this.update(&mut cx, |this, cx| {
 2057                            let mut context_menu = this.context_menu.borrow_mut();
 2058                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2059                            else {
 2060                                return;
 2061                            };
 2062
 2063                            if menu.id > completion_menu.id {
 2064                                return;
 2065                            }
 2066
 2067                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2068                            drop(context_menu);
 2069                            cx.notify();
 2070                        })
 2071                    })
 2072                    .detach();
 2073
 2074                    if show_completions {
 2075                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2076                    }
 2077                } else {
 2078                    drop(context_menu);
 2079                    self.hide_context_menu(window, cx);
 2080                }
 2081            } else {
 2082                drop(context_menu);
 2083            }
 2084
 2085            hide_hover(self, cx);
 2086
 2087            if old_cursor_position.to_display_point(&display_map).row()
 2088                != new_cursor_position.to_display_point(&display_map).row()
 2089            {
 2090                self.available_code_actions.take();
 2091            }
 2092            self.refresh_code_actions(window, cx);
 2093            self.refresh_document_highlights(cx);
 2094            refresh_matching_bracket_highlights(self, window, cx);
 2095            self.update_visible_inline_completion(window, cx);
 2096            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2097            if self.git_blame_inline_enabled {
 2098                self.start_inline_blame_timer(window, cx);
 2099            }
 2100        }
 2101
 2102        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2103        cx.emit(EditorEvent::SelectionsChanged { local });
 2104
 2105        if self.selections.disjoint_anchors().len() == 1 {
 2106            cx.emit(SearchEvent::ActiveMatchChanged)
 2107        }
 2108        cx.notify();
 2109    }
 2110
 2111    pub fn change_selections<R>(
 2112        &mut self,
 2113        autoscroll: Option<Autoscroll>,
 2114        window: &mut Window,
 2115        cx: &mut Context<Self>,
 2116        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2117    ) -> R {
 2118        self.change_selections_inner(autoscroll, true, window, cx, change)
 2119    }
 2120
 2121    pub fn change_selections_inner<R>(
 2122        &mut self,
 2123        autoscroll: Option<Autoscroll>,
 2124        request_completions: bool,
 2125        window: &mut Window,
 2126        cx: &mut Context<Self>,
 2127        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2128    ) -> R {
 2129        let old_cursor_position = self.selections.newest_anchor().head();
 2130        self.push_to_selection_history();
 2131
 2132        let (changed, result) = self.selections.change_with(cx, change);
 2133
 2134        if changed {
 2135            if let Some(autoscroll) = autoscroll {
 2136                self.request_autoscroll(autoscroll, cx);
 2137            }
 2138            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2139
 2140            if self.should_open_signature_help_automatically(
 2141                &old_cursor_position,
 2142                self.signature_help_state.backspace_pressed(),
 2143                cx,
 2144            ) {
 2145                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2146            }
 2147            self.signature_help_state.set_backspace_pressed(false);
 2148        }
 2149
 2150        result
 2151    }
 2152
 2153    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2154    where
 2155        I: IntoIterator<Item = (Range<S>, T)>,
 2156        S: ToOffset,
 2157        T: Into<Arc<str>>,
 2158    {
 2159        if self.read_only(cx) {
 2160            return;
 2161        }
 2162
 2163        self.buffer
 2164            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2165    }
 2166
 2167    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2168    where
 2169        I: IntoIterator<Item = (Range<S>, T)>,
 2170        S: ToOffset,
 2171        T: Into<Arc<str>>,
 2172    {
 2173        if self.read_only(cx) {
 2174            return;
 2175        }
 2176
 2177        self.buffer.update(cx, |buffer, cx| {
 2178            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2179        });
 2180    }
 2181
 2182    pub fn edit_with_block_indent<I, S, T>(
 2183        &mut self,
 2184        edits: I,
 2185        original_indent_columns: Vec<u32>,
 2186        cx: &mut Context<Self>,
 2187    ) where
 2188        I: IntoIterator<Item = (Range<S>, T)>,
 2189        S: ToOffset,
 2190        T: Into<Arc<str>>,
 2191    {
 2192        if self.read_only(cx) {
 2193            return;
 2194        }
 2195
 2196        self.buffer.update(cx, |buffer, cx| {
 2197            buffer.edit(
 2198                edits,
 2199                Some(AutoindentMode::Block {
 2200                    original_indent_columns,
 2201                }),
 2202                cx,
 2203            )
 2204        });
 2205    }
 2206
 2207    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2208        self.hide_context_menu(window, cx);
 2209
 2210        match phase {
 2211            SelectPhase::Begin {
 2212                position,
 2213                add,
 2214                click_count,
 2215            } => self.begin_selection(position, add, click_count, window, cx),
 2216            SelectPhase::BeginColumnar {
 2217                position,
 2218                goal_column,
 2219                reset,
 2220            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2221            SelectPhase::Extend {
 2222                position,
 2223                click_count,
 2224            } => self.extend_selection(position, click_count, window, cx),
 2225            SelectPhase::Update {
 2226                position,
 2227                goal_column,
 2228                scroll_delta,
 2229            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2230            SelectPhase::End => self.end_selection(window, cx),
 2231        }
 2232    }
 2233
 2234    fn extend_selection(
 2235        &mut self,
 2236        position: DisplayPoint,
 2237        click_count: usize,
 2238        window: &mut Window,
 2239        cx: &mut Context<Self>,
 2240    ) {
 2241        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2242        let tail = self.selections.newest::<usize>(cx).tail();
 2243        self.begin_selection(position, false, click_count, window, cx);
 2244
 2245        let position = position.to_offset(&display_map, Bias::Left);
 2246        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2247
 2248        let mut pending_selection = self
 2249            .selections
 2250            .pending_anchor()
 2251            .expect("extend_selection not called with pending selection");
 2252        if position >= tail {
 2253            pending_selection.start = tail_anchor;
 2254        } else {
 2255            pending_selection.end = tail_anchor;
 2256            pending_selection.reversed = true;
 2257        }
 2258
 2259        let mut pending_mode = self.selections.pending_mode().unwrap();
 2260        match &mut pending_mode {
 2261            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2262            _ => {}
 2263        }
 2264
 2265        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2266            s.set_pending(pending_selection, pending_mode)
 2267        });
 2268    }
 2269
 2270    fn begin_selection(
 2271        &mut self,
 2272        position: DisplayPoint,
 2273        add: bool,
 2274        click_count: usize,
 2275        window: &mut Window,
 2276        cx: &mut Context<Self>,
 2277    ) {
 2278        if !self.focus_handle.is_focused(window) {
 2279            self.last_focused_descendant = None;
 2280            window.focus(&self.focus_handle);
 2281        }
 2282
 2283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2284        let buffer = &display_map.buffer_snapshot;
 2285        let newest_selection = self.selections.newest_anchor().clone();
 2286        let position = display_map.clip_point(position, Bias::Left);
 2287
 2288        let start;
 2289        let end;
 2290        let mode;
 2291        let mut auto_scroll;
 2292        match click_count {
 2293            1 => {
 2294                start = buffer.anchor_before(position.to_point(&display_map));
 2295                end = start;
 2296                mode = SelectMode::Character;
 2297                auto_scroll = true;
 2298            }
 2299            2 => {
 2300                let range = movement::surrounding_word(&display_map, position);
 2301                start = buffer.anchor_before(range.start.to_point(&display_map));
 2302                end = buffer.anchor_before(range.end.to_point(&display_map));
 2303                mode = SelectMode::Word(start..end);
 2304                auto_scroll = true;
 2305            }
 2306            3 => {
 2307                let position = display_map
 2308                    .clip_point(position, Bias::Left)
 2309                    .to_point(&display_map);
 2310                let line_start = display_map.prev_line_boundary(position).0;
 2311                let next_line_start = buffer.clip_point(
 2312                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2313                    Bias::Left,
 2314                );
 2315                start = buffer.anchor_before(line_start);
 2316                end = buffer.anchor_before(next_line_start);
 2317                mode = SelectMode::Line(start..end);
 2318                auto_scroll = true;
 2319            }
 2320            _ => {
 2321                start = buffer.anchor_before(0);
 2322                end = buffer.anchor_before(buffer.len());
 2323                mode = SelectMode::All;
 2324                auto_scroll = false;
 2325            }
 2326        }
 2327        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2328
 2329        let point_to_delete: Option<usize> = {
 2330            let selected_points: Vec<Selection<Point>> =
 2331                self.selections.disjoint_in_range(start..end, cx);
 2332
 2333            if !add || click_count > 1 {
 2334                None
 2335            } else if !selected_points.is_empty() {
 2336                Some(selected_points[0].id)
 2337            } else {
 2338                let clicked_point_already_selected =
 2339                    self.selections.disjoint.iter().find(|selection| {
 2340                        selection.start.to_point(buffer) == start.to_point(buffer)
 2341                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2342                    });
 2343
 2344                clicked_point_already_selected.map(|selection| selection.id)
 2345            }
 2346        };
 2347
 2348        let selections_count = self.selections.count();
 2349
 2350        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2351            if let Some(point_to_delete) = point_to_delete {
 2352                s.delete(point_to_delete);
 2353
 2354                if selections_count == 1 {
 2355                    s.set_pending_anchor_range(start..end, mode);
 2356                }
 2357            } else {
 2358                if !add {
 2359                    s.clear_disjoint();
 2360                } else if click_count > 1 {
 2361                    s.delete(newest_selection.id)
 2362                }
 2363
 2364                s.set_pending_anchor_range(start..end, mode);
 2365            }
 2366        });
 2367    }
 2368
 2369    fn begin_columnar_selection(
 2370        &mut self,
 2371        position: DisplayPoint,
 2372        goal_column: u32,
 2373        reset: bool,
 2374        window: &mut Window,
 2375        cx: &mut Context<Self>,
 2376    ) {
 2377        if !self.focus_handle.is_focused(window) {
 2378            self.last_focused_descendant = None;
 2379            window.focus(&self.focus_handle);
 2380        }
 2381
 2382        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2383
 2384        if reset {
 2385            let pointer_position = display_map
 2386                .buffer_snapshot
 2387                .anchor_before(position.to_point(&display_map));
 2388
 2389            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2390                s.clear_disjoint();
 2391                s.set_pending_anchor_range(
 2392                    pointer_position..pointer_position,
 2393                    SelectMode::Character,
 2394                );
 2395            });
 2396        }
 2397
 2398        let tail = self.selections.newest::<Point>(cx).tail();
 2399        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2400
 2401        if !reset {
 2402            self.select_columns(
 2403                tail.to_display_point(&display_map),
 2404                position,
 2405                goal_column,
 2406                &display_map,
 2407                window,
 2408                cx,
 2409            );
 2410        }
 2411    }
 2412
 2413    fn update_selection(
 2414        &mut self,
 2415        position: DisplayPoint,
 2416        goal_column: u32,
 2417        scroll_delta: gpui::Point<f32>,
 2418        window: &mut Window,
 2419        cx: &mut Context<Self>,
 2420    ) {
 2421        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2422
 2423        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2424            let tail = tail.to_display_point(&display_map);
 2425            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2426        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2427            let buffer = self.buffer.read(cx).snapshot(cx);
 2428            let head;
 2429            let tail;
 2430            let mode = self.selections.pending_mode().unwrap();
 2431            match &mode {
 2432                SelectMode::Character => {
 2433                    head = position.to_point(&display_map);
 2434                    tail = pending.tail().to_point(&buffer);
 2435                }
 2436                SelectMode::Word(original_range) => {
 2437                    let original_display_range = original_range.start.to_display_point(&display_map)
 2438                        ..original_range.end.to_display_point(&display_map);
 2439                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2440                        ..original_display_range.end.to_point(&display_map);
 2441                    if movement::is_inside_word(&display_map, position)
 2442                        || original_display_range.contains(&position)
 2443                    {
 2444                        let word_range = movement::surrounding_word(&display_map, position);
 2445                        if word_range.start < original_display_range.start {
 2446                            head = word_range.start.to_point(&display_map);
 2447                        } else {
 2448                            head = word_range.end.to_point(&display_map);
 2449                        }
 2450                    } else {
 2451                        head = position.to_point(&display_map);
 2452                    }
 2453
 2454                    if head <= original_buffer_range.start {
 2455                        tail = original_buffer_range.end;
 2456                    } else {
 2457                        tail = original_buffer_range.start;
 2458                    }
 2459                }
 2460                SelectMode::Line(original_range) => {
 2461                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2462
 2463                    let position = display_map
 2464                        .clip_point(position, Bias::Left)
 2465                        .to_point(&display_map);
 2466                    let line_start = display_map.prev_line_boundary(position).0;
 2467                    let next_line_start = buffer.clip_point(
 2468                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2469                        Bias::Left,
 2470                    );
 2471
 2472                    if line_start < original_range.start {
 2473                        head = line_start
 2474                    } else {
 2475                        head = next_line_start
 2476                    }
 2477
 2478                    if head <= original_range.start {
 2479                        tail = original_range.end;
 2480                    } else {
 2481                        tail = original_range.start;
 2482                    }
 2483                }
 2484                SelectMode::All => {
 2485                    return;
 2486                }
 2487            };
 2488
 2489            if head < tail {
 2490                pending.start = buffer.anchor_before(head);
 2491                pending.end = buffer.anchor_before(tail);
 2492                pending.reversed = true;
 2493            } else {
 2494                pending.start = buffer.anchor_before(tail);
 2495                pending.end = buffer.anchor_before(head);
 2496                pending.reversed = false;
 2497            }
 2498
 2499            self.change_selections(None, window, cx, |s| {
 2500                s.set_pending(pending, mode);
 2501            });
 2502        } else {
 2503            log::error!("update_selection dispatched with no pending selection");
 2504            return;
 2505        }
 2506
 2507        self.apply_scroll_delta(scroll_delta, window, cx);
 2508        cx.notify();
 2509    }
 2510
 2511    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2512        self.columnar_selection_tail.take();
 2513        if self.selections.pending_anchor().is_some() {
 2514            let selections = self.selections.all::<usize>(cx);
 2515            self.change_selections(None, window, cx, |s| {
 2516                s.select(selections);
 2517                s.clear_pending();
 2518            });
 2519        }
 2520    }
 2521
 2522    fn select_columns(
 2523        &mut self,
 2524        tail: DisplayPoint,
 2525        head: DisplayPoint,
 2526        goal_column: u32,
 2527        display_map: &DisplaySnapshot,
 2528        window: &mut Window,
 2529        cx: &mut Context<Self>,
 2530    ) {
 2531        let start_row = cmp::min(tail.row(), head.row());
 2532        let end_row = cmp::max(tail.row(), head.row());
 2533        let start_column = cmp::min(tail.column(), goal_column);
 2534        let end_column = cmp::max(tail.column(), goal_column);
 2535        let reversed = start_column < tail.column();
 2536
 2537        let selection_ranges = (start_row.0..=end_row.0)
 2538            .map(DisplayRow)
 2539            .filter_map(|row| {
 2540                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2541                    let start = display_map
 2542                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2543                        .to_point(display_map);
 2544                    let end = display_map
 2545                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2546                        .to_point(display_map);
 2547                    if reversed {
 2548                        Some(end..start)
 2549                    } else {
 2550                        Some(start..end)
 2551                    }
 2552                } else {
 2553                    None
 2554                }
 2555            })
 2556            .collect::<Vec<_>>();
 2557
 2558        self.change_selections(None, window, cx, |s| {
 2559            s.select_ranges(selection_ranges);
 2560        });
 2561        cx.notify();
 2562    }
 2563
 2564    pub fn has_pending_nonempty_selection(&self) -> bool {
 2565        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2566            Some(Selection { start, end, .. }) => start != end,
 2567            None => false,
 2568        };
 2569
 2570        pending_nonempty_selection
 2571            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2572    }
 2573
 2574    pub fn has_pending_selection(&self) -> bool {
 2575        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2576    }
 2577
 2578    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2579        self.selection_mark_mode = false;
 2580
 2581        if self.clear_expanded_diff_hunks(cx) {
 2582            cx.notify();
 2583            return;
 2584        }
 2585        if self.dismiss_menus_and_popups(true, window, cx) {
 2586            return;
 2587        }
 2588
 2589        if self.mode == EditorMode::Full
 2590            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2591        {
 2592            return;
 2593        }
 2594
 2595        cx.propagate();
 2596    }
 2597
 2598    pub fn dismiss_menus_and_popups(
 2599        &mut self,
 2600        is_user_requested: bool,
 2601        window: &mut Window,
 2602        cx: &mut Context<Self>,
 2603    ) -> bool {
 2604        if self.take_rename(false, window, cx).is_some() {
 2605            return true;
 2606        }
 2607
 2608        if hide_hover(self, cx) {
 2609            return true;
 2610        }
 2611
 2612        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2613            return true;
 2614        }
 2615
 2616        if self.hide_context_menu(window, cx).is_some() {
 2617            return true;
 2618        }
 2619
 2620        if self.mouse_context_menu.take().is_some() {
 2621            return true;
 2622        }
 2623
 2624        if is_user_requested && self.discard_inline_completion(true, cx) {
 2625            return true;
 2626        }
 2627
 2628        if self.snippet_stack.pop().is_some() {
 2629            return true;
 2630        }
 2631
 2632        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2633            self.dismiss_diagnostics(cx);
 2634            return true;
 2635        }
 2636
 2637        false
 2638    }
 2639
 2640    fn linked_editing_ranges_for(
 2641        &self,
 2642        selection: Range<text::Anchor>,
 2643        cx: &App,
 2644    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2645        if self.linked_edit_ranges.is_empty() {
 2646            return None;
 2647        }
 2648        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2649            selection.end.buffer_id.and_then(|end_buffer_id| {
 2650                if selection.start.buffer_id != Some(end_buffer_id) {
 2651                    return None;
 2652                }
 2653                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2654                let snapshot = buffer.read(cx).snapshot();
 2655                self.linked_edit_ranges
 2656                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2657                    .map(|ranges| (ranges, snapshot, buffer))
 2658            })?;
 2659        use text::ToOffset as TO;
 2660        // find offset from the start of current range to current cursor position
 2661        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2662
 2663        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2664        let start_difference = start_offset - start_byte_offset;
 2665        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2666        let end_difference = end_offset - start_byte_offset;
 2667        // Current range has associated linked ranges.
 2668        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2669        for range in linked_ranges.iter() {
 2670            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2671            let end_offset = start_offset + end_difference;
 2672            let start_offset = start_offset + start_difference;
 2673            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2674                continue;
 2675            }
 2676            if self.selections.disjoint_anchor_ranges().any(|s| {
 2677                if s.start.buffer_id != selection.start.buffer_id
 2678                    || s.end.buffer_id != selection.end.buffer_id
 2679                {
 2680                    return false;
 2681                }
 2682                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2683                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2684            }) {
 2685                continue;
 2686            }
 2687            let start = buffer_snapshot.anchor_after(start_offset);
 2688            let end = buffer_snapshot.anchor_after(end_offset);
 2689            linked_edits
 2690                .entry(buffer.clone())
 2691                .or_default()
 2692                .push(start..end);
 2693        }
 2694        Some(linked_edits)
 2695    }
 2696
 2697    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2698        let text: Arc<str> = text.into();
 2699
 2700        if self.read_only(cx) {
 2701            return;
 2702        }
 2703
 2704        let selections = self.selections.all_adjusted(cx);
 2705        let mut bracket_inserted = false;
 2706        let mut edits = Vec::new();
 2707        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2708        let mut new_selections = Vec::with_capacity(selections.len());
 2709        let mut new_autoclose_regions = Vec::new();
 2710        let snapshot = self.buffer.read(cx).read(cx);
 2711
 2712        for (selection, autoclose_region) in
 2713            self.selections_with_autoclose_regions(selections, &snapshot)
 2714        {
 2715            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2716                // Determine if the inserted text matches the opening or closing
 2717                // bracket of any of this language's bracket pairs.
 2718                let mut bracket_pair = None;
 2719                let mut is_bracket_pair_start = false;
 2720                let mut is_bracket_pair_end = false;
 2721                if !text.is_empty() {
 2722                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2723                    //  and they are removing the character that triggered IME popup.
 2724                    for (pair, enabled) in scope.brackets() {
 2725                        if !pair.close && !pair.surround {
 2726                            continue;
 2727                        }
 2728
 2729                        if enabled && pair.start.ends_with(text.as_ref()) {
 2730                            let prefix_len = pair.start.len() - text.len();
 2731                            let preceding_text_matches_prefix = prefix_len == 0
 2732                                || (selection.start.column >= (prefix_len as u32)
 2733                                    && snapshot.contains_str_at(
 2734                                        Point::new(
 2735                                            selection.start.row,
 2736                                            selection.start.column - (prefix_len as u32),
 2737                                        ),
 2738                                        &pair.start[..prefix_len],
 2739                                    ));
 2740                            if preceding_text_matches_prefix {
 2741                                bracket_pair = Some(pair.clone());
 2742                                is_bracket_pair_start = true;
 2743                                break;
 2744                            }
 2745                        }
 2746                        if pair.end.as_str() == text.as_ref() {
 2747                            bracket_pair = Some(pair.clone());
 2748                            is_bracket_pair_end = true;
 2749                            break;
 2750                        }
 2751                    }
 2752                }
 2753
 2754                if let Some(bracket_pair) = bracket_pair {
 2755                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2756                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2757                    let auto_surround =
 2758                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2759                    if selection.is_empty() {
 2760                        if is_bracket_pair_start {
 2761                            // If the inserted text is a suffix of an opening bracket and the
 2762                            // selection is preceded by the rest of the opening bracket, then
 2763                            // insert the closing bracket.
 2764                            let following_text_allows_autoclose = snapshot
 2765                                .chars_at(selection.start)
 2766                                .next()
 2767                                .map_or(true, |c| scope.should_autoclose_before(c));
 2768
 2769                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2770                                && bracket_pair.start.len() == 1
 2771                            {
 2772                                let target = bracket_pair.start.chars().next().unwrap();
 2773                                let current_line_count = snapshot
 2774                                    .reversed_chars_at(selection.start)
 2775                                    .take_while(|&c| c != '\n')
 2776                                    .filter(|&c| c == target)
 2777                                    .count();
 2778                                current_line_count % 2 == 1
 2779                            } else {
 2780                                false
 2781                            };
 2782
 2783                            if autoclose
 2784                                && bracket_pair.close
 2785                                && following_text_allows_autoclose
 2786                                && !is_closing_quote
 2787                            {
 2788                                let anchor = snapshot.anchor_before(selection.end);
 2789                                new_selections.push((selection.map(|_| anchor), text.len()));
 2790                                new_autoclose_regions.push((
 2791                                    anchor,
 2792                                    text.len(),
 2793                                    selection.id,
 2794                                    bracket_pair.clone(),
 2795                                ));
 2796                                edits.push((
 2797                                    selection.range(),
 2798                                    format!("{}{}", text, bracket_pair.end).into(),
 2799                                ));
 2800                                bracket_inserted = true;
 2801                                continue;
 2802                            }
 2803                        }
 2804
 2805                        if let Some(region) = autoclose_region {
 2806                            // If the selection is followed by an auto-inserted closing bracket,
 2807                            // then don't insert that closing bracket again; just move the selection
 2808                            // past the closing bracket.
 2809                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2810                                && text.as_ref() == region.pair.end.as_str();
 2811                            if should_skip {
 2812                                let anchor = snapshot.anchor_after(selection.end);
 2813                                new_selections
 2814                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2815                                continue;
 2816                            }
 2817                        }
 2818
 2819                        let always_treat_brackets_as_autoclosed = snapshot
 2820                            .settings_at(selection.start, cx)
 2821                            .always_treat_brackets_as_autoclosed;
 2822                        if always_treat_brackets_as_autoclosed
 2823                            && is_bracket_pair_end
 2824                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2825                        {
 2826                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2827                            // and the inserted text is a closing bracket and the selection is followed
 2828                            // by the closing bracket then move the selection past the closing bracket.
 2829                            let anchor = snapshot.anchor_after(selection.end);
 2830                            new_selections.push((selection.map(|_| anchor), text.len()));
 2831                            continue;
 2832                        }
 2833                    }
 2834                    // If an opening bracket is 1 character long and is typed while
 2835                    // text is selected, then surround that text with the bracket pair.
 2836                    else if auto_surround
 2837                        && bracket_pair.surround
 2838                        && is_bracket_pair_start
 2839                        && bracket_pair.start.chars().count() == 1
 2840                    {
 2841                        edits.push((selection.start..selection.start, text.clone()));
 2842                        edits.push((
 2843                            selection.end..selection.end,
 2844                            bracket_pair.end.as_str().into(),
 2845                        ));
 2846                        bracket_inserted = true;
 2847                        new_selections.push((
 2848                            Selection {
 2849                                id: selection.id,
 2850                                start: snapshot.anchor_after(selection.start),
 2851                                end: snapshot.anchor_before(selection.end),
 2852                                reversed: selection.reversed,
 2853                                goal: selection.goal,
 2854                            },
 2855                            0,
 2856                        ));
 2857                        continue;
 2858                    }
 2859                }
 2860            }
 2861
 2862            if self.auto_replace_emoji_shortcode
 2863                && selection.is_empty()
 2864                && text.as_ref().ends_with(':')
 2865            {
 2866                if let Some(possible_emoji_short_code) =
 2867                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2868                {
 2869                    if !possible_emoji_short_code.is_empty() {
 2870                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2871                            let emoji_shortcode_start = Point::new(
 2872                                selection.start.row,
 2873                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2874                            );
 2875
 2876                            // Remove shortcode from buffer
 2877                            edits.push((
 2878                                emoji_shortcode_start..selection.start,
 2879                                "".to_string().into(),
 2880                            ));
 2881                            new_selections.push((
 2882                                Selection {
 2883                                    id: selection.id,
 2884                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2885                                    end: snapshot.anchor_before(selection.start),
 2886                                    reversed: selection.reversed,
 2887                                    goal: selection.goal,
 2888                                },
 2889                                0,
 2890                            ));
 2891
 2892                            // Insert emoji
 2893                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2894                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2895                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2896
 2897                            continue;
 2898                        }
 2899                    }
 2900                }
 2901            }
 2902
 2903            // If not handling any auto-close operation, then just replace the selected
 2904            // text with the given input and move the selection to the end of the
 2905            // newly inserted text.
 2906            let anchor = snapshot.anchor_after(selection.end);
 2907            if !self.linked_edit_ranges.is_empty() {
 2908                let start_anchor = snapshot.anchor_before(selection.start);
 2909
 2910                let is_word_char = text.chars().next().map_or(true, |char| {
 2911                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2912                    classifier.is_word(char)
 2913                });
 2914
 2915                if is_word_char {
 2916                    if let Some(ranges) = self
 2917                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2918                    {
 2919                        for (buffer, edits) in ranges {
 2920                            linked_edits
 2921                                .entry(buffer.clone())
 2922                                .or_default()
 2923                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2924                        }
 2925                    }
 2926                }
 2927            }
 2928
 2929            new_selections.push((selection.map(|_| anchor), 0));
 2930            edits.push((selection.start..selection.end, text.clone()));
 2931        }
 2932
 2933        drop(snapshot);
 2934
 2935        self.transact(window, cx, |this, window, cx| {
 2936            this.buffer.update(cx, |buffer, cx| {
 2937                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2938            });
 2939            for (buffer, edits) in linked_edits {
 2940                buffer.update(cx, |buffer, cx| {
 2941                    let snapshot = buffer.snapshot();
 2942                    let edits = edits
 2943                        .into_iter()
 2944                        .map(|(range, text)| {
 2945                            use text::ToPoint as TP;
 2946                            let end_point = TP::to_point(&range.end, &snapshot);
 2947                            let start_point = TP::to_point(&range.start, &snapshot);
 2948                            (start_point..end_point, text)
 2949                        })
 2950                        .sorted_by_key(|(range, _)| range.start)
 2951                        .collect::<Vec<_>>();
 2952                    buffer.edit(edits, None, cx);
 2953                })
 2954            }
 2955            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2956            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2957            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2958            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2959                .zip(new_selection_deltas)
 2960                .map(|(selection, delta)| Selection {
 2961                    id: selection.id,
 2962                    start: selection.start + delta,
 2963                    end: selection.end + delta,
 2964                    reversed: selection.reversed,
 2965                    goal: SelectionGoal::None,
 2966                })
 2967                .collect::<Vec<_>>();
 2968
 2969            let mut i = 0;
 2970            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2971                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2972                let start = map.buffer_snapshot.anchor_before(position);
 2973                let end = map.buffer_snapshot.anchor_after(position);
 2974                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2975                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2976                        Ordering::Less => i += 1,
 2977                        Ordering::Greater => break,
 2978                        Ordering::Equal => {
 2979                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2980                                Ordering::Less => i += 1,
 2981                                Ordering::Equal => break,
 2982                                Ordering::Greater => break,
 2983                            }
 2984                        }
 2985                    }
 2986                }
 2987                this.autoclose_regions.insert(
 2988                    i,
 2989                    AutocloseRegion {
 2990                        selection_id,
 2991                        range: start..end,
 2992                        pair,
 2993                    },
 2994                );
 2995            }
 2996
 2997            let had_active_inline_completion = this.has_active_inline_completion();
 2998            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2999                s.select(new_selections)
 3000            });
 3001
 3002            if !bracket_inserted {
 3003                if let Some(on_type_format_task) =
 3004                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3005                {
 3006                    on_type_format_task.detach_and_log_err(cx);
 3007                }
 3008            }
 3009
 3010            let editor_settings = EditorSettings::get_global(cx);
 3011            if bracket_inserted
 3012                && (editor_settings.auto_signature_help
 3013                    || editor_settings.show_signature_help_after_edits)
 3014            {
 3015                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3016            }
 3017
 3018            let trigger_in_words =
 3019                this.show_edit_predictions_in_menu(cx) || !had_active_inline_completion;
 3020            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3021            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3022            this.refresh_inline_completion(true, false, window, cx);
 3023        });
 3024    }
 3025
 3026    fn find_possible_emoji_shortcode_at_position(
 3027        snapshot: &MultiBufferSnapshot,
 3028        position: Point,
 3029    ) -> Option<String> {
 3030        let mut chars = Vec::new();
 3031        let mut found_colon = false;
 3032        for char in snapshot.reversed_chars_at(position).take(100) {
 3033            // Found a possible emoji shortcode in the middle of the buffer
 3034            if found_colon {
 3035                if char.is_whitespace() {
 3036                    chars.reverse();
 3037                    return Some(chars.iter().collect());
 3038                }
 3039                // If the previous character is not a whitespace, we are in the middle of a word
 3040                // and we only want to complete the shortcode if the word is made up of other emojis
 3041                let mut containing_word = String::new();
 3042                for ch in snapshot
 3043                    .reversed_chars_at(position)
 3044                    .skip(chars.len() + 1)
 3045                    .take(100)
 3046                {
 3047                    if ch.is_whitespace() {
 3048                        break;
 3049                    }
 3050                    containing_word.push(ch);
 3051                }
 3052                let containing_word = containing_word.chars().rev().collect::<String>();
 3053                if util::word_consists_of_emojis(containing_word.as_str()) {
 3054                    chars.reverse();
 3055                    return Some(chars.iter().collect());
 3056                }
 3057            }
 3058
 3059            if char.is_whitespace() || !char.is_ascii() {
 3060                return None;
 3061            }
 3062            if char == ':' {
 3063                found_colon = true;
 3064            } else {
 3065                chars.push(char);
 3066            }
 3067        }
 3068        // Found a possible emoji shortcode at the beginning of the buffer
 3069        chars.reverse();
 3070        Some(chars.iter().collect())
 3071    }
 3072
 3073    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3074        self.transact(window, cx, |this, window, cx| {
 3075            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3076                let selections = this.selections.all::<usize>(cx);
 3077                let multi_buffer = this.buffer.read(cx);
 3078                let buffer = multi_buffer.snapshot(cx);
 3079                selections
 3080                    .iter()
 3081                    .map(|selection| {
 3082                        let start_point = selection.start.to_point(&buffer);
 3083                        let mut indent =
 3084                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3085                        indent.len = cmp::min(indent.len, start_point.column);
 3086                        let start = selection.start;
 3087                        let end = selection.end;
 3088                        let selection_is_empty = start == end;
 3089                        let language_scope = buffer.language_scope_at(start);
 3090                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3091                            &language_scope
 3092                        {
 3093                            let leading_whitespace_len = buffer
 3094                                .reversed_chars_at(start)
 3095                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3096                                .map(|c| c.len_utf8())
 3097                                .sum::<usize>();
 3098
 3099                            let trailing_whitespace_len = buffer
 3100                                .chars_at(end)
 3101                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3102                                .map(|c| c.len_utf8())
 3103                                .sum::<usize>();
 3104
 3105                            let insert_extra_newline =
 3106                                language.brackets().any(|(pair, enabled)| {
 3107                                    let pair_start = pair.start.trim_end();
 3108                                    let pair_end = pair.end.trim_start();
 3109
 3110                                    enabled
 3111                                        && pair.newline
 3112                                        && buffer.contains_str_at(
 3113                                            end + trailing_whitespace_len,
 3114                                            pair_end,
 3115                                        )
 3116                                        && buffer.contains_str_at(
 3117                                            (start - leading_whitespace_len)
 3118                                                .saturating_sub(pair_start.len()),
 3119                                            pair_start,
 3120                                        )
 3121                                });
 3122
 3123                            // Comment extension on newline is allowed only for cursor selections
 3124                            let comment_delimiter = maybe!({
 3125                                if !selection_is_empty {
 3126                                    return None;
 3127                                }
 3128
 3129                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3130                                    return None;
 3131                                }
 3132
 3133                                let delimiters = language.line_comment_prefixes();
 3134                                let max_len_of_delimiter =
 3135                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3136                                let (snapshot, range) =
 3137                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3138
 3139                                let mut index_of_first_non_whitespace = 0;
 3140                                let comment_candidate = snapshot
 3141                                    .chars_for_range(range)
 3142                                    .skip_while(|c| {
 3143                                        let should_skip = c.is_whitespace();
 3144                                        if should_skip {
 3145                                            index_of_first_non_whitespace += 1;
 3146                                        }
 3147                                        should_skip
 3148                                    })
 3149                                    .take(max_len_of_delimiter)
 3150                                    .collect::<String>();
 3151                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3152                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3153                                })?;
 3154                                let cursor_is_placed_after_comment_marker =
 3155                                    index_of_first_non_whitespace + comment_prefix.len()
 3156                                        <= start_point.column as usize;
 3157                                if cursor_is_placed_after_comment_marker {
 3158                                    Some(comment_prefix.clone())
 3159                                } else {
 3160                                    None
 3161                                }
 3162                            });
 3163                            (comment_delimiter, insert_extra_newline)
 3164                        } else {
 3165                            (None, false)
 3166                        };
 3167
 3168                        let capacity_for_delimiter = comment_delimiter
 3169                            .as_deref()
 3170                            .map(str::len)
 3171                            .unwrap_or_default();
 3172                        let mut new_text =
 3173                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3174                        new_text.push('\n');
 3175                        new_text.extend(indent.chars());
 3176                        if let Some(delimiter) = &comment_delimiter {
 3177                            new_text.push_str(delimiter);
 3178                        }
 3179                        if insert_extra_newline {
 3180                            new_text = new_text.repeat(2);
 3181                        }
 3182
 3183                        let anchor = buffer.anchor_after(end);
 3184                        let new_selection = selection.map(|_| anchor);
 3185                        (
 3186                            (start..end, new_text),
 3187                            (insert_extra_newline, new_selection),
 3188                        )
 3189                    })
 3190                    .unzip()
 3191            };
 3192
 3193            this.edit_with_autoindent(edits, cx);
 3194            let buffer = this.buffer.read(cx).snapshot(cx);
 3195            let new_selections = selection_fixup_info
 3196                .into_iter()
 3197                .map(|(extra_newline_inserted, new_selection)| {
 3198                    let mut cursor = new_selection.end.to_point(&buffer);
 3199                    if extra_newline_inserted {
 3200                        cursor.row -= 1;
 3201                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3202                    }
 3203                    new_selection.map(|_| cursor)
 3204                })
 3205                .collect();
 3206
 3207            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3208                s.select(new_selections)
 3209            });
 3210            this.refresh_inline_completion(true, false, window, cx);
 3211        });
 3212    }
 3213
 3214    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3215        let buffer = self.buffer.read(cx);
 3216        let snapshot = buffer.snapshot(cx);
 3217
 3218        let mut edits = Vec::new();
 3219        let mut rows = Vec::new();
 3220
 3221        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3222            let cursor = selection.head();
 3223            let row = cursor.row;
 3224
 3225            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3226
 3227            let newline = "\n".to_string();
 3228            edits.push((start_of_line..start_of_line, newline));
 3229
 3230            rows.push(row + rows_inserted as u32);
 3231        }
 3232
 3233        self.transact(window, cx, |editor, window, cx| {
 3234            editor.edit(edits, cx);
 3235
 3236            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3237                let mut index = 0;
 3238                s.move_cursors_with(|map, _, _| {
 3239                    let row = rows[index];
 3240                    index += 1;
 3241
 3242                    let point = Point::new(row, 0);
 3243                    let boundary = map.next_line_boundary(point).1;
 3244                    let clipped = map.clip_point(boundary, Bias::Left);
 3245
 3246                    (clipped, SelectionGoal::None)
 3247                });
 3248            });
 3249
 3250            let mut indent_edits = Vec::new();
 3251            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3252            for row in rows {
 3253                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3254                for (row, indent) in indents {
 3255                    if indent.len == 0 {
 3256                        continue;
 3257                    }
 3258
 3259                    let text = match indent.kind {
 3260                        IndentKind::Space => " ".repeat(indent.len as usize),
 3261                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3262                    };
 3263                    let point = Point::new(row.0, 0);
 3264                    indent_edits.push((point..point, text));
 3265                }
 3266            }
 3267            editor.edit(indent_edits, cx);
 3268        });
 3269    }
 3270
 3271    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3272        let buffer = self.buffer.read(cx);
 3273        let snapshot = buffer.snapshot(cx);
 3274
 3275        let mut edits = Vec::new();
 3276        let mut rows = Vec::new();
 3277        let mut rows_inserted = 0;
 3278
 3279        for selection in self.selections.all_adjusted(cx) {
 3280            let cursor = selection.head();
 3281            let row = cursor.row;
 3282
 3283            let point = Point::new(row + 1, 0);
 3284            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3285
 3286            let newline = "\n".to_string();
 3287            edits.push((start_of_line..start_of_line, newline));
 3288
 3289            rows_inserted += 1;
 3290            rows.push(row + rows_inserted);
 3291        }
 3292
 3293        self.transact(window, cx, |editor, window, cx| {
 3294            editor.edit(edits, cx);
 3295
 3296            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3297                let mut index = 0;
 3298                s.move_cursors_with(|map, _, _| {
 3299                    let row = rows[index];
 3300                    index += 1;
 3301
 3302                    let point = Point::new(row, 0);
 3303                    let boundary = map.next_line_boundary(point).1;
 3304                    let clipped = map.clip_point(boundary, Bias::Left);
 3305
 3306                    (clipped, SelectionGoal::None)
 3307                });
 3308            });
 3309
 3310            let mut indent_edits = Vec::new();
 3311            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3312            for row in rows {
 3313                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3314                for (row, indent) in indents {
 3315                    if indent.len == 0 {
 3316                        continue;
 3317                    }
 3318
 3319                    let text = match indent.kind {
 3320                        IndentKind::Space => " ".repeat(indent.len as usize),
 3321                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3322                    };
 3323                    let point = Point::new(row.0, 0);
 3324                    indent_edits.push((point..point, text));
 3325                }
 3326            }
 3327            editor.edit(indent_edits, cx);
 3328        });
 3329    }
 3330
 3331    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3332        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3333            original_indent_columns: Vec::new(),
 3334        });
 3335        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3336    }
 3337
 3338    fn insert_with_autoindent_mode(
 3339        &mut self,
 3340        text: &str,
 3341        autoindent_mode: Option<AutoindentMode>,
 3342        window: &mut Window,
 3343        cx: &mut Context<Self>,
 3344    ) {
 3345        if self.read_only(cx) {
 3346            return;
 3347        }
 3348
 3349        let text: Arc<str> = text.into();
 3350        self.transact(window, cx, |this, window, cx| {
 3351            let old_selections = this.selections.all_adjusted(cx);
 3352            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3353                let anchors = {
 3354                    let snapshot = buffer.read(cx);
 3355                    old_selections
 3356                        .iter()
 3357                        .map(|s| {
 3358                            let anchor = snapshot.anchor_after(s.head());
 3359                            s.map(|_| anchor)
 3360                        })
 3361                        .collect::<Vec<_>>()
 3362                };
 3363                buffer.edit(
 3364                    old_selections
 3365                        .iter()
 3366                        .map(|s| (s.start..s.end, text.clone())),
 3367                    autoindent_mode,
 3368                    cx,
 3369                );
 3370                anchors
 3371            });
 3372
 3373            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3374                s.select_anchors(selection_anchors);
 3375            });
 3376
 3377            cx.notify();
 3378        });
 3379    }
 3380
 3381    fn trigger_completion_on_input(
 3382        &mut self,
 3383        text: &str,
 3384        trigger_in_words: bool,
 3385        window: &mut Window,
 3386        cx: &mut Context<Self>,
 3387    ) {
 3388        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3389            self.show_completions(
 3390                &ShowCompletions {
 3391                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3392                },
 3393                window,
 3394                cx,
 3395            );
 3396        } else {
 3397            self.hide_context_menu(window, cx);
 3398        }
 3399    }
 3400
 3401    fn is_completion_trigger(
 3402        &self,
 3403        text: &str,
 3404        trigger_in_words: bool,
 3405        cx: &mut Context<Self>,
 3406    ) -> bool {
 3407        let position = self.selections.newest_anchor().head();
 3408        let multibuffer = self.buffer.read(cx);
 3409        let Some(buffer) = position
 3410            .buffer_id
 3411            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3412        else {
 3413            return false;
 3414        };
 3415
 3416        if let Some(completion_provider) = &self.completion_provider {
 3417            completion_provider.is_completion_trigger(
 3418                &buffer,
 3419                position.text_anchor,
 3420                text,
 3421                trigger_in_words,
 3422                cx,
 3423            )
 3424        } else {
 3425            false
 3426        }
 3427    }
 3428
 3429    /// If any empty selections is touching the start of its innermost containing autoclose
 3430    /// region, expand it to select the brackets.
 3431    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3432        let selections = self.selections.all::<usize>(cx);
 3433        let buffer = self.buffer.read(cx).read(cx);
 3434        let new_selections = self
 3435            .selections_with_autoclose_regions(selections, &buffer)
 3436            .map(|(mut selection, region)| {
 3437                if !selection.is_empty() {
 3438                    return selection;
 3439                }
 3440
 3441                if let Some(region) = region {
 3442                    let mut range = region.range.to_offset(&buffer);
 3443                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3444                        range.start -= region.pair.start.len();
 3445                        if buffer.contains_str_at(range.start, &region.pair.start)
 3446                            && buffer.contains_str_at(range.end, &region.pair.end)
 3447                        {
 3448                            range.end += region.pair.end.len();
 3449                            selection.start = range.start;
 3450                            selection.end = range.end;
 3451
 3452                            return selection;
 3453                        }
 3454                    }
 3455                }
 3456
 3457                let always_treat_brackets_as_autoclosed = buffer
 3458                    .settings_at(selection.start, cx)
 3459                    .always_treat_brackets_as_autoclosed;
 3460
 3461                if !always_treat_brackets_as_autoclosed {
 3462                    return selection;
 3463                }
 3464
 3465                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3466                    for (pair, enabled) in scope.brackets() {
 3467                        if !enabled || !pair.close {
 3468                            continue;
 3469                        }
 3470
 3471                        if buffer.contains_str_at(selection.start, &pair.end) {
 3472                            let pair_start_len = pair.start.len();
 3473                            if buffer.contains_str_at(
 3474                                selection.start.saturating_sub(pair_start_len),
 3475                                &pair.start,
 3476                            ) {
 3477                                selection.start -= pair_start_len;
 3478                                selection.end += pair.end.len();
 3479
 3480                                return selection;
 3481                            }
 3482                        }
 3483                    }
 3484                }
 3485
 3486                selection
 3487            })
 3488            .collect();
 3489
 3490        drop(buffer);
 3491        self.change_selections(None, window, cx, |selections| {
 3492            selections.select(new_selections)
 3493        });
 3494    }
 3495
 3496    /// Iterate the given selections, and for each one, find the smallest surrounding
 3497    /// autoclose region. This uses the ordering of the selections and the autoclose
 3498    /// regions to avoid repeated comparisons.
 3499    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3500        &'a self,
 3501        selections: impl IntoIterator<Item = Selection<D>>,
 3502        buffer: &'a MultiBufferSnapshot,
 3503    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3504        let mut i = 0;
 3505        let mut regions = self.autoclose_regions.as_slice();
 3506        selections.into_iter().map(move |selection| {
 3507            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3508
 3509            let mut enclosing = None;
 3510            while let Some(pair_state) = regions.get(i) {
 3511                if pair_state.range.end.to_offset(buffer) < range.start {
 3512                    regions = &regions[i + 1..];
 3513                    i = 0;
 3514                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3515                    break;
 3516                } else {
 3517                    if pair_state.selection_id == selection.id {
 3518                        enclosing = Some(pair_state);
 3519                    }
 3520                    i += 1;
 3521                }
 3522            }
 3523
 3524            (selection, enclosing)
 3525        })
 3526    }
 3527
 3528    /// Remove any autoclose regions that no longer contain their selection.
 3529    fn invalidate_autoclose_regions(
 3530        &mut self,
 3531        mut selections: &[Selection<Anchor>],
 3532        buffer: &MultiBufferSnapshot,
 3533    ) {
 3534        self.autoclose_regions.retain(|state| {
 3535            let mut i = 0;
 3536            while let Some(selection) = selections.get(i) {
 3537                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3538                    selections = &selections[1..];
 3539                    continue;
 3540                }
 3541                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3542                    break;
 3543                }
 3544                if selection.id == state.selection_id {
 3545                    return true;
 3546                } else {
 3547                    i += 1;
 3548                }
 3549            }
 3550            false
 3551        });
 3552    }
 3553
 3554    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3555        let offset = position.to_offset(buffer);
 3556        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3557        if offset > word_range.start && kind == Some(CharKind::Word) {
 3558            Some(
 3559                buffer
 3560                    .text_for_range(word_range.start..offset)
 3561                    .collect::<String>(),
 3562            )
 3563        } else {
 3564            None
 3565        }
 3566    }
 3567
 3568    pub fn toggle_inlay_hints(
 3569        &mut self,
 3570        _: &ToggleInlayHints,
 3571        _: &mut Window,
 3572        cx: &mut Context<Self>,
 3573    ) {
 3574        self.refresh_inlay_hints(
 3575            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3576            cx,
 3577        );
 3578    }
 3579
 3580    pub fn inlay_hints_enabled(&self) -> bool {
 3581        self.inlay_hint_cache.enabled
 3582    }
 3583
 3584    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3585        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3586            return;
 3587        }
 3588
 3589        let reason_description = reason.description();
 3590        let ignore_debounce = matches!(
 3591            reason,
 3592            InlayHintRefreshReason::SettingsChange(_)
 3593                | InlayHintRefreshReason::Toggle(_)
 3594                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3595        );
 3596        let (invalidate_cache, required_languages) = match reason {
 3597            InlayHintRefreshReason::Toggle(enabled) => {
 3598                self.inlay_hint_cache.enabled = enabled;
 3599                if enabled {
 3600                    (InvalidationStrategy::RefreshRequested, None)
 3601                } else {
 3602                    self.inlay_hint_cache.clear();
 3603                    self.splice_inlays(
 3604                        &self
 3605                            .visible_inlay_hints(cx)
 3606                            .iter()
 3607                            .map(|inlay| inlay.id)
 3608                            .collect::<Vec<InlayId>>(),
 3609                        Vec::new(),
 3610                        cx,
 3611                    );
 3612                    return;
 3613                }
 3614            }
 3615            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3616                match self.inlay_hint_cache.update_settings(
 3617                    &self.buffer,
 3618                    new_settings,
 3619                    self.visible_inlay_hints(cx),
 3620                    cx,
 3621                ) {
 3622                    ControlFlow::Break(Some(InlaySplice {
 3623                        to_remove,
 3624                        to_insert,
 3625                    })) => {
 3626                        self.splice_inlays(&to_remove, to_insert, cx);
 3627                        return;
 3628                    }
 3629                    ControlFlow::Break(None) => return,
 3630                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3631                }
 3632            }
 3633            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3634                if let Some(InlaySplice {
 3635                    to_remove,
 3636                    to_insert,
 3637                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3638                {
 3639                    self.splice_inlays(&to_remove, to_insert, cx);
 3640                }
 3641                return;
 3642            }
 3643            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3644            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3645                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3646            }
 3647            InlayHintRefreshReason::RefreshRequested => {
 3648                (InvalidationStrategy::RefreshRequested, None)
 3649            }
 3650        };
 3651
 3652        if let Some(InlaySplice {
 3653            to_remove,
 3654            to_insert,
 3655        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3656            reason_description,
 3657            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3658            invalidate_cache,
 3659            ignore_debounce,
 3660            cx,
 3661        ) {
 3662            self.splice_inlays(&to_remove, to_insert, cx);
 3663        }
 3664    }
 3665
 3666    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3667        self.display_map
 3668            .read(cx)
 3669            .current_inlays()
 3670            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3671            .cloned()
 3672            .collect()
 3673    }
 3674
 3675    pub fn excerpts_for_inlay_hints_query(
 3676        &self,
 3677        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3678        cx: &mut Context<Editor>,
 3679    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3680        let Some(project) = self.project.as_ref() else {
 3681            return HashMap::default();
 3682        };
 3683        let project = project.read(cx);
 3684        let multi_buffer = self.buffer().read(cx);
 3685        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3686        let multi_buffer_visible_start = self
 3687            .scroll_manager
 3688            .anchor()
 3689            .anchor
 3690            .to_point(&multi_buffer_snapshot);
 3691        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3692            multi_buffer_visible_start
 3693                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3694            Bias::Left,
 3695        );
 3696        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3697        multi_buffer_snapshot
 3698            .range_to_buffer_ranges(multi_buffer_visible_range)
 3699            .into_iter()
 3700            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3701            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3702                let buffer_file = project::File::from_dyn(buffer.file())?;
 3703                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3704                let worktree_entry = buffer_worktree
 3705                    .read(cx)
 3706                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3707                if worktree_entry.is_ignored {
 3708                    return None;
 3709                }
 3710
 3711                let language = buffer.language()?;
 3712                if let Some(restrict_to_languages) = restrict_to_languages {
 3713                    if !restrict_to_languages.contains(language) {
 3714                        return None;
 3715                    }
 3716                }
 3717                Some((
 3718                    excerpt_id,
 3719                    (
 3720                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3721                        buffer.version().clone(),
 3722                        excerpt_visible_range,
 3723                    ),
 3724                ))
 3725            })
 3726            .collect()
 3727    }
 3728
 3729    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3730        TextLayoutDetails {
 3731            text_system: window.text_system().clone(),
 3732            editor_style: self.style.clone().unwrap(),
 3733            rem_size: window.rem_size(),
 3734            scroll_anchor: self.scroll_manager.anchor(),
 3735            visible_rows: self.visible_line_count(),
 3736            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3737        }
 3738    }
 3739
 3740    pub fn splice_inlays(
 3741        &self,
 3742        to_remove: &[InlayId],
 3743        to_insert: Vec<Inlay>,
 3744        cx: &mut Context<Self>,
 3745    ) {
 3746        self.display_map.update(cx, |display_map, cx| {
 3747            display_map.splice_inlays(to_remove, to_insert, cx)
 3748        });
 3749        cx.notify();
 3750    }
 3751
 3752    fn trigger_on_type_formatting(
 3753        &self,
 3754        input: String,
 3755        window: &mut Window,
 3756        cx: &mut Context<Self>,
 3757    ) -> Option<Task<Result<()>>> {
 3758        if input.len() != 1 {
 3759            return None;
 3760        }
 3761
 3762        let project = self.project.as_ref()?;
 3763        let position = self.selections.newest_anchor().head();
 3764        let (buffer, buffer_position) = self
 3765            .buffer
 3766            .read(cx)
 3767            .text_anchor_for_position(position, cx)?;
 3768
 3769        let settings = language_settings::language_settings(
 3770            buffer
 3771                .read(cx)
 3772                .language_at(buffer_position)
 3773                .map(|l| l.name()),
 3774            buffer.read(cx).file(),
 3775            cx,
 3776        );
 3777        if !settings.use_on_type_format {
 3778            return None;
 3779        }
 3780
 3781        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3782        // hence we do LSP request & edit on host side only — add formats to host's history.
 3783        let push_to_lsp_host_history = true;
 3784        // If this is not the host, append its history with new edits.
 3785        let push_to_client_history = project.read(cx).is_via_collab();
 3786
 3787        let on_type_formatting = project.update(cx, |project, cx| {
 3788            project.on_type_format(
 3789                buffer.clone(),
 3790                buffer_position,
 3791                input,
 3792                push_to_lsp_host_history,
 3793                cx,
 3794            )
 3795        });
 3796        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3797            if let Some(transaction) = on_type_formatting.await? {
 3798                if push_to_client_history {
 3799                    buffer
 3800                        .update(&mut cx, |buffer, _| {
 3801                            buffer.push_transaction(transaction, Instant::now());
 3802                        })
 3803                        .ok();
 3804                }
 3805                editor.update(&mut cx, |editor, cx| {
 3806                    editor.refresh_document_highlights(cx);
 3807                })?;
 3808            }
 3809            Ok(())
 3810        }))
 3811    }
 3812
 3813    pub fn show_completions(
 3814        &mut self,
 3815        options: &ShowCompletions,
 3816        window: &mut Window,
 3817        cx: &mut Context<Self>,
 3818    ) {
 3819        if self.pending_rename.is_some() {
 3820            return;
 3821        }
 3822
 3823        let Some(provider) = self.completion_provider.as_ref() else {
 3824            return;
 3825        };
 3826
 3827        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3828            return;
 3829        }
 3830
 3831        let position = self.selections.newest_anchor().head();
 3832        if position.diff_base_anchor.is_some() {
 3833            return;
 3834        }
 3835        let (buffer, buffer_position) =
 3836            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3837                output
 3838            } else {
 3839                return;
 3840            };
 3841        let show_completion_documentation = buffer
 3842            .read(cx)
 3843            .snapshot()
 3844            .settings_at(buffer_position, cx)
 3845            .show_completion_documentation;
 3846
 3847        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3848
 3849        let trigger_kind = match &options.trigger {
 3850            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3851                CompletionTriggerKind::TRIGGER_CHARACTER
 3852            }
 3853            _ => CompletionTriggerKind::INVOKED,
 3854        };
 3855        let completion_context = CompletionContext {
 3856            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3857                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3858                    Some(String::from(trigger))
 3859                } else {
 3860                    None
 3861                }
 3862            }),
 3863            trigger_kind,
 3864        };
 3865        let completions =
 3866            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3867        let sort_completions = provider.sort_completions();
 3868
 3869        let id = post_inc(&mut self.next_completion_id);
 3870        let task = cx.spawn_in(window, |editor, mut cx| {
 3871            async move {
 3872                editor.update(&mut cx, |this, _| {
 3873                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3874                })?;
 3875                let completions = completions.await.log_err();
 3876                let menu = if let Some(completions) = completions {
 3877                    let mut menu = CompletionsMenu::new(
 3878                        id,
 3879                        sort_completions,
 3880                        show_completion_documentation,
 3881                        position,
 3882                        buffer.clone(),
 3883                        completions.into(),
 3884                    );
 3885
 3886                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3887                        .await;
 3888
 3889                    menu.visible().then_some(menu)
 3890                } else {
 3891                    None
 3892                };
 3893
 3894                editor.update_in(&mut cx, |editor, window, cx| {
 3895                    match editor.context_menu.borrow().as_ref() {
 3896                        None => {}
 3897                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3898                            if prev_menu.id > id {
 3899                                return;
 3900                            }
 3901                        }
 3902                        _ => return,
 3903                    }
 3904
 3905                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3906                        let mut menu = menu.unwrap();
 3907                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3908
 3909                        *editor.context_menu.borrow_mut() =
 3910                            Some(CodeContextMenu::Completions(menu));
 3911
 3912                        if editor.show_edit_predictions_in_menu(cx) {
 3913                            editor.update_visible_inline_completion(window, cx);
 3914                        } else {
 3915                            editor.discard_inline_completion(false, cx);
 3916                        }
 3917
 3918                        cx.notify();
 3919                    } else if editor.completion_tasks.len() <= 1 {
 3920                        // If there are no more completion tasks and the last menu was
 3921                        // empty, we should hide it.
 3922                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3923                        // If it was already hidden and we don't show inline
 3924                        // completions in the menu, we should also show the
 3925                        // inline-completion when available.
 3926                        if was_hidden && editor.show_edit_predictions_in_menu(cx) {
 3927                            editor.update_visible_inline_completion(window, cx);
 3928                        }
 3929                    }
 3930                })?;
 3931
 3932                Ok::<_, anyhow::Error>(())
 3933            }
 3934            .log_err()
 3935        });
 3936
 3937        self.completion_tasks.push((id, task));
 3938    }
 3939
 3940    pub fn confirm_completion(
 3941        &mut self,
 3942        action: &ConfirmCompletion,
 3943        window: &mut Window,
 3944        cx: &mut Context<Self>,
 3945    ) -> Option<Task<Result<()>>> {
 3946        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3947    }
 3948
 3949    pub fn compose_completion(
 3950        &mut self,
 3951        action: &ComposeCompletion,
 3952        window: &mut Window,
 3953        cx: &mut Context<Self>,
 3954    ) -> Option<Task<Result<()>>> {
 3955        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3956    }
 3957
 3958    fn do_completion(
 3959        &mut self,
 3960        item_ix: Option<usize>,
 3961        intent: CompletionIntent,
 3962        window: &mut Window,
 3963        cx: &mut Context<Editor>,
 3964    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3965        use language::ToOffset as _;
 3966
 3967        let completions_menu =
 3968            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3969                menu
 3970            } else {
 3971                return None;
 3972            };
 3973
 3974        let entries = completions_menu.entries.borrow();
 3975        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3976        if self.show_edit_predictions_in_menu(cx) {
 3977            self.discard_inline_completion(true, cx);
 3978        }
 3979        let candidate_id = mat.candidate_id;
 3980        drop(entries);
 3981
 3982        let buffer_handle = completions_menu.buffer;
 3983        let completion = completions_menu
 3984            .completions
 3985            .borrow()
 3986            .get(candidate_id)?
 3987            .clone();
 3988        cx.stop_propagation();
 3989
 3990        let snippet;
 3991        let text;
 3992
 3993        if completion.is_snippet() {
 3994            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3995            text = snippet.as_ref().unwrap().text.clone();
 3996        } else {
 3997            snippet = None;
 3998            text = completion.new_text.clone();
 3999        };
 4000        let selections = self.selections.all::<usize>(cx);
 4001        let buffer = buffer_handle.read(cx);
 4002        let old_range = completion.old_range.to_offset(buffer);
 4003        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4004
 4005        let newest_selection = self.selections.newest_anchor();
 4006        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4007            return None;
 4008        }
 4009
 4010        let lookbehind = newest_selection
 4011            .start
 4012            .text_anchor
 4013            .to_offset(buffer)
 4014            .saturating_sub(old_range.start);
 4015        let lookahead = old_range
 4016            .end
 4017            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4018        let mut common_prefix_len = old_text
 4019            .bytes()
 4020            .zip(text.bytes())
 4021            .take_while(|(a, b)| a == b)
 4022            .count();
 4023
 4024        let snapshot = self.buffer.read(cx).snapshot(cx);
 4025        let mut range_to_replace: Option<Range<isize>> = None;
 4026        let mut ranges = Vec::new();
 4027        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4028        for selection in &selections {
 4029            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4030                let start = selection.start.saturating_sub(lookbehind);
 4031                let end = selection.end + lookahead;
 4032                if selection.id == newest_selection.id {
 4033                    range_to_replace = Some(
 4034                        ((start + common_prefix_len) as isize - selection.start as isize)
 4035                            ..(end as isize - selection.start as isize),
 4036                    );
 4037                }
 4038                ranges.push(start + common_prefix_len..end);
 4039            } else {
 4040                common_prefix_len = 0;
 4041                ranges.clear();
 4042                ranges.extend(selections.iter().map(|s| {
 4043                    if s.id == newest_selection.id {
 4044                        range_to_replace = Some(
 4045                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4046                                - selection.start as isize
 4047                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4048                                    - selection.start as isize,
 4049                        );
 4050                        old_range.clone()
 4051                    } else {
 4052                        s.start..s.end
 4053                    }
 4054                }));
 4055                break;
 4056            }
 4057            if !self.linked_edit_ranges.is_empty() {
 4058                let start_anchor = snapshot.anchor_before(selection.head());
 4059                let end_anchor = snapshot.anchor_after(selection.tail());
 4060                if let Some(ranges) = self
 4061                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4062                {
 4063                    for (buffer, edits) in ranges {
 4064                        linked_edits.entry(buffer.clone()).or_default().extend(
 4065                            edits
 4066                                .into_iter()
 4067                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4068                        );
 4069                    }
 4070                }
 4071            }
 4072        }
 4073        let text = &text[common_prefix_len..];
 4074
 4075        cx.emit(EditorEvent::InputHandled {
 4076            utf16_range_to_replace: range_to_replace,
 4077            text: text.into(),
 4078        });
 4079
 4080        self.transact(window, cx, |this, window, cx| {
 4081            if let Some(mut snippet) = snippet {
 4082                snippet.text = text.to_string();
 4083                for tabstop in snippet
 4084                    .tabstops
 4085                    .iter_mut()
 4086                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4087                {
 4088                    tabstop.start -= common_prefix_len as isize;
 4089                    tabstop.end -= common_prefix_len as isize;
 4090                }
 4091
 4092                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4093            } else {
 4094                this.buffer.update(cx, |buffer, cx| {
 4095                    buffer.edit(
 4096                        ranges.iter().map(|range| (range.clone(), text)),
 4097                        this.autoindent_mode.clone(),
 4098                        cx,
 4099                    );
 4100                });
 4101            }
 4102            for (buffer, edits) in linked_edits {
 4103                buffer.update(cx, |buffer, cx| {
 4104                    let snapshot = buffer.snapshot();
 4105                    let edits = edits
 4106                        .into_iter()
 4107                        .map(|(range, text)| {
 4108                            use text::ToPoint as TP;
 4109                            let end_point = TP::to_point(&range.end, &snapshot);
 4110                            let start_point = TP::to_point(&range.start, &snapshot);
 4111                            (start_point..end_point, text)
 4112                        })
 4113                        .sorted_by_key(|(range, _)| range.start)
 4114                        .collect::<Vec<_>>();
 4115                    buffer.edit(edits, None, cx);
 4116                })
 4117            }
 4118
 4119            this.refresh_inline_completion(true, false, window, cx);
 4120        });
 4121
 4122        let show_new_completions_on_confirm = completion
 4123            .confirm
 4124            .as_ref()
 4125            .map_or(false, |confirm| confirm(intent, window, cx));
 4126        if show_new_completions_on_confirm {
 4127            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4128        }
 4129
 4130        let provider = self.completion_provider.as_ref()?;
 4131        drop(completion);
 4132        let apply_edits = provider.apply_additional_edits_for_completion(
 4133            buffer_handle,
 4134            completions_menu.completions.clone(),
 4135            candidate_id,
 4136            true,
 4137            cx,
 4138        );
 4139
 4140        let editor_settings = EditorSettings::get_global(cx);
 4141        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4142            // After the code completion is finished, users often want to know what signatures are needed.
 4143            // so we should automatically call signature_help
 4144            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4145        }
 4146
 4147        Some(cx.foreground_executor().spawn(async move {
 4148            apply_edits.await?;
 4149            Ok(())
 4150        }))
 4151    }
 4152
 4153    pub fn toggle_code_actions(
 4154        &mut self,
 4155        action: &ToggleCodeActions,
 4156        window: &mut Window,
 4157        cx: &mut Context<Self>,
 4158    ) {
 4159        let mut context_menu = self.context_menu.borrow_mut();
 4160        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4161            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4162                // Toggle if we're selecting the same one
 4163                *context_menu = None;
 4164                cx.notify();
 4165                return;
 4166            } else {
 4167                // Otherwise, clear it and start a new one
 4168                *context_menu = None;
 4169                cx.notify();
 4170            }
 4171        }
 4172        drop(context_menu);
 4173        let snapshot = self.snapshot(window, cx);
 4174        let deployed_from_indicator = action.deployed_from_indicator;
 4175        let mut task = self.code_actions_task.take();
 4176        let action = action.clone();
 4177        cx.spawn_in(window, |editor, mut cx| async move {
 4178            while let Some(prev_task) = task {
 4179                prev_task.await.log_err();
 4180                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4181            }
 4182
 4183            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4184                if editor.focus_handle.is_focused(window) {
 4185                    let multibuffer_point = action
 4186                        .deployed_from_indicator
 4187                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4188                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4189                    let (buffer, buffer_row) = snapshot
 4190                        .buffer_snapshot
 4191                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4192                        .and_then(|(buffer_snapshot, range)| {
 4193                            editor
 4194                                .buffer
 4195                                .read(cx)
 4196                                .buffer(buffer_snapshot.remote_id())
 4197                                .map(|buffer| (buffer, range.start.row))
 4198                        })?;
 4199                    let (_, code_actions) = editor
 4200                        .available_code_actions
 4201                        .clone()
 4202                        .and_then(|(location, code_actions)| {
 4203                            let snapshot = location.buffer.read(cx).snapshot();
 4204                            let point_range = location.range.to_point(&snapshot);
 4205                            let point_range = point_range.start.row..=point_range.end.row;
 4206                            if point_range.contains(&buffer_row) {
 4207                                Some((location, code_actions))
 4208                            } else {
 4209                                None
 4210                            }
 4211                        })
 4212                        .unzip();
 4213                    let buffer_id = buffer.read(cx).remote_id();
 4214                    let tasks = editor
 4215                        .tasks
 4216                        .get(&(buffer_id, buffer_row))
 4217                        .map(|t| Arc::new(t.to_owned()));
 4218                    if tasks.is_none() && code_actions.is_none() {
 4219                        return None;
 4220                    }
 4221
 4222                    editor.completion_tasks.clear();
 4223                    editor.discard_inline_completion(false, cx);
 4224                    let task_context =
 4225                        tasks
 4226                            .as_ref()
 4227                            .zip(editor.project.clone())
 4228                            .map(|(tasks, project)| {
 4229                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4230                            });
 4231
 4232                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4233                        let task_context = match task_context {
 4234                            Some(task_context) => task_context.await,
 4235                            None => None,
 4236                        };
 4237                        let resolved_tasks =
 4238                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4239                                Rc::new(ResolvedTasks {
 4240                                    templates: tasks.resolve(&task_context).collect(),
 4241                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4242                                        multibuffer_point.row,
 4243                                        tasks.column,
 4244                                    )),
 4245                                })
 4246                            });
 4247                        let spawn_straight_away = resolved_tasks
 4248                            .as_ref()
 4249                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4250                            && code_actions
 4251                                .as_ref()
 4252                                .map_or(true, |actions| actions.is_empty());
 4253                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4254                            *editor.context_menu.borrow_mut() =
 4255                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4256                                    buffer,
 4257                                    actions: CodeActionContents {
 4258                                        tasks: resolved_tasks,
 4259                                        actions: code_actions,
 4260                                    },
 4261                                    selected_item: Default::default(),
 4262                                    scroll_handle: UniformListScrollHandle::default(),
 4263                                    deployed_from_indicator,
 4264                                }));
 4265                            if spawn_straight_away {
 4266                                if let Some(task) = editor.confirm_code_action(
 4267                                    &ConfirmCodeAction { item_ix: Some(0) },
 4268                                    window,
 4269                                    cx,
 4270                                ) {
 4271                                    cx.notify();
 4272                                    return task;
 4273                                }
 4274                            }
 4275                            cx.notify();
 4276                            Task::ready(Ok(()))
 4277                        }) {
 4278                            task.await
 4279                        } else {
 4280                            Ok(())
 4281                        }
 4282                    }))
 4283                } else {
 4284                    Some(Task::ready(Ok(())))
 4285                }
 4286            })?;
 4287            if let Some(task) = spawned_test_task {
 4288                task.await?;
 4289            }
 4290
 4291            Ok::<_, anyhow::Error>(())
 4292        })
 4293        .detach_and_log_err(cx);
 4294    }
 4295
 4296    pub fn confirm_code_action(
 4297        &mut self,
 4298        action: &ConfirmCodeAction,
 4299        window: &mut Window,
 4300        cx: &mut Context<Self>,
 4301    ) -> Option<Task<Result<()>>> {
 4302        let actions_menu =
 4303            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4304                menu
 4305            } else {
 4306                return None;
 4307            };
 4308        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4309        let action = actions_menu.actions.get(action_ix)?;
 4310        let title = action.label();
 4311        let buffer = actions_menu.buffer;
 4312        let workspace = self.workspace()?;
 4313
 4314        match action {
 4315            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4316                workspace.update(cx, |workspace, cx| {
 4317                    workspace::tasks::schedule_resolved_task(
 4318                        workspace,
 4319                        task_source_kind,
 4320                        resolved_task,
 4321                        false,
 4322                        cx,
 4323                    );
 4324
 4325                    Some(Task::ready(Ok(())))
 4326                })
 4327            }
 4328            CodeActionsItem::CodeAction {
 4329                excerpt_id,
 4330                action,
 4331                provider,
 4332            } => {
 4333                let apply_code_action =
 4334                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4335                let workspace = workspace.downgrade();
 4336                Some(cx.spawn_in(window, |editor, cx| async move {
 4337                    let project_transaction = apply_code_action.await?;
 4338                    Self::open_project_transaction(
 4339                        &editor,
 4340                        workspace,
 4341                        project_transaction,
 4342                        title,
 4343                        cx,
 4344                    )
 4345                    .await
 4346                }))
 4347            }
 4348        }
 4349    }
 4350
 4351    pub async fn open_project_transaction(
 4352        this: &WeakEntity<Editor>,
 4353        workspace: WeakEntity<Workspace>,
 4354        transaction: ProjectTransaction,
 4355        title: String,
 4356        mut cx: AsyncWindowContext,
 4357    ) -> Result<()> {
 4358        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4359        cx.update(|_, cx| {
 4360            entries.sort_unstable_by_key(|(buffer, _)| {
 4361                buffer.read(cx).file().map(|f| f.path().clone())
 4362            });
 4363        })?;
 4364
 4365        // If the project transaction's edits are all contained within this editor, then
 4366        // avoid opening a new editor to display them.
 4367
 4368        if let Some((buffer, transaction)) = entries.first() {
 4369            if entries.len() == 1 {
 4370                let excerpt = this.update(&mut cx, |editor, cx| {
 4371                    editor
 4372                        .buffer()
 4373                        .read(cx)
 4374                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4375                })?;
 4376                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4377                    if excerpted_buffer == *buffer {
 4378                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4379                            let excerpt_range = excerpt_range.to_offset(buffer);
 4380                            buffer
 4381                                .edited_ranges_for_transaction::<usize>(transaction)
 4382                                .all(|range| {
 4383                                    excerpt_range.start <= range.start
 4384                                        && excerpt_range.end >= range.end
 4385                                })
 4386                        })?;
 4387
 4388                        if all_edits_within_excerpt {
 4389                            return Ok(());
 4390                        }
 4391                    }
 4392                }
 4393            }
 4394        } else {
 4395            return Ok(());
 4396        }
 4397
 4398        let mut ranges_to_highlight = Vec::new();
 4399        let excerpt_buffer = cx.new(|cx| {
 4400            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4401            for (buffer_handle, transaction) in &entries {
 4402                let buffer = buffer_handle.read(cx);
 4403                ranges_to_highlight.extend(
 4404                    multibuffer.push_excerpts_with_context_lines(
 4405                        buffer_handle.clone(),
 4406                        buffer
 4407                            .edited_ranges_for_transaction::<usize>(transaction)
 4408                            .collect(),
 4409                        DEFAULT_MULTIBUFFER_CONTEXT,
 4410                        cx,
 4411                    ),
 4412                );
 4413            }
 4414            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4415            multibuffer
 4416        })?;
 4417
 4418        workspace.update_in(&mut cx, |workspace, window, cx| {
 4419            let project = workspace.project().clone();
 4420            let editor = cx
 4421                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4422            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4423            editor.update(cx, |editor, cx| {
 4424                editor.highlight_background::<Self>(
 4425                    &ranges_to_highlight,
 4426                    |theme| theme.editor_highlighted_line_background,
 4427                    cx,
 4428                );
 4429            });
 4430        })?;
 4431
 4432        Ok(())
 4433    }
 4434
 4435    pub fn clear_code_action_providers(&mut self) {
 4436        self.code_action_providers.clear();
 4437        self.available_code_actions.take();
 4438    }
 4439
 4440    pub fn add_code_action_provider(
 4441        &mut self,
 4442        provider: Rc<dyn CodeActionProvider>,
 4443        window: &mut Window,
 4444        cx: &mut Context<Self>,
 4445    ) {
 4446        if self
 4447            .code_action_providers
 4448            .iter()
 4449            .any(|existing_provider| existing_provider.id() == provider.id())
 4450        {
 4451            return;
 4452        }
 4453
 4454        self.code_action_providers.push(provider);
 4455        self.refresh_code_actions(window, cx);
 4456    }
 4457
 4458    pub fn remove_code_action_provider(
 4459        &mut self,
 4460        id: Arc<str>,
 4461        window: &mut Window,
 4462        cx: &mut Context<Self>,
 4463    ) {
 4464        self.code_action_providers
 4465            .retain(|provider| provider.id() != id);
 4466        self.refresh_code_actions(window, cx);
 4467    }
 4468
 4469    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4470        let buffer = self.buffer.read(cx);
 4471        let newest_selection = self.selections.newest_anchor().clone();
 4472        if newest_selection.head().diff_base_anchor.is_some() {
 4473            return None;
 4474        }
 4475        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4476        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4477        if start_buffer != end_buffer {
 4478            return None;
 4479        }
 4480
 4481        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4482            cx.background_executor()
 4483                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4484                .await;
 4485
 4486            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4487                let providers = this.code_action_providers.clone();
 4488                let tasks = this
 4489                    .code_action_providers
 4490                    .iter()
 4491                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4492                    .collect::<Vec<_>>();
 4493                (providers, tasks)
 4494            })?;
 4495
 4496            let mut actions = Vec::new();
 4497            for (provider, provider_actions) in
 4498                providers.into_iter().zip(future::join_all(tasks).await)
 4499            {
 4500                if let Some(provider_actions) = provider_actions.log_err() {
 4501                    actions.extend(provider_actions.into_iter().map(|action| {
 4502                        AvailableCodeAction {
 4503                            excerpt_id: newest_selection.start.excerpt_id,
 4504                            action,
 4505                            provider: provider.clone(),
 4506                        }
 4507                    }));
 4508                }
 4509            }
 4510
 4511            this.update(&mut cx, |this, cx| {
 4512                this.available_code_actions = if actions.is_empty() {
 4513                    None
 4514                } else {
 4515                    Some((
 4516                        Location {
 4517                            buffer: start_buffer,
 4518                            range: start..end,
 4519                        },
 4520                        actions.into(),
 4521                    ))
 4522                };
 4523                cx.notify();
 4524            })
 4525        }));
 4526        None
 4527    }
 4528
 4529    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4530        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4531            self.show_git_blame_inline = false;
 4532
 4533            self.show_git_blame_inline_delay_task =
 4534                Some(cx.spawn_in(window, |this, mut cx| async move {
 4535                    cx.background_executor().timer(delay).await;
 4536
 4537                    this.update(&mut cx, |this, cx| {
 4538                        this.show_git_blame_inline = true;
 4539                        cx.notify();
 4540                    })
 4541                    .log_err();
 4542                }));
 4543        }
 4544    }
 4545
 4546    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4547        if self.pending_rename.is_some() {
 4548            return None;
 4549        }
 4550
 4551        let provider = self.semantics_provider.clone()?;
 4552        let buffer = self.buffer.read(cx);
 4553        let newest_selection = self.selections.newest_anchor().clone();
 4554        let cursor_position = newest_selection.head();
 4555        let (cursor_buffer, cursor_buffer_position) =
 4556            buffer.text_anchor_for_position(cursor_position, cx)?;
 4557        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4558        if cursor_buffer != tail_buffer {
 4559            return None;
 4560        }
 4561        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4562        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4563            cx.background_executor()
 4564                .timer(Duration::from_millis(debounce))
 4565                .await;
 4566
 4567            let highlights = if let Some(highlights) = cx
 4568                .update(|cx| {
 4569                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4570                })
 4571                .ok()
 4572                .flatten()
 4573            {
 4574                highlights.await.log_err()
 4575            } else {
 4576                None
 4577            };
 4578
 4579            if let Some(highlights) = highlights {
 4580                this.update(&mut cx, |this, cx| {
 4581                    if this.pending_rename.is_some() {
 4582                        return;
 4583                    }
 4584
 4585                    let buffer_id = cursor_position.buffer_id;
 4586                    let buffer = this.buffer.read(cx);
 4587                    if !buffer
 4588                        .text_anchor_for_position(cursor_position, cx)
 4589                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4590                    {
 4591                        return;
 4592                    }
 4593
 4594                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4595                    let mut write_ranges = Vec::new();
 4596                    let mut read_ranges = Vec::new();
 4597                    for highlight in highlights {
 4598                        for (excerpt_id, excerpt_range) in
 4599                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4600                        {
 4601                            let start = highlight
 4602                                .range
 4603                                .start
 4604                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4605                            let end = highlight
 4606                                .range
 4607                                .end
 4608                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4609                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4610                                continue;
 4611                            }
 4612
 4613                            let range = Anchor {
 4614                                buffer_id,
 4615                                excerpt_id,
 4616                                text_anchor: start,
 4617                                diff_base_anchor: None,
 4618                            }..Anchor {
 4619                                buffer_id,
 4620                                excerpt_id,
 4621                                text_anchor: end,
 4622                                diff_base_anchor: None,
 4623                            };
 4624                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4625                                write_ranges.push(range);
 4626                            } else {
 4627                                read_ranges.push(range);
 4628                            }
 4629                        }
 4630                    }
 4631
 4632                    this.highlight_background::<DocumentHighlightRead>(
 4633                        &read_ranges,
 4634                        |theme| theme.editor_document_highlight_read_background,
 4635                        cx,
 4636                    );
 4637                    this.highlight_background::<DocumentHighlightWrite>(
 4638                        &write_ranges,
 4639                        |theme| theme.editor_document_highlight_write_background,
 4640                        cx,
 4641                    );
 4642                    cx.notify();
 4643                })
 4644                .log_err();
 4645            }
 4646        }));
 4647        None
 4648    }
 4649
 4650    pub fn refresh_inline_completion(
 4651        &mut self,
 4652        debounce: bool,
 4653        user_requested: bool,
 4654        window: &mut Window,
 4655        cx: &mut Context<Self>,
 4656    ) -> Option<()> {
 4657        let provider = self.edit_prediction_provider()?;
 4658        let cursor = self.selections.newest_anchor().head();
 4659        let (buffer, cursor_buffer_position) =
 4660            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4661
 4662        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4663            self.discard_inline_completion(false, cx);
 4664            return None;
 4665        }
 4666
 4667        if !user_requested
 4668            && (!self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4669                || !self.is_focused(window)
 4670                || buffer.read(cx).is_empty())
 4671        {
 4672            self.discard_inline_completion(false, cx);
 4673            return None;
 4674        }
 4675
 4676        self.update_visible_inline_completion(window, cx);
 4677        provider.refresh(
 4678            self.project.clone(),
 4679            buffer,
 4680            cursor_buffer_position,
 4681            debounce,
 4682            cx,
 4683        );
 4684        Some(())
 4685    }
 4686
 4687    pub fn should_show_inline_completions(&self, cx: &App) -> bool {
 4688        let cursor = self.selections.newest_anchor().head();
 4689        if let Some((buffer, cursor_position)) =
 4690            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4691        {
 4692            self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
 4693        } else {
 4694            false
 4695        }
 4696    }
 4697
 4698    fn edit_prediction_requires_modifier(&self, cx: &App) -> bool {
 4699        let cursor = self.selections.newest_anchor().head();
 4700
 4701        self.buffer
 4702            .read(cx)
 4703            .text_anchor_for_position(cursor, cx)
 4704            .map(|(buffer, _)| {
 4705                all_language_settings(buffer.read(cx).file(), cx).inline_completions_preview_mode()
 4706                    == InlineCompletionPreviewMode::WhenHoldingModifier
 4707            })
 4708            .unwrap_or(false)
 4709    }
 4710
 4711    fn should_show_inline_completions_in_buffer(
 4712        &self,
 4713        buffer: &Entity<Buffer>,
 4714        buffer_position: language::Anchor,
 4715        cx: &App,
 4716    ) -> bool {
 4717        if !self.snippet_stack.is_empty() {
 4718            return false;
 4719        }
 4720
 4721        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 4722            return false;
 4723        }
 4724
 4725        if let Some(show_inline_completions) = self.show_inline_completions_override {
 4726            show_inline_completions
 4727        } else {
 4728            let buffer = buffer.read(cx);
 4729            self.mode == EditorMode::Full
 4730                && language_settings(
 4731                    buffer.language_at(buffer_position).map(|l| l.name()),
 4732                    buffer.file(),
 4733                    cx,
 4734                )
 4735                .show_edit_predictions
 4736        }
 4737    }
 4738
 4739    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4740        let cursor = self.selections.newest_anchor().head();
 4741        if let Some((buffer, cursor_position)) =
 4742            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4743        {
 4744            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4745        } else {
 4746            false
 4747        }
 4748    }
 4749
 4750    fn inline_completions_enabled_in_buffer(
 4751        &self,
 4752        buffer: &Entity<Buffer>,
 4753        buffer_position: language::Anchor,
 4754        cx: &App,
 4755    ) -> bool {
 4756        maybe!({
 4757            let provider = self.edit_prediction_provider()?;
 4758            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4759                return Some(false);
 4760            }
 4761            let buffer = buffer.read(cx);
 4762            let Some(file) = buffer.file() else {
 4763                return Some(true);
 4764            };
 4765            let settings = all_language_settings(Some(file), cx);
 4766            Some(settings.inline_completions_enabled_for_path(file.path()))
 4767        })
 4768        .unwrap_or(false)
 4769    }
 4770
 4771    fn cycle_inline_completion(
 4772        &mut self,
 4773        direction: Direction,
 4774        window: &mut Window,
 4775        cx: &mut Context<Self>,
 4776    ) -> Option<()> {
 4777        let provider = self.edit_prediction_provider()?;
 4778        let cursor = self.selections.newest_anchor().head();
 4779        let (buffer, cursor_buffer_position) =
 4780            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4781        if self.inline_completions_hidden_for_vim_mode
 4782            || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4783        {
 4784            return None;
 4785        }
 4786
 4787        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4788        self.update_visible_inline_completion(window, cx);
 4789
 4790        Some(())
 4791    }
 4792
 4793    pub fn show_inline_completion(
 4794        &mut self,
 4795        _: &ShowEditPrediction,
 4796        window: &mut Window,
 4797        cx: &mut Context<Self>,
 4798    ) {
 4799        if !self.has_active_inline_completion() {
 4800            self.refresh_inline_completion(false, true, window, cx);
 4801            return;
 4802        }
 4803
 4804        self.update_visible_inline_completion(window, cx);
 4805    }
 4806
 4807    pub fn display_cursor_names(
 4808        &mut self,
 4809        _: &DisplayCursorNames,
 4810        window: &mut Window,
 4811        cx: &mut Context<Self>,
 4812    ) {
 4813        self.show_cursor_names(window, cx);
 4814    }
 4815
 4816    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4817        self.show_cursor_names = true;
 4818        cx.notify();
 4819        cx.spawn_in(window, |this, mut cx| async move {
 4820            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4821            this.update(&mut cx, |this, cx| {
 4822                this.show_cursor_names = false;
 4823                cx.notify()
 4824            })
 4825            .ok()
 4826        })
 4827        .detach();
 4828    }
 4829
 4830    pub fn next_edit_prediction(
 4831        &mut self,
 4832        _: &NextEditPrediction,
 4833        window: &mut Window,
 4834        cx: &mut Context<Self>,
 4835    ) {
 4836        if self.has_active_inline_completion() {
 4837            self.cycle_inline_completion(Direction::Next, window, cx);
 4838        } else {
 4839            let is_copilot_disabled = self
 4840                .refresh_inline_completion(false, true, window, cx)
 4841                .is_none();
 4842            if is_copilot_disabled {
 4843                cx.propagate();
 4844            }
 4845        }
 4846    }
 4847
 4848    pub fn previous_edit_prediction(
 4849        &mut self,
 4850        _: &PreviousEditPrediction,
 4851        window: &mut Window,
 4852        cx: &mut Context<Self>,
 4853    ) {
 4854        if self.has_active_inline_completion() {
 4855            self.cycle_inline_completion(Direction::Prev, window, cx);
 4856        } else {
 4857            let is_copilot_disabled = self
 4858                .refresh_inline_completion(false, true, window, cx)
 4859                .is_none();
 4860            if is_copilot_disabled {
 4861                cx.propagate();
 4862            }
 4863        }
 4864    }
 4865
 4866    pub fn accept_edit_prediction(
 4867        &mut self,
 4868        _: &AcceptEditPrediction,
 4869        window: &mut Window,
 4870        cx: &mut Context<Self>,
 4871    ) {
 4872        let buffer = self.buffer.read(cx);
 4873        let snapshot = buffer.snapshot(cx);
 4874        let selection = self.selections.newest_adjusted(cx);
 4875        let cursor = selection.head();
 4876        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4877        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4878        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4879        {
 4880            if cursor.column < suggested_indent.len
 4881                && cursor.column <= current_indent.len
 4882                && current_indent.len <= suggested_indent.len
 4883            {
 4884                self.tab(&Default::default(), window, cx);
 4885                return;
 4886            }
 4887        }
 4888
 4889        if self.show_edit_predictions_in_menu(cx) {
 4890            self.hide_context_menu(window, cx);
 4891        }
 4892
 4893        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4894            return;
 4895        };
 4896
 4897        self.report_inline_completion_event(
 4898            active_inline_completion.completion_id.clone(),
 4899            true,
 4900            cx,
 4901        );
 4902
 4903        match &active_inline_completion.completion {
 4904            InlineCompletion::Move { target, .. } => {
 4905                let target = *target;
 4906                // Note that this is also done in vim's handler of the Tab action.
 4907                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4908                    selections.select_anchor_ranges([target..target]);
 4909                });
 4910            }
 4911            InlineCompletion::Edit { edits, .. } => {
 4912                if let Some(provider) = self.edit_prediction_provider() {
 4913                    provider.accept(cx);
 4914                }
 4915
 4916                let snapshot = self.buffer.read(cx).snapshot(cx);
 4917                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4918
 4919                self.buffer.update(cx, |buffer, cx| {
 4920                    buffer.edit(edits.iter().cloned(), None, cx)
 4921                });
 4922
 4923                self.change_selections(None, window, cx, |s| {
 4924                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4925                });
 4926
 4927                self.update_visible_inline_completion(window, cx);
 4928                if self.active_inline_completion.is_none() {
 4929                    self.refresh_inline_completion(true, true, window, cx);
 4930                }
 4931
 4932                cx.notify();
 4933            }
 4934        }
 4935    }
 4936
 4937    pub fn accept_partial_inline_completion(
 4938        &mut self,
 4939        _: &AcceptPartialEditPrediction,
 4940        window: &mut Window,
 4941        cx: &mut Context<Self>,
 4942    ) {
 4943        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4944            return;
 4945        };
 4946        if self.selections.count() != 1 {
 4947            return;
 4948        }
 4949
 4950        self.report_inline_completion_event(
 4951            active_inline_completion.completion_id.clone(),
 4952            true,
 4953            cx,
 4954        );
 4955
 4956        match &active_inline_completion.completion {
 4957            InlineCompletion::Move { target, .. } => {
 4958                let target = *target;
 4959                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4960                    selections.select_anchor_ranges([target..target]);
 4961                });
 4962            }
 4963            InlineCompletion::Edit { edits, .. } => {
 4964                // Find an insertion that starts at the cursor position.
 4965                let snapshot = self.buffer.read(cx).snapshot(cx);
 4966                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4967                let insertion = edits.iter().find_map(|(range, text)| {
 4968                    let range = range.to_offset(&snapshot);
 4969                    if range.is_empty() && range.start == cursor_offset {
 4970                        Some(text)
 4971                    } else {
 4972                        None
 4973                    }
 4974                });
 4975
 4976                if let Some(text) = insertion {
 4977                    let mut partial_completion = text
 4978                        .chars()
 4979                        .by_ref()
 4980                        .take_while(|c| c.is_alphabetic())
 4981                        .collect::<String>();
 4982                    if partial_completion.is_empty() {
 4983                        partial_completion = text
 4984                            .chars()
 4985                            .by_ref()
 4986                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4987                            .collect::<String>();
 4988                    }
 4989
 4990                    cx.emit(EditorEvent::InputHandled {
 4991                        utf16_range_to_replace: None,
 4992                        text: partial_completion.clone().into(),
 4993                    });
 4994
 4995                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4996
 4997                    self.refresh_inline_completion(true, true, window, cx);
 4998                    cx.notify();
 4999                } else {
 5000                    self.accept_edit_prediction(&Default::default(), window, cx);
 5001                }
 5002            }
 5003        }
 5004    }
 5005
 5006    fn discard_inline_completion(
 5007        &mut self,
 5008        should_report_inline_completion_event: bool,
 5009        cx: &mut Context<Self>,
 5010    ) -> bool {
 5011        if should_report_inline_completion_event {
 5012            let completion_id = self
 5013                .active_inline_completion
 5014                .as_ref()
 5015                .and_then(|active_completion| active_completion.completion_id.clone());
 5016
 5017            self.report_inline_completion_event(completion_id, false, cx);
 5018        }
 5019
 5020        if let Some(provider) = self.edit_prediction_provider() {
 5021            provider.discard(cx);
 5022        }
 5023
 5024        self.take_active_inline_completion(cx)
 5025    }
 5026
 5027    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5028        let Some(provider) = self.edit_prediction_provider() else {
 5029            return;
 5030        };
 5031
 5032        let Some((_, buffer, _)) = self
 5033            .buffer
 5034            .read(cx)
 5035            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5036        else {
 5037            return;
 5038        };
 5039
 5040        let extension = buffer
 5041            .read(cx)
 5042            .file()
 5043            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5044
 5045        let event_type = match accepted {
 5046            true => "Edit Prediction Accepted",
 5047            false => "Edit Prediction Discarded",
 5048        };
 5049        telemetry::event!(
 5050            event_type,
 5051            provider = provider.name(),
 5052            prediction_id = id,
 5053            suggestion_accepted = accepted,
 5054            file_extension = extension,
 5055        );
 5056    }
 5057
 5058    pub fn has_active_inline_completion(&self) -> bool {
 5059        self.active_inline_completion.is_some()
 5060    }
 5061
 5062    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5063        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5064            return false;
 5065        };
 5066
 5067        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5068        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5069        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5070        true
 5071    }
 5072
 5073    /// Returns true when we're displaying the inline completion popover below the cursor
 5074    /// like we are not previewing and the LSP autocomplete menu is visible
 5075    /// or we are in `when_holding_modifier` mode.
 5076    pub fn inline_completion_visible_in_cursor_popover(
 5077        &self,
 5078        has_completion: bool,
 5079        cx: &App,
 5080    ) -> bool {
 5081        if self.previewing_inline_completion
 5082            || !self.show_edit_predictions_in_menu(cx)
 5083            || !self.should_show_inline_completions(cx)
 5084        {
 5085            return false;
 5086        }
 5087
 5088        if self.has_visible_completions_menu() {
 5089            return true;
 5090        }
 5091
 5092        has_completion && self.edit_prediction_requires_modifier(cx)
 5093    }
 5094
 5095    fn update_inline_completion_preview(
 5096        &mut self,
 5097        modifiers: &Modifiers,
 5098        window: &mut Window,
 5099        cx: &mut Context<Self>,
 5100    ) {
 5101        if !self.show_edit_predictions_in_menu(cx) {
 5102            return;
 5103        }
 5104
 5105        self.previewing_inline_completion = modifiers.alt;
 5106        self.update_visible_inline_completion(window, cx);
 5107        cx.notify();
 5108    }
 5109
 5110    fn update_visible_inline_completion(
 5111        &mut self,
 5112        _window: &mut Window,
 5113        cx: &mut Context<Self>,
 5114    ) -> Option<()> {
 5115        let selection = self.selections.newest_anchor();
 5116        let cursor = selection.head();
 5117        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5118        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5119        let excerpt_id = cursor.excerpt_id;
 5120
 5121        let show_in_menu = self.show_edit_predictions_in_menu(cx);
 5122        let completions_menu_has_precedence = !show_in_menu
 5123            && (self.context_menu.borrow().is_some()
 5124                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5125        if completions_menu_has_precedence
 5126            || !offset_selection.is_empty()
 5127            || self
 5128                .active_inline_completion
 5129                .as_ref()
 5130                .map_or(false, |completion| {
 5131                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5132                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5133                    !invalidation_range.contains(&offset_selection.head())
 5134                })
 5135        {
 5136            self.discard_inline_completion(false, cx);
 5137            return None;
 5138        }
 5139
 5140        self.take_active_inline_completion(cx);
 5141        let provider = self.edit_prediction_provider()?;
 5142
 5143        let (buffer, cursor_buffer_position) =
 5144            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5145
 5146        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5147        let edits = inline_completion
 5148            .edits
 5149            .into_iter()
 5150            .flat_map(|(range, new_text)| {
 5151                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5152                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5153                Some((start..end, new_text))
 5154            })
 5155            .collect::<Vec<_>>();
 5156        if edits.is_empty() {
 5157            return None;
 5158        }
 5159
 5160        let first_edit_start = edits.first().unwrap().0.start;
 5161        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5162        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5163
 5164        let last_edit_end = edits.last().unwrap().0.end;
 5165        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5166        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5167
 5168        let cursor_row = cursor.to_point(&multibuffer).row;
 5169
 5170        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5171
 5172        let mut inlay_ids = Vec::new();
 5173        let invalidation_row_range;
 5174        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5175            Some(cursor_row..edit_end_row)
 5176        } else if cursor_row > edit_end_row {
 5177            Some(edit_start_row..cursor_row)
 5178        } else {
 5179            None
 5180        };
 5181        let is_move =
 5182            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5183        let completion = if is_move {
 5184            invalidation_row_range =
 5185                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5186            let target = first_edit_start;
 5187            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5188            // TODO: Base this off of TreeSitter or word boundaries?
 5189            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5190                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5191                Bias::Left,
 5192            ));
 5193            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5194                Point::new(target_point.row, target_point.column + 20),
 5195                Bias::Right,
 5196            ));
 5197            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5198            InlineCompletion::Move {
 5199                target,
 5200                range_around_target,
 5201                snapshot,
 5202            }
 5203        } else {
 5204            let show_completions_in_buffer = !self
 5205                .inline_completion_visible_in_cursor_popover(true, cx)
 5206                && !self.inline_completions_hidden_for_vim_mode;
 5207            if show_completions_in_buffer {
 5208                if edits
 5209                    .iter()
 5210                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5211                {
 5212                    let mut inlays = Vec::new();
 5213                    for (range, new_text) in &edits {
 5214                        let inlay = Inlay::inline_completion(
 5215                            post_inc(&mut self.next_inlay_id),
 5216                            range.start,
 5217                            new_text.as_str(),
 5218                        );
 5219                        inlay_ids.push(inlay.id);
 5220                        inlays.push(inlay);
 5221                    }
 5222
 5223                    self.splice_inlays(&[], inlays, cx);
 5224                } else {
 5225                    let background_color = cx.theme().status().deleted_background;
 5226                    self.highlight_text::<InlineCompletionHighlight>(
 5227                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5228                        HighlightStyle {
 5229                            background_color: Some(background_color),
 5230                            ..Default::default()
 5231                        },
 5232                        cx,
 5233                    );
 5234                }
 5235            }
 5236
 5237            invalidation_row_range = edit_start_row..edit_end_row;
 5238
 5239            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5240                if provider.show_tab_accept_marker() {
 5241                    EditDisplayMode::TabAccept
 5242                } else {
 5243                    EditDisplayMode::Inline
 5244                }
 5245            } else {
 5246                EditDisplayMode::DiffPopover
 5247            };
 5248
 5249            InlineCompletion::Edit {
 5250                edits,
 5251                edit_preview: inline_completion.edit_preview,
 5252                display_mode,
 5253                snapshot,
 5254            }
 5255        };
 5256
 5257        let invalidation_range = multibuffer
 5258            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5259            ..multibuffer.anchor_after(Point::new(
 5260                invalidation_row_range.end,
 5261                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5262            ));
 5263
 5264        self.stale_inline_completion_in_menu = None;
 5265        self.active_inline_completion = Some(InlineCompletionState {
 5266            inlay_ids,
 5267            completion,
 5268            completion_id: inline_completion.id,
 5269            invalidation_range,
 5270        });
 5271
 5272        cx.notify();
 5273
 5274        Some(())
 5275    }
 5276
 5277    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5278        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5279    }
 5280
 5281    fn show_edit_predictions_in_menu(&self, cx: &App) -> bool {
 5282        let by_provider = matches!(
 5283            self.menu_inline_completions_policy,
 5284            MenuInlineCompletionsPolicy::ByProvider
 5285        );
 5286
 5287        by_provider
 5288            && EditorSettings::get_global(cx).show_edit_predictions_in_menu
 5289            && self
 5290                .edit_prediction_provider()
 5291                .map_or(false, |provider| provider.show_completions_in_menu())
 5292    }
 5293
 5294    fn render_code_actions_indicator(
 5295        &self,
 5296        _style: &EditorStyle,
 5297        row: DisplayRow,
 5298        is_active: bool,
 5299        cx: &mut Context<Self>,
 5300    ) -> Option<IconButton> {
 5301        if self.available_code_actions.is_some() {
 5302            Some(
 5303                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5304                    .shape(ui::IconButtonShape::Square)
 5305                    .icon_size(IconSize::XSmall)
 5306                    .icon_color(Color::Muted)
 5307                    .toggle_state(is_active)
 5308                    .tooltip({
 5309                        let focus_handle = self.focus_handle.clone();
 5310                        move |window, cx| {
 5311                            Tooltip::for_action_in(
 5312                                "Toggle Code Actions",
 5313                                &ToggleCodeActions {
 5314                                    deployed_from_indicator: None,
 5315                                },
 5316                                &focus_handle,
 5317                                window,
 5318                                cx,
 5319                            )
 5320                        }
 5321                    })
 5322                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5323                        window.focus(&editor.focus_handle(cx));
 5324                        editor.toggle_code_actions(
 5325                            &ToggleCodeActions {
 5326                                deployed_from_indicator: Some(row),
 5327                            },
 5328                            window,
 5329                            cx,
 5330                        );
 5331                    })),
 5332            )
 5333        } else {
 5334            None
 5335        }
 5336    }
 5337
 5338    fn clear_tasks(&mut self) {
 5339        self.tasks.clear()
 5340    }
 5341
 5342    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5343        if self.tasks.insert(key, value).is_some() {
 5344            // This case should hopefully be rare, but just in case...
 5345            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5346        }
 5347    }
 5348
 5349    fn build_tasks_context(
 5350        project: &Entity<Project>,
 5351        buffer: &Entity<Buffer>,
 5352        buffer_row: u32,
 5353        tasks: &Arc<RunnableTasks>,
 5354        cx: &mut Context<Self>,
 5355    ) -> Task<Option<task::TaskContext>> {
 5356        let position = Point::new(buffer_row, tasks.column);
 5357        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5358        let location = Location {
 5359            buffer: buffer.clone(),
 5360            range: range_start..range_start,
 5361        };
 5362        // Fill in the environmental variables from the tree-sitter captures
 5363        let mut captured_task_variables = TaskVariables::default();
 5364        for (capture_name, value) in tasks.extra_variables.clone() {
 5365            captured_task_variables.insert(
 5366                task::VariableName::Custom(capture_name.into()),
 5367                value.clone(),
 5368            );
 5369        }
 5370        project.update(cx, |project, cx| {
 5371            project.task_store().update(cx, |task_store, cx| {
 5372                task_store.task_context_for_location(captured_task_variables, location, cx)
 5373            })
 5374        })
 5375    }
 5376
 5377    pub fn spawn_nearest_task(
 5378        &mut self,
 5379        action: &SpawnNearestTask,
 5380        window: &mut Window,
 5381        cx: &mut Context<Self>,
 5382    ) {
 5383        let Some((workspace, _)) = self.workspace.clone() else {
 5384            return;
 5385        };
 5386        let Some(project) = self.project.clone() else {
 5387            return;
 5388        };
 5389
 5390        // Try to find a closest, enclosing node using tree-sitter that has a
 5391        // task
 5392        let Some((buffer, buffer_row, tasks)) = self
 5393            .find_enclosing_node_task(cx)
 5394            // Or find the task that's closest in row-distance.
 5395            .or_else(|| self.find_closest_task(cx))
 5396        else {
 5397            return;
 5398        };
 5399
 5400        let reveal_strategy = action.reveal;
 5401        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5402        cx.spawn_in(window, |_, mut cx| async move {
 5403            let context = task_context.await?;
 5404            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5405
 5406            let resolved = resolved_task.resolved.as_mut()?;
 5407            resolved.reveal = reveal_strategy;
 5408
 5409            workspace
 5410                .update(&mut cx, |workspace, cx| {
 5411                    workspace::tasks::schedule_resolved_task(
 5412                        workspace,
 5413                        task_source_kind,
 5414                        resolved_task,
 5415                        false,
 5416                        cx,
 5417                    );
 5418                })
 5419                .ok()
 5420        })
 5421        .detach();
 5422    }
 5423
 5424    fn find_closest_task(
 5425        &mut self,
 5426        cx: &mut Context<Self>,
 5427    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5428        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5429
 5430        let ((buffer_id, row), tasks) = self
 5431            .tasks
 5432            .iter()
 5433            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5434
 5435        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5436        let tasks = Arc::new(tasks.to_owned());
 5437        Some((buffer, *row, tasks))
 5438    }
 5439
 5440    fn find_enclosing_node_task(
 5441        &mut self,
 5442        cx: &mut Context<Self>,
 5443    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5444        let snapshot = self.buffer.read(cx).snapshot(cx);
 5445        let offset = self.selections.newest::<usize>(cx).head();
 5446        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5447        let buffer_id = excerpt.buffer().remote_id();
 5448
 5449        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5450        let mut cursor = layer.node().walk();
 5451
 5452        while cursor.goto_first_child_for_byte(offset).is_some() {
 5453            if cursor.node().end_byte() == offset {
 5454                cursor.goto_next_sibling();
 5455            }
 5456        }
 5457
 5458        // Ascend to the smallest ancestor that contains the range and has a task.
 5459        loop {
 5460            let node = cursor.node();
 5461            let node_range = node.byte_range();
 5462            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5463
 5464            // Check if this node contains our offset
 5465            if node_range.start <= offset && node_range.end >= offset {
 5466                // If it contains offset, check for task
 5467                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5468                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5469                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5470                }
 5471            }
 5472
 5473            if !cursor.goto_parent() {
 5474                break;
 5475            }
 5476        }
 5477        None
 5478    }
 5479
 5480    fn render_run_indicator(
 5481        &self,
 5482        _style: &EditorStyle,
 5483        is_active: bool,
 5484        row: DisplayRow,
 5485        cx: &mut Context<Self>,
 5486    ) -> IconButton {
 5487        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5488            .shape(ui::IconButtonShape::Square)
 5489            .icon_size(IconSize::XSmall)
 5490            .icon_color(Color::Muted)
 5491            .toggle_state(is_active)
 5492            .on_click(cx.listener(move |editor, _e, window, cx| {
 5493                window.focus(&editor.focus_handle(cx));
 5494                editor.toggle_code_actions(
 5495                    &ToggleCodeActions {
 5496                        deployed_from_indicator: Some(row),
 5497                    },
 5498                    window,
 5499                    cx,
 5500                );
 5501            }))
 5502    }
 5503
 5504    pub fn context_menu_visible(&self) -> bool {
 5505        !self.previewing_inline_completion
 5506            && self
 5507                .context_menu
 5508                .borrow()
 5509                .as_ref()
 5510                .map_or(false, |menu| menu.visible())
 5511    }
 5512
 5513    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5514        self.context_menu
 5515            .borrow()
 5516            .as_ref()
 5517            .map(|menu| menu.origin())
 5518    }
 5519
 5520    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5521        px(30.)
 5522    }
 5523
 5524    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5525        if self.read_only(cx) {
 5526            cx.theme().players().read_only()
 5527        } else {
 5528            self.style.as_ref().unwrap().local_player
 5529        }
 5530    }
 5531
 5532    #[allow(clippy::too_many_arguments)]
 5533    fn render_edit_prediction_cursor_popover(
 5534        &self,
 5535        min_width: Pixels,
 5536        max_width: Pixels,
 5537        cursor_point: Point,
 5538        style: &EditorStyle,
 5539        accept_keystroke: &gpui::Keystroke,
 5540        window: &Window,
 5541        cx: &mut Context<Editor>,
 5542    ) -> Option<AnyElement> {
 5543        let provider = self.edit_prediction_provider.as_ref()?;
 5544
 5545        if provider.provider.needs_terms_acceptance(cx) {
 5546            return Some(
 5547                h_flex()
 5548                    .h(self.edit_prediction_cursor_popover_height())
 5549                    .min_w(min_width)
 5550                    .flex_1()
 5551                    .px_2()
 5552                    .gap_3()
 5553                    .elevation_2(cx)
 5554                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5555                    .id("accept-terms")
 5556                    .cursor_pointer()
 5557                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5558                    .on_click(cx.listener(|this, _event, window, cx| {
 5559                        cx.stop_propagation();
 5560                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5561                        window.dispatch_action(
 5562                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5563                            cx,
 5564                        );
 5565                    }))
 5566                    .child(
 5567                        h_flex()
 5568                            .flex_1()
 5569                            .gap_2()
 5570                            .child(Icon::new(IconName::ZedPredict))
 5571                            .child(Label::new("Accept Terms of Service"))
 5572                            .child(div().w_full())
 5573                            .child(
 5574                                Icon::new(IconName::ArrowUpRight)
 5575                                    .color(Color::Muted)
 5576                                    .size(IconSize::Small),
 5577                            )
 5578                            .into_any_element(),
 5579                    )
 5580                    .into_any(),
 5581            );
 5582        }
 5583
 5584        let is_refreshing = provider.provider.is_refreshing(cx);
 5585
 5586        fn pending_completion_container() -> Div {
 5587            h_flex()
 5588                .h_full()
 5589                .flex_1()
 5590                .gap_2()
 5591                .child(Icon::new(IconName::ZedPredict))
 5592        }
 5593
 5594        let completion = match &self.active_inline_completion {
 5595            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5596                completion,
 5597                cursor_point,
 5598                style,
 5599                window,
 5600                cx,
 5601            )?,
 5602
 5603            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5604                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5605                    stale_completion,
 5606                    cursor_point,
 5607                    style,
 5608                    window,
 5609                    cx,
 5610                )?,
 5611
 5612                None => {
 5613                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5614                }
 5615            },
 5616
 5617            None => pending_completion_container().child(Label::new("No Prediction")),
 5618        };
 5619
 5620        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5621        let completion = completion.font(buffer_font.clone());
 5622
 5623        let completion = if is_refreshing {
 5624            completion
 5625                .with_animation(
 5626                    "loading-completion",
 5627                    Animation::new(Duration::from_secs(2))
 5628                        .repeat()
 5629                        .with_easing(pulsating_between(0.4, 0.8)),
 5630                    |label, delta| label.opacity(delta),
 5631                )
 5632                .into_any_element()
 5633        } else {
 5634            completion.into_any_element()
 5635        };
 5636
 5637        let has_completion = self.active_inline_completion.is_some();
 5638
 5639        Some(
 5640            h_flex()
 5641                .h(self.edit_prediction_cursor_popover_height())
 5642                .min_w(min_width)
 5643                .max_w(max_width)
 5644                .flex_1()
 5645                .px_2()
 5646                .elevation_2(cx)
 5647                .child(completion)
 5648                .child(ui::Divider::vertical())
 5649                .child(
 5650                    h_flex()
 5651                        .h_full()
 5652                        .gap_1()
 5653                        .pl_2()
 5654                        .child(h_flex().font(buffer_font.clone()).gap_1().children(
 5655                            ui::render_modifiers(
 5656                                &accept_keystroke.modifiers,
 5657                                PlatformStyle::platform(),
 5658                                Some(if !has_completion {
 5659                                    Color::Muted
 5660                                } else {
 5661                                    Color::Default
 5662                                }),
 5663                                None,
 5664                                true,
 5665                            ),
 5666                        ))
 5667                        .child(Label::new("Preview").into_any_element())
 5668                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5669                )
 5670                .into_any(),
 5671        )
 5672    }
 5673
 5674    fn render_edit_prediction_cursor_popover_preview(
 5675        &self,
 5676        completion: &InlineCompletionState,
 5677        cursor_point: Point,
 5678        style: &EditorStyle,
 5679        window: &Window,
 5680        cx: &mut Context<Editor>,
 5681    ) -> Option<Div> {
 5682        use text::ToPoint as _;
 5683
 5684        fn render_relative_row_jump(
 5685            prefix: impl Into<String>,
 5686            current_row: u32,
 5687            target_row: u32,
 5688        ) -> Div {
 5689            let (row_diff, arrow) = if target_row < current_row {
 5690                (current_row - target_row, IconName::ArrowUp)
 5691            } else {
 5692                (target_row - current_row, IconName::ArrowDown)
 5693            };
 5694
 5695            h_flex()
 5696                .child(
 5697                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5698                        .color(Color::Muted)
 5699                        .size(LabelSize::Small),
 5700                )
 5701                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5702        }
 5703
 5704        match &completion.completion {
 5705            InlineCompletion::Edit {
 5706                edits,
 5707                edit_preview,
 5708                snapshot,
 5709                display_mode: _,
 5710            } => {
 5711                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5712
 5713                let highlighted_edits = crate::inline_completion_edit_text(
 5714                    &snapshot,
 5715                    &edits,
 5716                    edit_preview.as_ref()?,
 5717                    true,
 5718                    cx,
 5719                );
 5720
 5721                let len_total = highlighted_edits.text.len();
 5722                let first_line = &highlighted_edits.text
 5723                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5724                let first_line_len = first_line.len();
 5725
 5726                let first_highlight_start = highlighted_edits
 5727                    .highlights
 5728                    .first()
 5729                    .map_or(0, |(range, _)| range.start);
 5730                let drop_prefix_len = first_line
 5731                    .char_indices()
 5732                    .find(|(_, c)| !c.is_whitespace())
 5733                    .map_or(first_highlight_start, |(ix, _)| {
 5734                        ix.min(first_highlight_start)
 5735                    });
 5736
 5737                let preview_text = &first_line[drop_prefix_len..];
 5738                let preview_len = preview_text.len();
 5739                let highlights = highlighted_edits
 5740                    .highlights
 5741                    .into_iter()
 5742                    .take_until(|(range, _)| range.start > first_line_len)
 5743                    .map(|(range, style)| {
 5744                        (
 5745                            range.start - drop_prefix_len
 5746                                ..(range.end - drop_prefix_len).min(preview_len),
 5747                            style,
 5748                        )
 5749                    });
 5750
 5751                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5752                    .with_highlights(&style.text, highlights);
 5753
 5754                let preview = h_flex()
 5755                    .gap_1()
 5756                    .min_w_16()
 5757                    .child(styled_text)
 5758                    .when(len_total > first_line_len, |parent| parent.child(""));
 5759
 5760                let left = if first_edit_row != cursor_point.row {
 5761                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5762                        .into_any_element()
 5763                } else {
 5764                    Icon::new(IconName::ZedPredict).into_any_element()
 5765                };
 5766
 5767                Some(
 5768                    h_flex()
 5769                        .h_full()
 5770                        .flex_1()
 5771                        .gap_2()
 5772                        .pr_1()
 5773                        .overflow_x_hidden()
 5774                        .child(left)
 5775                        .child(preview),
 5776                )
 5777            }
 5778
 5779            InlineCompletion::Move {
 5780                target,
 5781                range_around_target,
 5782                snapshot,
 5783            } => {
 5784                let highlighted_text = snapshot.highlighted_text_for_range(
 5785                    range_around_target.clone(),
 5786                    None,
 5787                    &style.syntax,
 5788                );
 5789                let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
 5790                    "Jump ",
 5791                    cursor_point.row,
 5792                    target.text_anchor.to_point(&snapshot).row,
 5793                ));
 5794
 5795                if highlighted_text.text.is_empty() {
 5796                    return Some(base);
 5797                }
 5798
 5799                let cursor_color = self.current_user_player_color(cx).cursor;
 5800
 5801                let start_point = range_around_target.start.to_point(&snapshot);
 5802                let end_point = range_around_target.end.to_point(&snapshot);
 5803                let target_point = target.text_anchor.to_point(&snapshot);
 5804
 5805                let styled_text = highlighted_text.to_styled_text(&style.text);
 5806                let text_len = highlighted_text.text.len();
 5807
 5808                let cursor_relative_position = window
 5809                    .text_system()
 5810                    .layout_line(
 5811                        highlighted_text.text,
 5812                        style.text.font_size.to_pixels(window.rem_size()),
 5813                        // We don't need to include highlights
 5814                        // because we are only using this for the cursor position
 5815                        &[TextRun {
 5816                            len: text_len,
 5817                            font: style.text.font(),
 5818                            color: style.text.color,
 5819                            background_color: None,
 5820                            underline: None,
 5821                            strikethrough: None,
 5822                        }],
 5823                    )
 5824                    .log_err()
 5825                    .map(|line| {
 5826                        line.x_for_index(
 5827                            target_point.column.saturating_sub(start_point.column) as usize
 5828                        )
 5829                    });
 5830
 5831                let fade_before = start_point.column > 0;
 5832                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5833
 5834                let background = cx.theme().colors().elevated_surface_background;
 5835
 5836                let preview = h_flex()
 5837                    .relative()
 5838                    .child(styled_text)
 5839                    .when(fade_before, |parent| {
 5840                        parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
 5841                            linear_gradient(
 5842                                90.,
 5843                                linear_color_stop(background, 0.),
 5844                                linear_color_stop(background.opacity(0.), 1.),
 5845                            ),
 5846                        ))
 5847                    })
 5848                    .when(fade_after, |parent| {
 5849                        parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
 5850                            linear_gradient(
 5851                                -90.,
 5852                                linear_color_stop(background, 0.),
 5853                                linear_color_stop(background.opacity(0.), 1.),
 5854                            ),
 5855                        ))
 5856                    })
 5857                    .when_some(cursor_relative_position, |parent, position| {
 5858                        parent.child(
 5859                            div()
 5860                                .w(px(2.))
 5861                                .h_full()
 5862                                .bg(cursor_color)
 5863                                .absolute()
 5864                                .top_0()
 5865                                .left(position),
 5866                        )
 5867                    });
 5868
 5869                Some(base.child(preview))
 5870            }
 5871        }
 5872    }
 5873
 5874    fn render_context_menu(
 5875        &self,
 5876        style: &EditorStyle,
 5877        max_height_in_lines: u32,
 5878        y_flipped: bool,
 5879        window: &mut Window,
 5880        cx: &mut Context<Editor>,
 5881    ) -> Option<AnyElement> {
 5882        let menu = self.context_menu.borrow();
 5883        let menu = menu.as_ref()?;
 5884        if !menu.visible() {
 5885            return None;
 5886        };
 5887        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5888    }
 5889
 5890    fn render_context_menu_aside(
 5891        &self,
 5892        style: &EditorStyle,
 5893        max_size: Size<Pixels>,
 5894        cx: &mut Context<Editor>,
 5895    ) -> Option<AnyElement> {
 5896        self.context_menu.borrow().as_ref().and_then(|menu| {
 5897            if menu.visible() {
 5898                menu.render_aside(
 5899                    style,
 5900                    max_size,
 5901                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5902                    cx,
 5903                )
 5904            } else {
 5905                None
 5906            }
 5907        })
 5908    }
 5909
 5910    fn hide_context_menu(
 5911        &mut self,
 5912        window: &mut Window,
 5913        cx: &mut Context<Self>,
 5914    ) -> Option<CodeContextMenu> {
 5915        cx.notify();
 5916        self.completion_tasks.clear();
 5917        let context_menu = self.context_menu.borrow_mut().take();
 5918        self.stale_inline_completion_in_menu.take();
 5919        self.update_visible_inline_completion(window, cx);
 5920        context_menu
 5921    }
 5922
 5923    fn show_snippet_choices(
 5924        &mut self,
 5925        choices: &Vec<String>,
 5926        selection: Range<Anchor>,
 5927        cx: &mut Context<Self>,
 5928    ) {
 5929        if selection.start.buffer_id.is_none() {
 5930            return;
 5931        }
 5932        let buffer_id = selection.start.buffer_id.unwrap();
 5933        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5934        let id = post_inc(&mut self.next_completion_id);
 5935
 5936        if let Some(buffer) = buffer {
 5937            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5938                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5939            ));
 5940        }
 5941    }
 5942
 5943    pub fn insert_snippet(
 5944        &mut self,
 5945        insertion_ranges: &[Range<usize>],
 5946        snippet: Snippet,
 5947        window: &mut Window,
 5948        cx: &mut Context<Self>,
 5949    ) -> Result<()> {
 5950        struct Tabstop<T> {
 5951            is_end_tabstop: bool,
 5952            ranges: Vec<Range<T>>,
 5953            choices: Option<Vec<String>>,
 5954        }
 5955
 5956        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5957            let snippet_text: Arc<str> = snippet.text.clone().into();
 5958            buffer.edit(
 5959                insertion_ranges
 5960                    .iter()
 5961                    .cloned()
 5962                    .map(|range| (range, snippet_text.clone())),
 5963                Some(AutoindentMode::EachLine),
 5964                cx,
 5965            );
 5966
 5967            let snapshot = &*buffer.read(cx);
 5968            let snippet = &snippet;
 5969            snippet
 5970                .tabstops
 5971                .iter()
 5972                .map(|tabstop| {
 5973                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5974                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5975                    });
 5976                    let mut tabstop_ranges = tabstop
 5977                        .ranges
 5978                        .iter()
 5979                        .flat_map(|tabstop_range| {
 5980                            let mut delta = 0_isize;
 5981                            insertion_ranges.iter().map(move |insertion_range| {
 5982                                let insertion_start = insertion_range.start as isize + delta;
 5983                                delta +=
 5984                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5985
 5986                                let start = ((insertion_start + tabstop_range.start) as usize)
 5987                                    .min(snapshot.len());
 5988                                let end = ((insertion_start + tabstop_range.end) as usize)
 5989                                    .min(snapshot.len());
 5990                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5991                            })
 5992                        })
 5993                        .collect::<Vec<_>>();
 5994                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5995
 5996                    Tabstop {
 5997                        is_end_tabstop,
 5998                        ranges: tabstop_ranges,
 5999                        choices: tabstop.choices.clone(),
 6000                    }
 6001                })
 6002                .collect::<Vec<_>>()
 6003        });
 6004        if let Some(tabstop) = tabstops.first() {
 6005            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6006                s.select_ranges(tabstop.ranges.iter().cloned());
 6007            });
 6008
 6009            if let Some(choices) = &tabstop.choices {
 6010                if let Some(selection) = tabstop.ranges.first() {
 6011                    self.show_snippet_choices(choices, selection.clone(), cx)
 6012                }
 6013            }
 6014
 6015            // If we're already at the last tabstop and it's at the end of the snippet,
 6016            // we're done, we don't need to keep the state around.
 6017            if !tabstop.is_end_tabstop {
 6018                let choices = tabstops
 6019                    .iter()
 6020                    .map(|tabstop| tabstop.choices.clone())
 6021                    .collect();
 6022
 6023                let ranges = tabstops
 6024                    .into_iter()
 6025                    .map(|tabstop| tabstop.ranges)
 6026                    .collect::<Vec<_>>();
 6027
 6028                self.snippet_stack.push(SnippetState {
 6029                    active_index: 0,
 6030                    ranges,
 6031                    choices,
 6032                });
 6033            }
 6034
 6035            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6036            if self.autoclose_regions.is_empty() {
 6037                let snapshot = self.buffer.read(cx).snapshot(cx);
 6038                for selection in &mut self.selections.all::<Point>(cx) {
 6039                    let selection_head = selection.head();
 6040                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6041                        continue;
 6042                    };
 6043
 6044                    let mut bracket_pair = None;
 6045                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6046                    let prev_chars = snapshot
 6047                        .reversed_chars_at(selection_head)
 6048                        .collect::<String>();
 6049                    for (pair, enabled) in scope.brackets() {
 6050                        if enabled
 6051                            && pair.close
 6052                            && prev_chars.starts_with(pair.start.as_str())
 6053                            && next_chars.starts_with(pair.end.as_str())
 6054                        {
 6055                            bracket_pair = Some(pair.clone());
 6056                            break;
 6057                        }
 6058                    }
 6059                    if let Some(pair) = bracket_pair {
 6060                        let start = snapshot.anchor_after(selection_head);
 6061                        let end = snapshot.anchor_after(selection_head);
 6062                        self.autoclose_regions.push(AutocloseRegion {
 6063                            selection_id: selection.id,
 6064                            range: start..end,
 6065                            pair,
 6066                        });
 6067                    }
 6068                }
 6069            }
 6070        }
 6071        Ok(())
 6072    }
 6073
 6074    pub fn move_to_next_snippet_tabstop(
 6075        &mut self,
 6076        window: &mut Window,
 6077        cx: &mut Context<Self>,
 6078    ) -> bool {
 6079        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6080    }
 6081
 6082    pub fn move_to_prev_snippet_tabstop(
 6083        &mut self,
 6084        window: &mut Window,
 6085        cx: &mut Context<Self>,
 6086    ) -> bool {
 6087        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6088    }
 6089
 6090    pub fn move_to_snippet_tabstop(
 6091        &mut self,
 6092        bias: Bias,
 6093        window: &mut Window,
 6094        cx: &mut Context<Self>,
 6095    ) -> bool {
 6096        if let Some(mut snippet) = self.snippet_stack.pop() {
 6097            match bias {
 6098                Bias::Left => {
 6099                    if snippet.active_index > 0 {
 6100                        snippet.active_index -= 1;
 6101                    } else {
 6102                        self.snippet_stack.push(snippet);
 6103                        return false;
 6104                    }
 6105                }
 6106                Bias::Right => {
 6107                    if snippet.active_index + 1 < snippet.ranges.len() {
 6108                        snippet.active_index += 1;
 6109                    } else {
 6110                        self.snippet_stack.push(snippet);
 6111                        return false;
 6112                    }
 6113                }
 6114            }
 6115            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6116                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6117                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6118                });
 6119
 6120                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6121                    if let Some(selection) = current_ranges.first() {
 6122                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6123                    }
 6124                }
 6125
 6126                // If snippet state is not at the last tabstop, push it back on the stack
 6127                if snippet.active_index + 1 < snippet.ranges.len() {
 6128                    self.snippet_stack.push(snippet);
 6129                }
 6130                return true;
 6131            }
 6132        }
 6133
 6134        false
 6135    }
 6136
 6137    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6138        self.transact(window, cx, |this, window, cx| {
 6139            this.select_all(&SelectAll, window, cx);
 6140            this.insert("", window, cx);
 6141        });
 6142    }
 6143
 6144    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6145        self.transact(window, cx, |this, window, cx| {
 6146            this.select_autoclose_pair(window, cx);
 6147            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6148            if !this.linked_edit_ranges.is_empty() {
 6149                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6150                let snapshot = this.buffer.read(cx).snapshot(cx);
 6151
 6152                for selection in selections.iter() {
 6153                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6154                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6155                    if selection_start.buffer_id != selection_end.buffer_id {
 6156                        continue;
 6157                    }
 6158                    if let Some(ranges) =
 6159                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6160                    {
 6161                        for (buffer, entries) in ranges {
 6162                            linked_ranges.entry(buffer).or_default().extend(entries);
 6163                        }
 6164                    }
 6165                }
 6166            }
 6167
 6168            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6169            if !this.selections.line_mode {
 6170                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6171                for selection in &mut selections {
 6172                    if selection.is_empty() {
 6173                        let old_head = selection.head();
 6174                        let mut new_head =
 6175                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6176                                .to_point(&display_map);
 6177                        if let Some((buffer, line_buffer_range)) = display_map
 6178                            .buffer_snapshot
 6179                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6180                        {
 6181                            let indent_size =
 6182                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6183                            let indent_len = match indent_size.kind {
 6184                                IndentKind::Space => {
 6185                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6186                                }
 6187                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6188                            };
 6189                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6190                                let indent_len = indent_len.get();
 6191                                new_head = cmp::min(
 6192                                    new_head,
 6193                                    MultiBufferPoint::new(
 6194                                        old_head.row,
 6195                                        ((old_head.column - 1) / indent_len) * indent_len,
 6196                                    ),
 6197                                );
 6198                            }
 6199                        }
 6200
 6201                        selection.set_head(new_head, SelectionGoal::None);
 6202                    }
 6203                }
 6204            }
 6205
 6206            this.signature_help_state.set_backspace_pressed(true);
 6207            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6208                s.select(selections)
 6209            });
 6210            this.insert("", window, cx);
 6211            let empty_str: Arc<str> = Arc::from("");
 6212            for (buffer, edits) in linked_ranges {
 6213                let snapshot = buffer.read(cx).snapshot();
 6214                use text::ToPoint as TP;
 6215
 6216                let edits = edits
 6217                    .into_iter()
 6218                    .map(|range| {
 6219                        let end_point = TP::to_point(&range.end, &snapshot);
 6220                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6221
 6222                        if end_point == start_point {
 6223                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6224                                .saturating_sub(1);
 6225                            start_point =
 6226                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6227                        };
 6228
 6229                        (start_point..end_point, empty_str.clone())
 6230                    })
 6231                    .sorted_by_key(|(range, _)| range.start)
 6232                    .collect::<Vec<_>>();
 6233                buffer.update(cx, |this, cx| {
 6234                    this.edit(edits, None, cx);
 6235                })
 6236            }
 6237            this.refresh_inline_completion(true, false, window, cx);
 6238            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6239        });
 6240    }
 6241
 6242    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6243        self.transact(window, cx, |this, window, cx| {
 6244            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6245                let line_mode = s.line_mode;
 6246                s.move_with(|map, selection| {
 6247                    if selection.is_empty() && !line_mode {
 6248                        let cursor = movement::right(map, selection.head());
 6249                        selection.end = cursor;
 6250                        selection.reversed = true;
 6251                        selection.goal = SelectionGoal::None;
 6252                    }
 6253                })
 6254            });
 6255            this.insert("", window, cx);
 6256            this.refresh_inline_completion(true, false, window, cx);
 6257        });
 6258    }
 6259
 6260    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6261        if self.move_to_prev_snippet_tabstop(window, cx) {
 6262            return;
 6263        }
 6264
 6265        self.outdent(&Outdent, window, cx);
 6266    }
 6267
 6268    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6269        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6270            return;
 6271        }
 6272
 6273        let mut selections = self.selections.all_adjusted(cx);
 6274        let buffer = self.buffer.read(cx);
 6275        let snapshot = buffer.snapshot(cx);
 6276        let rows_iter = selections.iter().map(|s| s.head().row);
 6277        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6278
 6279        let mut edits = Vec::new();
 6280        let mut prev_edited_row = 0;
 6281        let mut row_delta = 0;
 6282        for selection in &mut selections {
 6283            if selection.start.row != prev_edited_row {
 6284                row_delta = 0;
 6285            }
 6286            prev_edited_row = selection.end.row;
 6287
 6288            // If the selection is non-empty, then increase the indentation of the selected lines.
 6289            if !selection.is_empty() {
 6290                row_delta =
 6291                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6292                continue;
 6293            }
 6294
 6295            // If the selection is empty and the cursor is in the leading whitespace before the
 6296            // suggested indentation, then auto-indent the line.
 6297            let cursor = selection.head();
 6298            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6299            if let Some(suggested_indent) =
 6300                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6301            {
 6302                if cursor.column < suggested_indent.len
 6303                    && cursor.column <= current_indent.len
 6304                    && current_indent.len <= suggested_indent.len
 6305                {
 6306                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6307                    selection.end = selection.start;
 6308                    if row_delta == 0 {
 6309                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6310                            cursor.row,
 6311                            current_indent,
 6312                            suggested_indent,
 6313                        ));
 6314                        row_delta = suggested_indent.len - current_indent.len;
 6315                    }
 6316                    continue;
 6317                }
 6318            }
 6319
 6320            // Otherwise, insert a hard or soft tab.
 6321            let settings = buffer.settings_at(cursor, cx);
 6322            let tab_size = if settings.hard_tabs {
 6323                IndentSize::tab()
 6324            } else {
 6325                let tab_size = settings.tab_size.get();
 6326                let char_column = snapshot
 6327                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6328                    .flat_map(str::chars)
 6329                    .count()
 6330                    + row_delta as usize;
 6331                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6332                IndentSize::spaces(chars_to_next_tab_stop)
 6333            };
 6334            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6335            selection.end = selection.start;
 6336            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6337            row_delta += tab_size.len;
 6338        }
 6339
 6340        self.transact(window, cx, |this, window, cx| {
 6341            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6342            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6343                s.select(selections)
 6344            });
 6345            this.refresh_inline_completion(true, false, window, cx);
 6346        });
 6347    }
 6348
 6349    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6350        if self.read_only(cx) {
 6351            return;
 6352        }
 6353        let mut selections = self.selections.all::<Point>(cx);
 6354        let mut prev_edited_row = 0;
 6355        let mut row_delta = 0;
 6356        let mut edits = Vec::new();
 6357        let buffer = self.buffer.read(cx);
 6358        let snapshot = buffer.snapshot(cx);
 6359        for selection in &mut selections {
 6360            if selection.start.row != prev_edited_row {
 6361                row_delta = 0;
 6362            }
 6363            prev_edited_row = selection.end.row;
 6364
 6365            row_delta =
 6366                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6367        }
 6368
 6369        self.transact(window, cx, |this, window, cx| {
 6370            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6371            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6372                s.select(selections)
 6373            });
 6374        });
 6375    }
 6376
 6377    fn indent_selection(
 6378        buffer: &MultiBuffer,
 6379        snapshot: &MultiBufferSnapshot,
 6380        selection: &mut Selection<Point>,
 6381        edits: &mut Vec<(Range<Point>, String)>,
 6382        delta_for_start_row: u32,
 6383        cx: &App,
 6384    ) -> u32 {
 6385        let settings = buffer.settings_at(selection.start, cx);
 6386        let tab_size = settings.tab_size.get();
 6387        let indent_kind = if settings.hard_tabs {
 6388            IndentKind::Tab
 6389        } else {
 6390            IndentKind::Space
 6391        };
 6392        let mut start_row = selection.start.row;
 6393        let mut end_row = selection.end.row + 1;
 6394
 6395        // If a selection ends at the beginning of a line, don't indent
 6396        // that last line.
 6397        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6398            end_row -= 1;
 6399        }
 6400
 6401        // Avoid re-indenting a row that has already been indented by a
 6402        // previous selection, but still update this selection's column
 6403        // to reflect that indentation.
 6404        if delta_for_start_row > 0 {
 6405            start_row += 1;
 6406            selection.start.column += delta_for_start_row;
 6407            if selection.end.row == selection.start.row {
 6408                selection.end.column += delta_for_start_row;
 6409            }
 6410        }
 6411
 6412        let mut delta_for_end_row = 0;
 6413        let has_multiple_rows = start_row + 1 != end_row;
 6414        for row in start_row..end_row {
 6415            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6416            let indent_delta = match (current_indent.kind, indent_kind) {
 6417                (IndentKind::Space, IndentKind::Space) => {
 6418                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6419                    IndentSize::spaces(columns_to_next_tab_stop)
 6420                }
 6421                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6422                (_, IndentKind::Tab) => IndentSize::tab(),
 6423            };
 6424
 6425            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6426                0
 6427            } else {
 6428                selection.start.column
 6429            };
 6430            let row_start = Point::new(row, start);
 6431            edits.push((
 6432                row_start..row_start,
 6433                indent_delta.chars().collect::<String>(),
 6434            ));
 6435
 6436            // Update this selection's endpoints to reflect the indentation.
 6437            if row == selection.start.row {
 6438                selection.start.column += indent_delta.len;
 6439            }
 6440            if row == selection.end.row {
 6441                selection.end.column += indent_delta.len;
 6442                delta_for_end_row = indent_delta.len;
 6443            }
 6444        }
 6445
 6446        if selection.start.row == selection.end.row {
 6447            delta_for_start_row + delta_for_end_row
 6448        } else {
 6449            delta_for_end_row
 6450        }
 6451    }
 6452
 6453    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6454        if self.read_only(cx) {
 6455            return;
 6456        }
 6457        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6458        let selections = self.selections.all::<Point>(cx);
 6459        let mut deletion_ranges = Vec::new();
 6460        let mut last_outdent = None;
 6461        {
 6462            let buffer = self.buffer.read(cx);
 6463            let snapshot = buffer.snapshot(cx);
 6464            for selection in &selections {
 6465                let settings = buffer.settings_at(selection.start, cx);
 6466                let tab_size = settings.tab_size.get();
 6467                let mut rows = selection.spanned_rows(false, &display_map);
 6468
 6469                // Avoid re-outdenting a row that has already been outdented by a
 6470                // previous selection.
 6471                if let Some(last_row) = last_outdent {
 6472                    if last_row == rows.start {
 6473                        rows.start = rows.start.next_row();
 6474                    }
 6475                }
 6476                let has_multiple_rows = rows.len() > 1;
 6477                for row in rows.iter_rows() {
 6478                    let indent_size = snapshot.indent_size_for_line(row);
 6479                    if indent_size.len > 0 {
 6480                        let deletion_len = match indent_size.kind {
 6481                            IndentKind::Space => {
 6482                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6483                                if columns_to_prev_tab_stop == 0 {
 6484                                    tab_size
 6485                                } else {
 6486                                    columns_to_prev_tab_stop
 6487                                }
 6488                            }
 6489                            IndentKind::Tab => 1,
 6490                        };
 6491                        let start = if has_multiple_rows
 6492                            || deletion_len > selection.start.column
 6493                            || indent_size.len < selection.start.column
 6494                        {
 6495                            0
 6496                        } else {
 6497                            selection.start.column - deletion_len
 6498                        };
 6499                        deletion_ranges.push(
 6500                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6501                        );
 6502                        last_outdent = Some(row);
 6503                    }
 6504                }
 6505            }
 6506        }
 6507
 6508        self.transact(window, cx, |this, window, cx| {
 6509            this.buffer.update(cx, |buffer, cx| {
 6510                let empty_str: Arc<str> = Arc::default();
 6511                buffer.edit(
 6512                    deletion_ranges
 6513                        .into_iter()
 6514                        .map(|range| (range, empty_str.clone())),
 6515                    None,
 6516                    cx,
 6517                );
 6518            });
 6519            let selections = this.selections.all::<usize>(cx);
 6520            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6521                s.select(selections)
 6522            });
 6523        });
 6524    }
 6525
 6526    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6527        if self.read_only(cx) {
 6528            return;
 6529        }
 6530        let selections = self
 6531            .selections
 6532            .all::<usize>(cx)
 6533            .into_iter()
 6534            .map(|s| s.range());
 6535
 6536        self.transact(window, cx, |this, window, cx| {
 6537            this.buffer.update(cx, |buffer, cx| {
 6538                buffer.autoindent_ranges(selections, cx);
 6539            });
 6540            let selections = this.selections.all::<usize>(cx);
 6541            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6542                s.select(selections)
 6543            });
 6544        });
 6545    }
 6546
 6547    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6548        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6549        let selections = self.selections.all::<Point>(cx);
 6550
 6551        let mut new_cursors = Vec::new();
 6552        let mut edit_ranges = Vec::new();
 6553        let mut selections = selections.iter().peekable();
 6554        while let Some(selection) = selections.next() {
 6555            let mut rows = selection.spanned_rows(false, &display_map);
 6556            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6557
 6558            // Accumulate contiguous regions of rows that we want to delete.
 6559            while let Some(next_selection) = selections.peek() {
 6560                let next_rows = next_selection.spanned_rows(false, &display_map);
 6561                if next_rows.start <= rows.end {
 6562                    rows.end = next_rows.end;
 6563                    selections.next().unwrap();
 6564                } else {
 6565                    break;
 6566                }
 6567            }
 6568
 6569            let buffer = &display_map.buffer_snapshot;
 6570            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6571            let edit_end;
 6572            let cursor_buffer_row;
 6573            if buffer.max_point().row >= rows.end.0 {
 6574                // If there's a line after the range, delete the \n from the end of the row range
 6575                // and position the cursor on the next line.
 6576                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6577                cursor_buffer_row = rows.end;
 6578            } else {
 6579                // If there isn't a line after the range, delete the \n from the line before the
 6580                // start of the row range and position the cursor there.
 6581                edit_start = edit_start.saturating_sub(1);
 6582                edit_end = buffer.len();
 6583                cursor_buffer_row = rows.start.previous_row();
 6584            }
 6585
 6586            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6587            *cursor.column_mut() =
 6588                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6589
 6590            new_cursors.push((
 6591                selection.id,
 6592                buffer.anchor_after(cursor.to_point(&display_map)),
 6593            ));
 6594            edit_ranges.push(edit_start..edit_end);
 6595        }
 6596
 6597        self.transact(window, cx, |this, window, cx| {
 6598            let buffer = this.buffer.update(cx, |buffer, cx| {
 6599                let empty_str: Arc<str> = Arc::default();
 6600                buffer.edit(
 6601                    edit_ranges
 6602                        .into_iter()
 6603                        .map(|range| (range, empty_str.clone())),
 6604                    None,
 6605                    cx,
 6606                );
 6607                buffer.snapshot(cx)
 6608            });
 6609            let new_selections = new_cursors
 6610                .into_iter()
 6611                .map(|(id, cursor)| {
 6612                    let cursor = cursor.to_point(&buffer);
 6613                    Selection {
 6614                        id,
 6615                        start: cursor,
 6616                        end: cursor,
 6617                        reversed: false,
 6618                        goal: SelectionGoal::None,
 6619                    }
 6620                })
 6621                .collect();
 6622
 6623            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6624                s.select(new_selections);
 6625            });
 6626        });
 6627    }
 6628
 6629    pub fn join_lines_impl(
 6630        &mut self,
 6631        insert_whitespace: bool,
 6632        window: &mut Window,
 6633        cx: &mut Context<Self>,
 6634    ) {
 6635        if self.read_only(cx) {
 6636            return;
 6637        }
 6638        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6639        for selection in self.selections.all::<Point>(cx) {
 6640            let start = MultiBufferRow(selection.start.row);
 6641            // Treat single line selections as if they include the next line. Otherwise this action
 6642            // would do nothing for single line selections individual cursors.
 6643            let end = if selection.start.row == selection.end.row {
 6644                MultiBufferRow(selection.start.row + 1)
 6645            } else {
 6646                MultiBufferRow(selection.end.row)
 6647            };
 6648
 6649            if let Some(last_row_range) = row_ranges.last_mut() {
 6650                if start <= last_row_range.end {
 6651                    last_row_range.end = end;
 6652                    continue;
 6653                }
 6654            }
 6655            row_ranges.push(start..end);
 6656        }
 6657
 6658        let snapshot = self.buffer.read(cx).snapshot(cx);
 6659        let mut cursor_positions = Vec::new();
 6660        for row_range in &row_ranges {
 6661            let anchor = snapshot.anchor_before(Point::new(
 6662                row_range.end.previous_row().0,
 6663                snapshot.line_len(row_range.end.previous_row()),
 6664            ));
 6665            cursor_positions.push(anchor..anchor);
 6666        }
 6667
 6668        self.transact(window, cx, |this, window, cx| {
 6669            for row_range in row_ranges.into_iter().rev() {
 6670                for row in row_range.iter_rows().rev() {
 6671                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6672                    let next_line_row = row.next_row();
 6673                    let indent = snapshot.indent_size_for_line(next_line_row);
 6674                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6675
 6676                    let replace =
 6677                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6678                            " "
 6679                        } else {
 6680                            ""
 6681                        };
 6682
 6683                    this.buffer.update(cx, |buffer, cx| {
 6684                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6685                    });
 6686                }
 6687            }
 6688
 6689            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6690                s.select_anchor_ranges(cursor_positions)
 6691            });
 6692        });
 6693    }
 6694
 6695    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6696        self.join_lines_impl(true, window, cx);
 6697    }
 6698
 6699    pub fn sort_lines_case_sensitive(
 6700        &mut self,
 6701        _: &SortLinesCaseSensitive,
 6702        window: &mut Window,
 6703        cx: &mut Context<Self>,
 6704    ) {
 6705        self.manipulate_lines(window, cx, |lines| lines.sort())
 6706    }
 6707
 6708    pub fn sort_lines_case_insensitive(
 6709        &mut self,
 6710        _: &SortLinesCaseInsensitive,
 6711        window: &mut Window,
 6712        cx: &mut Context<Self>,
 6713    ) {
 6714        self.manipulate_lines(window, cx, |lines| {
 6715            lines.sort_by_key(|line| line.to_lowercase())
 6716        })
 6717    }
 6718
 6719    pub fn unique_lines_case_insensitive(
 6720        &mut self,
 6721        _: &UniqueLinesCaseInsensitive,
 6722        window: &mut Window,
 6723        cx: &mut Context<Self>,
 6724    ) {
 6725        self.manipulate_lines(window, cx, |lines| {
 6726            let mut seen = HashSet::default();
 6727            lines.retain(|line| seen.insert(line.to_lowercase()));
 6728        })
 6729    }
 6730
 6731    pub fn unique_lines_case_sensitive(
 6732        &mut self,
 6733        _: &UniqueLinesCaseSensitive,
 6734        window: &mut Window,
 6735        cx: &mut Context<Self>,
 6736    ) {
 6737        self.manipulate_lines(window, cx, |lines| {
 6738            let mut seen = HashSet::default();
 6739            lines.retain(|line| seen.insert(*line));
 6740        })
 6741    }
 6742
 6743    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6744        let mut revert_changes = HashMap::default();
 6745        let snapshot = self.snapshot(window, cx);
 6746        for hunk in snapshot
 6747            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6748        {
 6749            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6750        }
 6751        if !revert_changes.is_empty() {
 6752            self.transact(window, cx, |editor, window, cx| {
 6753                editor.revert(revert_changes, window, cx);
 6754            });
 6755        }
 6756    }
 6757
 6758    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6759        let Some(project) = self.project.clone() else {
 6760            return;
 6761        };
 6762        self.reload(project, window, cx)
 6763            .detach_and_notify_err(window, cx);
 6764    }
 6765
 6766    pub fn revert_selected_hunks(
 6767        &mut self,
 6768        _: &RevertSelectedHunks,
 6769        window: &mut Window,
 6770        cx: &mut Context<Self>,
 6771    ) {
 6772        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6773        self.revert_hunks_in_ranges(selections, window, cx);
 6774    }
 6775
 6776    fn revert_hunks_in_ranges(
 6777        &mut self,
 6778        ranges: impl Iterator<Item = Range<Point>>,
 6779        window: &mut Window,
 6780        cx: &mut Context<Editor>,
 6781    ) {
 6782        let mut revert_changes = HashMap::default();
 6783        let snapshot = self.snapshot(window, cx);
 6784        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6785            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6786        }
 6787        if !revert_changes.is_empty() {
 6788            self.transact(window, cx, |editor, window, cx| {
 6789                editor.revert(revert_changes, window, cx);
 6790            });
 6791        }
 6792    }
 6793
 6794    pub fn open_active_item_in_terminal(
 6795        &mut self,
 6796        _: &OpenInTerminal,
 6797        window: &mut Window,
 6798        cx: &mut Context<Self>,
 6799    ) {
 6800        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6801            let project_path = buffer.read(cx).project_path(cx)?;
 6802            let project = self.project.as_ref()?.read(cx);
 6803            let entry = project.entry_for_path(&project_path, cx)?;
 6804            let parent = match &entry.canonical_path {
 6805                Some(canonical_path) => canonical_path.to_path_buf(),
 6806                None => project.absolute_path(&project_path, cx)?,
 6807            }
 6808            .parent()?
 6809            .to_path_buf();
 6810            Some(parent)
 6811        }) {
 6812            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6813        }
 6814    }
 6815
 6816    pub fn prepare_revert_change(
 6817        &self,
 6818        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6819        hunk: &MultiBufferDiffHunk,
 6820        cx: &mut App,
 6821    ) -> Option<()> {
 6822        let buffer = self.buffer.read(cx);
 6823        let diff = buffer.diff_for(hunk.buffer_id)?;
 6824        let buffer = buffer.buffer(hunk.buffer_id)?;
 6825        let buffer = buffer.read(cx);
 6826        let original_text = diff
 6827            .read(cx)
 6828            .snapshot
 6829            .base_text
 6830            .as_ref()?
 6831            .as_rope()
 6832            .slice(hunk.diff_base_byte_range.clone());
 6833        let buffer_snapshot = buffer.snapshot();
 6834        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6835        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6836            probe
 6837                .0
 6838                .start
 6839                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6840                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6841        }) {
 6842            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6843            Some(())
 6844        } else {
 6845            None
 6846        }
 6847    }
 6848
 6849    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6850        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6851    }
 6852
 6853    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6854        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6855    }
 6856
 6857    fn manipulate_lines<Fn>(
 6858        &mut self,
 6859        window: &mut Window,
 6860        cx: &mut Context<Self>,
 6861        mut callback: Fn,
 6862    ) where
 6863        Fn: FnMut(&mut Vec<&str>),
 6864    {
 6865        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6866        let buffer = self.buffer.read(cx).snapshot(cx);
 6867
 6868        let mut edits = Vec::new();
 6869
 6870        let selections = self.selections.all::<Point>(cx);
 6871        let mut selections = selections.iter().peekable();
 6872        let mut contiguous_row_selections = Vec::new();
 6873        let mut new_selections = Vec::new();
 6874        let mut added_lines = 0;
 6875        let mut removed_lines = 0;
 6876
 6877        while let Some(selection) = selections.next() {
 6878            let (start_row, end_row) = consume_contiguous_rows(
 6879                &mut contiguous_row_selections,
 6880                selection,
 6881                &display_map,
 6882                &mut selections,
 6883            );
 6884
 6885            let start_point = Point::new(start_row.0, 0);
 6886            let end_point = Point::new(
 6887                end_row.previous_row().0,
 6888                buffer.line_len(end_row.previous_row()),
 6889            );
 6890            let text = buffer
 6891                .text_for_range(start_point..end_point)
 6892                .collect::<String>();
 6893
 6894            let mut lines = text.split('\n').collect_vec();
 6895
 6896            let lines_before = lines.len();
 6897            callback(&mut lines);
 6898            let lines_after = lines.len();
 6899
 6900            edits.push((start_point..end_point, lines.join("\n")));
 6901
 6902            // Selections must change based on added and removed line count
 6903            let start_row =
 6904                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6905            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6906            new_selections.push(Selection {
 6907                id: selection.id,
 6908                start: start_row,
 6909                end: end_row,
 6910                goal: SelectionGoal::None,
 6911                reversed: selection.reversed,
 6912            });
 6913
 6914            if lines_after > lines_before {
 6915                added_lines += lines_after - lines_before;
 6916            } else if lines_before > lines_after {
 6917                removed_lines += lines_before - lines_after;
 6918            }
 6919        }
 6920
 6921        self.transact(window, cx, |this, window, cx| {
 6922            let buffer = this.buffer.update(cx, |buffer, cx| {
 6923                buffer.edit(edits, None, cx);
 6924                buffer.snapshot(cx)
 6925            });
 6926
 6927            // Recalculate offsets on newly edited buffer
 6928            let new_selections = new_selections
 6929                .iter()
 6930                .map(|s| {
 6931                    let start_point = Point::new(s.start.0, 0);
 6932                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6933                    Selection {
 6934                        id: s.id,
 6935                        start: buffer.point_to_offset(start_point),
 6936                        end: buffer.point_to_offset(end_point),
 6937                        goal: s.goal,
 6938                        reversed: s.reversed,
 6939                    }
 6940                })
 6941                .collect();
 6942
 6943            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6944                s.select(new_selections);
 6945            });
 6946
 6947            this.request_autoscroll(Autoscroll::fit(), cx);
 6948        });
 6949    }
 6950
 6951    pub fn convert_to_upper_case(
 6952        &mut self,
 6953        _: &ConvertToUpperCase,
 6954        window: &mut Window,
 6955        cx: &mut Context<Self>,
 6956    ) {
 6957        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6958    }
 6959
 6960    pub fn convert_to_lower_case(
 6961        &mut self,
 6962        _: &ConvertToLowerCase,
 6963        window: &mut Window,
 6964        cx: &mut Context<Self>,
 6965    ) {
 6966        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6967    }
 6968
 6969    pub fn convert_to_title_case(
 6970        &mut self,
 6971        _: &ConvertToTitleCase,
 6972        window: &mut Window,
 6973        cx: &mut Context<Self>,
 6974    ) {
 6975        self.manipulate_text(window, cx, |text| {
 6976            text.split('\n')
 6977                .map(|line| line.to_case(Case::Title))
 6978                .join("\n")
 6979        })
 6980    }
 6981
 6982    pub fn convert_to_snake_case(
 6983        &mut self,
 6984        _: &ConvertToSnakeCase,
 6985        window: &mut Window,
 6986        cx: &mut Context<Self>,
 6987    ) {
 6988        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6989    }
 6990
 6991    pub fn convert_to_kebab_case(
 6992        &mut self,
 6993        _: &ConvertToKebabCase,
 6994        window: &mut Window,
 6995        cx: &mut Context<Self>,
 6996    ) {
 6997        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6998    }
 6999
 7000    pub fn convert_to_upper_camel_case(
 7001        &mut self,
 7002        _: &ConvertToUpperCamelCase,
 7003        window: &mut Window,
 7004        cx: &mut Context<Self>,
 7005    ) {
 7006        self.manipulate_text(window, cx, |text| {
 7007            text.split('\n')
 7008                .map(|line| line.to_case(Case::UpperCamel))
 7009                .join("\n")
 7010        })
 7011    }
 7012
 7013    pub fn convert_to_lower_camel_case(
 7014        &mut self,
 7015        _: &ConvertToLowerCamelCase,
 7016        window: &mut Window,
 7017        cx: &mut Context<Self>,
 7018    ) {
 7019        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7020    }
 7021
 7022    pub fn convert_to_opposite_case(
 7023        &mut self,
 7024        _: &ConvertToOppositeCase,
 7025        window: &mut Window,
 7026        cx: &mut Context<Self>,
 7027    ) {
 7028        self.manipulate_text(window, cx, |text| {
 7029            text.chars()
 7030                .fold(String::with_capacity(text.len()), |mut t, c| {
 7031                    if c.is_uppercase() {
 7032                        t.extend(c.to_lowercase());
 7033                    } else {
 7034                        t.extend(c.to_uppercase());
 7035                    }
 7036                    t
 7037                })
 7038        })
 7039    }
 7040
 7041    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7042    where
 7043        Fn: FnMut(&str) -> String,
 7044    {
 7045        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7046        let buffer = self.buffer.read(cx).snapshot(cx);
 7047
 7048        let mut new_selections = Vec::new();
 7049        let mut edits = Vec::new();
 7050        let mut selection_adjustment = 0i32;
 7051
 7052        for selection in self.selections.all::<usize>(cx) {
 7053            let selection_is_empty = selection.is_empty();
 7054
 7055            let (start, end) = if selection_is_empty {
 7056                let word_range = movement::surrounding_word(
 7057                    &display_map,
 7058                    selection.start.to_display_point(&display_map),
 7059                );
 7060                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7061                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7062                (start, end)
 7063            } else {
 7064                (selection.start, selection.end)
 7065            };
 7066
 7067            let text = buffer.text_for_range(start..end).collect::<String>();
 7068            let old_length = text.len() as i32;
 7069            let text = callback(&text);
 7070
 7071            new_selections.push(Selection {
 7072                start: (start as i32 - selection_adjustment) as usize,
 7073                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7074                goal: SelectionGoal::None,
 7075                ..selection
 7076            });
 7077
 7078            selection_adjustment += old_length - text.len() as i32;
 7079
 7080            edits.push((start..end, text));
 7081        }
 7082
 7083        self.transact(window, cx, |this, window, cx| {
 7084            this.buffer.update(cx, |buffer, cx| {
 7085                buffer.edit(edits, None, cx);
 7086            });
 7087
 7088            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7089                s.select(new_selections);
 7090            });
 7091
 7092            this.request_autoscroll(Autoscroll::fit(), cx);
 7093        });
 7094    }
 7095
 7096    pub fn duplicate(
 7097        &mut self,
 7098        upwards: bool,
 7099        whole_lines: bool,
 7100        window: &mut Window,
 7101        cx: &mut Context<Self>,
 7102    ) {
 7103        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7104        let buffer = &display_map.buffer_snapshot;
 7105        let selections = self.selections.all::<Point>(cx);
 7106
 7107        let mut edits = Vec::new();
 7108        let mut selections_iter = selections.iter().peekable();
 7109        while let Some(selection) = selections_iter.next() {
 7110            let mut rows = selection.spanned_rows(false, &display_map);
 7111            // duplicate line-wise
 7112            if whole_lines || selection.start == selection.end {
 7113                // Avoid duplicating the same lines twice.
 7114                while let Some(next_selection) = selections_iter.peek() {
 7115                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7116                    if next_rows.start < rows.end {
 7117                        rows.end = next_rows.end;
 7118                        selections_iter.next().unwrap();
 7119                    } else {
 7120                        break;
 7121                    }
 7122                }
 7123
 7124                // Copy the text from the selected row region and splice it either at the start
 7125                // or end of the region.
 7126                let start = Point::new(rows.start.0, 0);
 7127                let end = Point::new(
 7128                    rows.end.previous_row().0,
 7129                    buffer.line_len(rows.end.previous_row()),
 7130                );
 7131                let text = buffer
 7132                    .text_for_range(start..end)
 7133                    .chain(Some("\n"))
 7134                    .collect::<String>();
 7135                let insert_location = if upwards {
 7136                    Point::new(rows.end.0, 0)
 7137                } else {
 7138                    start
 7139                };
 7140                edits.push((insert_location..insert_location, text));
 7141            } else {
 7142                // duplicate character-wise
 7143                let start = selection.start;
 7144                let end = selection.end;
 7145                let text = buffer.text_for_range(start..end).collect::<String>();
 7146                edits.push((selection.end..selection.end, text));
 7147            }
 7148        }
 7149
 7150        self.transact(window, cx, |this, _, cx| {
 7151            this.buffer.update(cx, |buffer, cx| {
 7152                buffer.edit(edits, None, cx);
 7153            });
 7154
 7155            this.request_autoscroll(Autoscroll::fit(), cx);
 7156        });
 7157    }
 7158
 7159    pub fn duplicate_line_up(
 7160        &mut self,
 7161        _: &DuplicateLineUp,
 7162        window: &mut Window,
 7163        cx: &mut Context<Self>,
 7164    ) {
 7165        self.duplicate(true, true, window, cx);
 7166    }
 7167
 7168    pub fn duplicate_line_down(
 7169        &mut self,
 7170        _: &DuplicateLineDown,
 7171        window: &mut Window,
 7172        cx: &mut Context<Self>,
 7173    ) {
 7174        self.duplicate(false, true, window, cx);
 7175    }
 7176
 7177    pub fn duplicate_selection(
 7178        &mut self,
 7179        _: &DuplicateSelection,
 7180        window: &mut Window,
 7181        cx: &mut Context<Self>,
 7182    ) {
 7183        self.duplicate(false, false, window, cx);
 7184    }
 7185
 7186    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7187        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7188        let buffer = self.buffer.read(cx).snapshot(cx);
 7189
 7190        let mut edits = Vec::new();
 7191        let mut unfold_ranges = Vec::new();
 7192        let mut refold_creases = Vec::new();
 7193
 7194        let selections = self.selections.all::<Point>(cx);
 7195        let mut selections = selections.iter().peekable();
 7196        let mut contiguous_row_selections = Vec::new();
 7197        let mut new_selections = Vec::new();
 7198
 7199        while let Some(selection) = selections.next() {
 7200            // Find all the selections that span a contiguous row range
 7201            let (start_row, end_row) = consume_contiguous_rows(
 7202                &mut contiguous_row_selections,
 7203                selection,
 7204                &display_map,
 7205                &mut selections,
 7206            );
 7207
 7208            // Move the text spanned by the row range to be before the line preceding the row range
 7209            if start_row.0 > 0 {
 7210                let range_to_move = Point::new(
 7211                    start_row.previous_row().0,
 7212                    buffer.line_len(start_row.previous_row()),
 7213                )
 7214                    ..Point::new(
 7215                        end_row.previous_row().0,
 7216                        buffer.line_len(end_row.previous_row()),
 7217                    );
 7218                let insertion_point = display_map
 7219                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7220                    .0;
 7221
 7222                // Don't move lines across excerpts
 7223                if buffer
 7224                    .excerpt_containing(insertion_point..range_to_move.end)
 7225                    .is_some()
 7226                {
 7227                    let text = buffer
 7228                        .text_for_range(range_to_move.clone())
 7229                        .flat_map(|s| s.chars())
 7230                        .skip(1)
 7231                        .chain(['\n'])
 7232                        .collect::<String>();
 7233
 7234                    edits.push((
 7235                        buffer.anchor_after(range_to_move.start)
 7236                            ..buffer.anchor_before(range_to_move.end),
 7237                        String::new(),
 7238                    ));
 7239                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7240                    edits.push((insertion_anchor..insertion_anchor, text));
 7241
 7242                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7243
 7244                    // Move selections up
 7245                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7246                        |mut selection| {
 7247                            selection.start.row -= row_delta;
 7248                            selection.end.row -= row_delta;
 7249                            selection
 7250                        },
 7251                    ));
 7252
 7253                    // Move folds up
 7254                    unfold_ranges.push(range_to_move.clone());
 7255                    for fold in display_map.folds_in_range(
 7256                        buffer.anchor_before(range_to_move.start)
 7257                            ..buffer.anchor_after(range_to_move.end),
 7258                    ) {
 7259                        let mut start = fold.range.start.to_point(&buffer);
 7260                        let mut end = fold.range.end.to_point(&buffer);
 7261                        start.row -= row_delta;
 7262                        end.row -= row_delta;
 7263                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7264                    }
 7265                }
 7266            }
 7267
 7268            // If we didn't move line(s), preserve the existing selections
 7269            new_selections.append(&mut contiguous_row_selections);
 7270        }
 7271
 7272        self.transact(window, cx, |this, window, cx| {
 7273            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7274            this.buffer.update(cx, |buffer, cx| {
 7275                for (range, text) in edits {
 7276                    buffer.edit([(range, text)], None, cx);
 7277                }
 7278            });
 7279            this.fold_creases(refold_creases, true, window, cx);
 7280            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7281                s.select(new_selections);
 7282            })
 7283        });
 7284    }
 7285
 7286    pub fn move_line_down(
 7287        &mut self,
 7288        _: &MoveLineDown,
 7289        window: &mut Window,
 7290        cx: &mut Context<Self>,
 7291    ) {
 7292        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7293        let buffer = self.buffer.read(cx).snapshot(cx);
 7294
 7295        let mut edits = Vec::new();
 7296        let mut unfold_ranges = Vec::new();
 7297        let mut refold_creases = Vec::new();
 7298
 7299        let selections = self.selections.all::<Point>(cx);
 7300        let mut selections = selections.iter().peekable();
 7301        let mut contiguous_row_selections = Vec::new();
 7302        let mut new_selections = Vec::new();
 7303
 7304        while let Some(selection) = selections.next() {
 7305            // Find all the selections that span a contiguous row range
 7306            let (start_row, end_row) = consume_contiguous_rows(
 7307                &mut contiguous_row_selections,
 7308                selection,
 7309                &display_map,
 7310                &mut selections,
 7311            );
 7312
 7313            // Move the text spanned by the row range to be after the last line of the row range
 7314            if end_row.0 <= buffer.max_point().row {
 7315                let range_to_move =
 7316                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7317                let insertion_point = display_map
 7318                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7319                    .0;
 7320
 7321                // Don't move lines across excerpt boundaries
 7322                if buffer
 7323                    .excerpt_containing(range_to_move.start..insertion_point)
 7324                    .is_some()
 7325                {
 7326                    let mut text = String::from("\n");
 7327                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7328                    text.pop(); // Drop trailing newline
 7329                    edits.push((
 7330                        buffer.anchor_after(range_to_move.start)
 7331                            ..buffer.anchor_before(range_to_move.end),
 7332                        String::new(),
 7333                    ));
 7334                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7335                    edits.push((insertion_anchor..insertion_anchor, text));
 7336
 7337                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7338
 7339                    // Move selections down
 7340                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7341                        |mut selection| {
 7342                            selection.start.row += row_delta;
 7343                            selection.end.row += row_delta;
 7344                            selection
 7345                        },
 7346                    ));
 7347
 7348                    // Move folds down
 7349                    unfold_ranges.push(range_to_move.clone());
 7350                    for fold in display_map.folds_in_range(
 7351                        buffer.anchor_before(range_to_move.start)
 7352                            ..buffer.anchor_after(range_to_move.end),
 7353                    ) {
 7354                        let mut start = fold.range.start.to_point(&buffer);
 7355                        let mut end = fold.range.end.to_point(&buffer);
 7356                        start.row += row_delta;
 7357                        end.row += row_delta;
 7358                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7359                    }
 7360                }
 7361            }
 7362
 7363            // If we didn't move line(s), preserve the existing selections
 7364            new_selections.append(&mut contiguous_row_selections);
 7365        }
 7366
 7367        self.transact(window, cx, |this, window, cx| {
 7368            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7369            this.buffer.update(cx, |buffer, cx| {
 7370                for (range, text) in edits {
 7371                    buffer.edit([(range, text)], None, cx);
 7372                }
 7373            });
 7374            this.fold_creases(refold_creases, true, window, cx);
 7375            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7376                s.select(new_selections)
 7377            });
 7378        });
 7379    }
 7380
 7381    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7382        let text_layout_details = &self.text_layout_details(window);
 7383        self.transact(window, cx, |this, window, cx| {
 7384            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7385                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7386                let line_mode = s.line_mode;
 7387                s.move_with(|display_map, selection| {
 7388                    if !selection.is_empty() || line_mode {
 7389                        return;
 7390                    }
 7391
 7392                    let mut head = selection.head();
 7393                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7394                    if head.column() == display_map.line_len(head.row()) {
 7395                        transpose_offset = display_map
 7396                            .buffer_snapshot
 7397                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7398                    }
 7399
 7400                    if transpose_offset == 0 {
 7401                        return;
 7402                    }
 7403
 7404                    *head.column_mut() += 1;
 7405                    head = display_map.clip_point(head, Bias::Right);
 7406                    let goal = SelectionGoal::HorizontalPosition(
 7407                        display_map
 7408                            .x_for_display_point(head, text_layout_details)
 7409                            .into(),
 7410                    );
 7411                    selection.collapse_to(head, goal);
 7412
 7413                    let transpose_start = display_map
 7414                        .buffer_snapshot
 7415                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7416                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7417                        let transpose_end = display_map
 7418                            .buffer_snapshot
 7419                            .clip_offset(transpose_offset + 1, Bias::Right);
 7420                        if let Some(ch) =
 7421                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7422                        {
 7423                            edits.push((transpose_start..transpose_offset, String::new()));
 7424                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7425                        }
 7426                    }
 7427                });
 7428                edits
 7429            });
 7430            this.buffer
 7431                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7432            let selections = this.selections.all::<usize>(cx);
 7433            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7434                s.select(selections);
 7435            });
 7436        });
 7437    }
 7438
 7439    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7440        self.rewrap_impl(IsVimMode::No, cx)
 7441    }
 7442
 7443    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7444        let buffer = self.buffer.read(cx).snapshot(cx);
 7445        let selections = self.selections.all::<Point>(cx);
 7446        let mut selections = selections.iter().peekable();
 7447
 7448        let mut edits = Vec::new();
 7449        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7450
 7451        while let Some(selection) = selections.next() {
 7452            let mut start_row = selection.start.row;
 7453            let mut end_row = selection.end.row;
 7454
 7455            // Skip selections that overlap with a range that has already been rewrapped.
 7456            let selection_range = start_row..end_row;
 7457            if rewrapped_row_ranges
 7458                .iter()
 7459                .any(|range| range.overlaps(&selection_range))
 7460            {
 7461                continue;
 7462            }
 7463
 7464            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7465
 7466            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7467                match language_scope.language_name().as_ref() {
 7468                    "Markdown" | "Plain Text" => {
 7469                        should_rewrap = true;
 7470                    }
 7471                    _ => {}
 7472                }
 7473            }
 7474
 7475            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7476
 7477            // Since not all lines in the selection may be at the same indent
 7478            // level, choose the indent size that is the most common between all
 7479            // of the lines.
 7480            //
 7481            // If there is a tie, we use the deepest indent.
 7482            let (indent_size, indent_end) = {
 7483                let mut indent_size_occurrences = HashMap::default();
 7484                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7485
 7486                for row in start_row..=end_row {
 7487                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7488                    rows_by_indent_size.entry(indent).or_default().push(row);
 7489                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7490                }
 7491
 7492                let indent_size = indent_size_occurrences
 7493                    .into_iter()
 7494                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7495                    .map(|(indent, _)| indent)
 7496                    .unwrap_or_default();
 7497                let row = rows_by_indent_size[&indent_size][0];
 7498                let indent_end = Point::new(row, indent_size.len);
 7499
 7500                (indent_size, indent_end)
 7501            };
 7502
 7503            let mut line_prefix = indent_size.chars().collect::<String>();
 7504
 7505            if let Some(comment_prefix) =
 7506                buffer
 7507                    .language_scope_at(selection.head())
 7508                    .and_then(|language| {
 7509                        language
 7510                            .line_comment_prefixes()
 7511                            .iter()
 7512                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7513                            .cloned()
 7514                    })
 7515            {
 7516                line_prefix.push_str(&comment_prefix);
 7517                should_rewrap = true;
 7518            }
 7519
 7520            if !should_rewrap {
 7521                continue;
 7522            }
 7523
 7524            if selection.is_empty() {
 7525                'expand_upwards: while start_row > 0 {
 7526                    let prev_row = start_row - 1;
 7527                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7528                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7529                    {
 7530                        start_row = prev_row;
 7531                    } else {
 7532                        break 'expand_upwards;
 7533                    }
 7534                }
 7535
 7536                'expand_downwards: while end_row < buffer.max_point().row {
 7537                    let next_row = end_row + 1;
 7538                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7539                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7540                    {
 7541                        end_row = next_row;
 7542                    } else {
 7543                        break 'expand_downwards;
 7544                    }
 7545                }
 7546            }
 7547
 7548            let start = Point::new(start_row, 0);
 7549            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7550            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7551            let Some(lines_without_prefixes) = selection_text
 7552                .lines()
 7553                .map(|line| {
 7554                    line.strip_prefix(&line_prefix)
 7555                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7556                        .ok_or_else(|| {
 7557                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7558                        })
 7559                })
 7560                .collect::<Result<Vec<_>, _>>()
 7561                .log_err()
 7562            else {
 7563                continue;
 7564            };
 7565
 7566            let wrap_column = buffer
 7567                .settings_at(Point::new(start_row, 0), cx)
 7568                .preferred_line_length as usize;
 7569            let wrapped_text = wrap_with_prefix(
 7570                line_prefix,
 7571                lines_without_prefixes.join(" "),
 7572                wrap_column,
 7573                tab_size,
 7574            );
 7575
 7576            // TODO: should always use char-based diff while still supporting cursor behavior that
 7577            // matches vim.
 7578            let diff = match is_vim_mode {
 7579                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7580                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7581            };
 7582            let mut offset = start.to_offset(&buffer);
 7583            let mut moved_since_edit = true;
 7584
 7585            for change in diff.iter_all_changes() {
 7586                let value = change.value();
 7587                match change.tag() {
 7588                    ChangeTag::Equal => {
 7589                        offset += value.len();
 7590                        moved_since_edit = true;
 7591                    }
 7592                    ChangeTag::Delete => {
 7593                        let start = buffer.anchor_after(offset);
 7594                        let end = buffer.anchor_before(offset + value.len());
 7595
 7596                        if moved_since_edit {
 7597                            edits.push((start..end, String::new()));
 7598                        } else {
 7599                            edits.last_mut().unwrap().0.end = end;
 7600                        }
 7601
 7602                        offset += value.len();
 7603                        moved_since_edit = false;
 7604                    }
 7605                    ChangeTag::Insert => {
 7606                        if moved_since_edit {
 7607                            let anchor = buffer.anchor_after(offset);
 7608                            edits.push((anchor..anchor, value.to_string()));
 7609                        } else {
 7610                            edits.last_mut().unwrap().1.push_str(value);
 7611                        }
 7612
 7613                        moved_since_edit = false;
 7614                    }
 7615                }
 7616            }
 7617
 7618            rewrapped_row_ranges.push(start_row..=end_row);
 7619        }
 7620
 7621        self.buffer
 7622            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7623    }
 7624
 7625    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7626        let mut text = String::new();
 7627        let buffer = self.buffer.read(cx).snapshot(cx);
 7628        let mut selections = self.selections.all::<Point>(cx);
 7629        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7630        {
 7631            let max_point = buffer.max_point();
 7632            let mut is_first = true;
 7633            for selection in &mut selections {
 7634                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7635                if is_entire_line {
 7636                    selection.start = Point::new(selection.start.row, 0);
 7637                    if !selection.is_empty() && selection.end.column == 0 {
 7638                        selection.end = cmp::min(max_point, selection.end);
 7639                    } else {
 7640                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7641                    }
 7642                    selection.goal = SelectionGoal::None;
 7643                }
 7644                if is_first {
 7645                    is_first = false;
 7646                } else {
 7647                    text += "\n";
 7648                }
 7649                let mut len = 0;
 7650                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7651                    text.push_str(chunk);
 7652                    len += chunk.len();
 7653                }
 7654                clipboard_selections.push(ClipboardSelection {
 7655                    len,
 7656                    is_entire_line,
 7657                    first_line_indent: buffer
 7658                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7659                        .len,
 7660                });
 7661            }
 7662        }
 7663
 7664        self.transact(window, cx, |this, window, cx| {
 7665            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7666                s.select(selections);
 7667            });
 7668            this.insert("", window, cx);
 7669        });
 7670        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7671    }
 7672
 7673    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7674        let item = self.cut_common(window, cx);
 7675        cx.write_to_clipboard(item);
 7676    }
 7677
 7678    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7679        self.change_selections(None, window, cx, |s| {
 7680            s.move_with(|snapshot, sel| {
 7681                if sel.is_empty() {
 7682                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7683                }
 7684            });
 7685        });
 7686        let item = self.cut_common(window, cx);
 7687        cx.set_global(KillRing(item))
 7688    }
 7689
 7690    pub fn kill_ring_yank(
 7691        &mut self,
 7692        _: &KillRingYank,
 7693        window: &mut Window,
 7694        cx: &mut Context<Self>,
 7695    ) {
 7696        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7697            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7698                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7699            } else {
 7700                return;
 7701            }
 7702        } else {
 7703            return;
 7704        };
 7705        self.do_paste(&text, metadata, false, window, cx);
 7706    }
 7707
 7708    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7709        let selections = self.selections.all::<Point>(cx);
 7710        let buffer = self.buffer.read(cx).read(cx);
 7711        let mut text = String::new();
 7712
 7713        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7714        {
 7715            let max_point = buffer.max_point();
 7716            let mut is_first = true;
 7717            for selection in selections.iter() {
 7718                let mut start = selection.start;
 7719                let mut end = selection.end;
 7720                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7721                if is_entire_line {
 7722                    start = Point::new(start.row, 0);
 7723                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7724                }
 7725                if is_first {
 7726                    is_first = false;
 7727                } else {
 7728                    text += "\n";
 7729                }
 7730                let mut len = 0;
 7731                for chunk in buffer.text_for_range(start..end) {
 7732                    text.push_str(chunk);
 7733                    len += chunk.len();
 7734                }
 7735                clipboard_selections.push(ClipboardSelection {
 7736                    len,
 7737                    is_entire_line,
 7738                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7739                });
 7740            }
 7741        }
 7742
 7743        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7744            text,
 7745            clipboard_selections,
 7746        ));
 7747    }
 7748
 7749    pub fn do_paste(
 7750        &mut self,
 7751        text: &String,
 7752        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7753        handle_entire_lines: bool,
 7754        window: &mut Window,
 7755        cx: &mut Context<Self>,
 7756    ) {
 7757        if self.read_only(cx) {
 7758            return;
 7759        }
 7760
 7761        let clipboard_text = Cow::Borrowed(text);
 7762
 7763        self.transact(window, cx, |this, window, cx| {
 7764            if let Some(mut clipboard_selections) = clipboard_selections {
 7765                let old_selections = this.selections.all::<usize>(cx);
 7766                let all_selections_were_entire_line =
 7767                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7768                let first_selection_indent_column =
 7769                    clipboard_selections.first().map(|s| s.first_line_indent);
 7770                if clipboard_selections.len() != old_selections.len() {
 7771                    clipboard_selections.drain(..);
 7772                }
 7773                let cursor_offset = this.selections.last::<usize>(cx).head();
 7774                let mut auto_indent_on_paste = true;
 7775
 7776                this.buffer.update(cx, |buffer, cx| {
 7777                    let snapshot = buffer.read(cx);
 7778                    auto_indent_on_paste =
 7779                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7780
 7781                    let mut start_offset = 0;
 7782                    let mut edits = Vec::new();
 7783                    let mut original_indent_columns = Vec::new();
 7784                    for (ix, selection) in old_selections.iter().enumerate() {
 7785                        let to_insert;
 7786                        let entire_line;
 7787                        let original_indent_column;
 7788                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7789                            let end_offset = start_offset + clipboard_selection.len;
 7790                            to_insert = &clipboard_text[start_offset..end_offset];
 7791                            entire_line = clipboard_selection.is_entire_line;
 7792                            start_offset = end_offset + 1;
 7793                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7794                        } else {
 7795                            to_insert = clipboard_text.as_str();
 7796                            entire_line = all_selections_were_entire_line;
 7797                            original_indent_column = first_selection_indent_column
 7798                        }
 7799
 7800                        // If the corresponding selection was empty when this slice of the
 7801                        // clipboard text was written, then the entire line containing the
 7802                        // selection was copied. If this selection is also currently empty,
 7803                        // then paste the line before the current line of the buffer.
 7804                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7805                            let column = selection.start.to_point(&snapshot).column as usize;
 7806                            let line_start = selection.start - column;
 7807                            line_start..line_start
 7808                        } else {
 7809                            selection.range()
 7810                        };
 7811
 7812                        edits.push((range, to_insert));
 7813                        original_indent_columns.extend(original_indent_column);
 7814                    }
 7815                    drop(snapshot);
 7816
 7817                    buffer.edit(
 7818                        edits,
 7819                        if auto_indent_on_paste {
 7820                            Some(AutoindentMode::Block {
 7821                                original_indent_columns,
 7822                            })
 7823                        } else {
 7824                            None
 7825                        },
 7826                        cx,
 7827                    );
 7828                });
 7829
 7830                let selections = this.selections.all::<usize>(cx);
 7831                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7832                    s.select(selections)
 7833                });
 7834            } else {
 7835                this.insert(&clipboard_text, window, cx);
 7836            }
 7837        });
 7838    }
 7839
 7840    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7841        if let Some(item) = cx.read_from_clipboard() {
 7842            let entries = item.entries();
 7843
 7844            match entries.first() {
 7845                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7846                // of all the pasted entries.
 7847                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7848                    .do_paste(
 7849                        clipboard_string.text(),
 7850                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7851                        true,
 7852                        window,
 7853                        cx,
 7854                    ),
 7855                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7856            }
 7857        }
 7858    }
 7859
 7860    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7861        if self.read_only(cx) {
 7862            return;
 7863        }
 7864
 7865        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7866            if let Some((selections, _)) =
 7867                self.selection_history.transaction(transaction_id).cloned()
 7868            {
 7869                self.change_selections(None, window, cx, |s| {
 7870                    s.select_anchors(selections.to_vec());
 7871                });
 7872            }
 7873            self.request_autoscroll(Autoscroll::fit(), cx);
 7874            self.unmark_text(window, cx);
 7875            self.refresh_inline_completion(true, false, window, cx);
 7876            cx.emit(EditorEvent::Edited { transaction_id });
 7877            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7878        }
 7879    }
 7880
 7881    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7882        if self.read_only(cx) {
 7883            return;
 7884        }
 7885
 7886        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7887            if let Some((_, Some(selections))) =
 7888                self.selection_history.transaction(transaction_id).cloned()
 7889            {
 7890                self.change_selections(None, window, cx, |s| {
 7891                    s.select_anchors(selections.to_vec());
 7892                });
 7893            }
 7894            self.request_autoscroll(Autoscroll::fit(), cx);
 7895            self.unmark_text(window, cx);
 7896            self.refresh_inline_completion(true, false, window, cx);
 7897            cx.emit(EditorEvent::Edited { transaction_id });
 7898        }
 7899    }
 7900
 7901    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7902        self.buffer
 7903            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7904    }
 7905
 7906    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7907        self.buffer
 7908            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7909    }
 7910
 7911    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7912        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7913            let line_mode = s.line_mode;
 7914            s.move_with(|map, selection| {
 7915                let cursor = if selection.is_empty() && !line_mode {
 7916                    movement::left(map, selection.start)
 7917                } else {
 7918                    selection.start
 7919                };
 7920                selection.collapse_to(cursor, SelectionGoal::None);
 7921            });
 7922        })
 7923    }
 7924
 7925    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7927            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7928        })
 7929    }
 7930
 7931    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7933            let line_mode = s.line_mode;
 7934            s.move_with(|map, selection| {
 7935                let cursor = if selection.is_empty() && !line_mode {
 7936                    movement::right(map, selection.end)
 7937                } else {
 7938                    selection.end
 7939                };
 7940                selection.collapse_to(cursor, SelectionGoal::None)
 7941            });
 7942        })
 7943    }
 7944
 7945    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7946        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7947            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7948        })
 7949    }
 7950
 7951    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7952        if self.take_rename(true, window, cx).is_some() {
 7953            return;
 7954        }
 7955
 7956        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7957            cx.propagate();
 7958            return;
 7959        }
 7960
 7961        let text_layout_details = &self.text_layout_details(window);
 7962        let selection_count = self.selections.count();
 7963        let first_selection = self.selections.first_anchor();
 7964
 7965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7966            let line_mode = s.line_mode;
 7967            s.move_with(|map, selection| {
 7968                if !selection.is_empty() && !line_mode {
 7969                    selection.goal = SelectionGoal::None;
 7970                }
 7971                let (cursor, goal) = movement::up(
 7972                    map,
 7973                    selection.start,
 7974                    selection.goal,
 7975                    false,
 7976                    text_layout_details,
 7977                );
 7978                selection.collapse_to(cursor, goal);
 7979            });
 7980        });
 7981
 7982        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7983        {
 7984            cx.propagate();
 7985        }
 7986    }
 7987
 7988    pub fn move_up_by_lines(
 7989        &mut self,
 7990        action: &MoveUpByLines,
 7991        window: &mut Window,
 7992        cx: &mut Context<Self>,
 7993    ) {
 7994        if self.take_rename(true, window, cx).is_some() {
 7995            return;
 7996        }
 7997
 7998        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7999            cx.propagate();
 8000            return;
 8001        }
 8002
 8003        let text_layout_details = &self.text_layout_details(window);
 8004
 8005        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8006            let line_mode = s.line_mode;
 8007            s.move_with(|map, selection| {
 8008                if !selection.is_empty() && !line_mode {
 8009                    selection.goal = SelectionGoal::None;
 8010                }
 8011                let (cursor, goal) = movement::up_by_rows(
 8012                    map,
 8013                    selection.start,
 8014                    action.lines,
 8015                    selection.goal,
 8016                    false,
 8017                    text_layout_details,
 8018                );
 8019                selection.collapse_to(cursor, goal);
 8020            });
 8021        })
 8022    }
 8023
 8024    pub fn move_down_by_lines(
 8025        &mut self,
 8026        action: &MoveDownByLines,
 8027        window: &mut Window,
 8028        cx: &mut Context<Self>,
 8029    ) {
 8030        if self.take_rename(true, window, cx).is_some() {
 8031            return;
 8032        }
 8033
 8034        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8035            cx.propagate();
 8036            return;
 8037        }
 8038
 8039        let text_layout_details = &self.text_layout_details(window);
 8040
 8041        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8042            let line_mode = s.line_mode;
 8043            s.move_with(|map, selection| {
 8044                if !selection.is_empty() && !line_mode {
 8045                    selection.goal = SelectionGoal::None;
 8046                }
 8047                let (cursor, goal) = movement::down_by_rows(
 8048                    map,
 8049                    selection.start,
 8050                    action.lines,
 8051                    selection.goal,
 8052                    false,
 8053                    text_layout_details,
 8054                );
 8055                selection.collapse_to(cursor, goal);
 8056            });
 8057        })
 8058    }
 8059
 8060    pub fn select_down_by_lines(
 8061        &mut self,
 8062        action: &SelectDownByLines,
 8063        window: &mut Window,
 8064        cx: &mut Context<Self>,
 8065    ) {
 8066        let text_layout_details = &self.text_layout_details(window);
 8067        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8068            s.move_heads_with(|map, head, goal| {
 8069                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8070            })
 8071        })
 8072    }
 8073
 8074    pub fn select_up_by_lines(
 8075        &mut self,
 8076        action: &SelectUpByLines,
 8077        window: &mut Window,
 8078        cx: &mut Context<Self>,
 8079    ) {
 8080        let text_layout_details = &self.text_layout_details(window);
 8081        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8082            s.move_heads_with(|map, head, goal| {
 8083                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8084            })
 8085        })
 8086    }
 8087
 8088    pub fn select_page_up(
 8089        &mut self,
 8090        _: &SelectPageUp,
 8091        window: &mut Window,
 8092        cx: &mut Context<Self>,
 8093    ) {
 8094        let Some(row_count) = self.visible_row_count() else {
 8095            return;
 8096        };
 8097
 8098        let text_layout_details = &self.text_layout_details(window);
 8099
 8100        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8101            s.move_heads_with(|map, head, goal| {
 8102                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8103            })
 8104        })
 8105    }
 8106
 8107    pub fn move_page_up(
 8108        &mut self,
 8109        action: &MovePageUp,
 8110        window: &mut Window,
 8111        cx: &mut Context<Self>,
 8112    ) {
 8113        if self.take_rename(true, window, cx).is_some() {
 8114            return;
 8115        }
 8116
 8117        if self
 8118            .context_menu
 8119            .borrow_mut()
 8120            .as_mut()
 8121            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8122            .unwrap_or(false)
 8123        {
 8124            return;
 8125        }
 8126
 8127        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8128            cx.propagate();
 8129            return;
 8130        }
 8131
 8132        let Some(row_count) = self.visible_row_count() else {
 8133            return;
 8134        };
 8135
 8136        let autoscroll = if action.center_cursor {
 8137            Autoscroll::center()
 8138        } else {
 8139            Autoscroll::fit()
 8140        };
 8141
 8142        let text_layout_details = &self.text_layout_details(window);
 8143
 8144        self.change_selections(Some(autoscroll), window, cx, |s| {
 8145            let line_mode = s.line_mode;
 8146            s.move_with(|map, selection| {
 8147                if !selection.is_empty() && !line_mode {
 8148                    selection.goal = SelectionGoal::None;
 8149                }
 8150                let (cursor, goal) = movement::up_by_rows(
 8151                    map,
 8152                    selection.end,
 8153                    row_count,
 8154                    selection.goal,
 8155                    false,
 8156                    text_layout_details,
 8157                );
 8158                selection.collapse_to(cursor, goal);
 8159            });
 8160        });
 8161    }
 8162
 8163    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8164        let text_layout_details = &self.text_layout_details(window);
 8165        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8166            s.move_heads_with(|map, head, goal| {
 8167                movement::up(map, head, goal, false, text_layout_details)
 8168            })
 8169        })
 8170    }
 8171
 8172    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8173        self.take_rename(true, window, cx);
 8174
 8175        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8176            cx.propagate();
 8177            return;
 8178        }
 8179
 8180        let text_layout_details = &self.text_layout_details(window);
 8181        let selection_count = self.selections.count();
 8182        let first_selection = self.selections.first_anchor();
 8183
 8184        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8185            let line_mode = s.line_mode;
 8186            s.move_with(|map, selection| {
 8187                if !selection.is_empty() && !line_mode {
 8188                    selection.goal = SelectionGoal::None;
 8189                }
 8190                let (cursor, goal) = movement::down(
 8191                    map,
 8192                    selection.end,
 8193                    selection.goal,
 8194                    false,
 8195                    text_layout_details,
 8196                );
 8197                selection.collapse_to(cursor, goal);
 8198            });
 8199        });
 8200
 8201        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8202        {
 8203            cx.propagate();
 8204        }
 8205    }
 8206
 8207    pub fn select_page_down(
 8208        &mut self,
 8209        _: &SelectPageDown,
 8210        window: &mut Window,
 8211        cx: &mut Context<Self>,
 8212    ) {
 8213        let Some(row_count) = self.visible_row_count() else {
 8214            return;
 8215        };
 8216
 8217        let text_layout_details = &self.text_layout_details(window);
 8218
 8219        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8220            s.move_heads_with(|map, head, goal| {
 8221                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8222            })
 8223        })
 8224    }
 8225
 8226    pub fn move_page_down(
 8227        &mut self,
 8228        action: &MovePageDown,
 8229        window: &mut Window,
 8230        cx: &mut Context<Self>,
 8231    ) {
 8232        if self.take_rename(true, window, cx).is_some() {
 8233            return;
 8234        }
 8235
 8236        if self
 8237            .context_menu
 8238            .borrow_mut()
 8239            .as_mut()
 8240            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8241            .unwrap_or(false)
 8242        {
 8243            return;
 8244        }
 8245
 8246        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8247            cx.propagate();
 8248            return;
 8249        }
 8250
 8251        let Some(row_count) = self.visible_row_count() else {
 8252            return;
 8253        };
 8254
 8255        let autoscroll = if action.center_cursor {
 8256            Autoscroll::center()
 8257        } else {
 8258            Autoscroll::fit()
 8259        };
 8260
 8261        let text_layout_details = &self.text_layout_details(window);
 8262        self.change_selections(Some(autoscroll), window, cx, |s| {
 8263            let line_mode = s.line_mode;
 8264            s.move_with(|map, selection| {
 8265                if !selection.is_empty() && !line_mode {
 8266                    selection.goal = SelectionGoal::None;
 8267                }
 8268                let (cursor, goal) = movement::down_by_rows(
 8269                    map,
 8270                    selection.end,
 8271                    row_count,
 8272                    selection.goal,
 8273                    false,
 8274                    text_layout_details,
 8275                );
 8276                selection.collapse_to(cursor, goal);
 8277            });
 8278        });
 8279    }
 8280
 8281    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8282        let text_layout_details = &self.text_layout_details(window);
 8283        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8284            s.move_heads_with(|map, head, goal| {
 8285                movement::down(map, head, goal, false, text_layout_details)
 8286            })
 8287        });
 8288    }
 8289
 8290    pub fn context_menu_first(
 8291        &mut self,
 8292        _: &ContextMenuFirst,
 8293        _window: &mut Window,
 8294        cx: &mut Context<Self>,
 8295    ) {
 8296        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8297            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8298        }
 8299    }
 8300
 8301    pub fn context_menu_prev(
 8302        &mut self,
 8303        _: &ContextMenuPrev,
 8304        _window: &mut Window,
 8305        cx: &mut Context<Self>,
 8306    ) {
 8307        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8308            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8309        }
 8310    }
 8311
 8312    pub fn context_menu_next(
 8313        &mut self,
 8314        _: &ContextMenuNext,
 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_next(self.completion_provider.as_deref(), cx);
 8320        }
 8321    }
 8322
 8323    pub fn context_menu_last(
 8324        &mut self,
 8325        _: &ContextMenuLast,
 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_last(self.completion_provider.as_deref(), cx);
 8331        }
 8332    }
 8333
 8334    pub fn move_to_previous_word_start(
 8335        &mut self,
 8336        _: &MoveToPreviousWordStart,
 8337        window: &mut Window,
 8338        cx: &mut Context<Self>,
 8339    ) {
 8340        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8341            s.move_cursors_with(|map, head, _| {
 8342                (
 8343                    movement::previous_word_start(map, head),
 8344                    SelectionGoal::None,
 8345                )
 8346            });
 8347        })
 8348    }
 8349
 8350    pub fn move_to_previous_subword_start(
 8351        &mut self,
 8352        _: &MoveToPreviousSubwordStart,
 8353        window: &mut Window,
 8354        cx: &mut Context<Self>,
 8355    ) {
 8356        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8357            s.move_cursors_with(|map, head, _| {
 8358                (
 8359                    movement::previous_subword_start(map, head),
 8360                    SelectionGoal::None,
 8361                )
 8362            });
 8363        })
 8364    }
 8365
 8366    pub fn select_to_previous_word_start(
 8367        &mut self,
 8368        _: &SelectToPreviousWordStart,
 8369        window: &mut Window,
 8370        cx: &mut Context<Self>,
 8371    ) {
 8372        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8373            s.move_heads_with(|map, head, _| {
 8374                (
 8375                    movement::previous_word_start(map, head),
 8376                    SelectionGoal::None,
 8377                )
 8378            });
 8379        })
 8380    }
 8381
 8382    pub fn select_to_previous_subword_start(
 8383        &mut self,
 8384        _: &SelectToPreviousSubwordStart,
 8385        window: &mut Window,
 8386        cx: &mut Context<Self>,
 8387    ) {
 8388        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8389            s.move_heads_with(|map, head, _| {
 8390                (
 8391                    movement::previous_subword_start(map, head),
 8392                    SelectionGoal::None,
 8393                )
 8394            });
 8395        })
 8396    }
 8397
 8398    pub fn delete_to_previous_word_start(
 8399        &mut self,
 8400        action: &DeleteToPreviousWordStart,
 8401        window: &mut Window,
 8402        cx: &mut Context<Self>,
 8403    ) {
 8404        self.transact(window, cx, |this, window, cx| {
 8405            this.select_autoclose_pair(window, cx);
 8406            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8407                let line_mode = s.line_mode;
 8408                s.move_with(|map, selection| {
 8409                    if selection.is_empty() && !line_mode {
 8410                        let cursor = if action.ignore_newlines {
 8411                            movement::previous_word_start(map, selection.head())
 8412                        } else {
 8413                            movement::previous_word_start_or_newline(map, selection.head())
 8414                        };
 8415                        selection.set_head(cursor, SelectionGoal::None);
 8416                    }
 8417                });
 8418            });
 8419            this.insert("", window, cx);
 8420        });
 8421    }
 8422
 8423    pub fn delete_to_previous_subword_start(
 8424        &mut self,
 8425        _: &DeleteToPreviousSubwordStart,
 8426        window: &mut Window,
 8427        cx: &mut Context<Self>,
 8428    ) {
 8429        self.transact(window, cx, |this, window, cx| {
 8430            this.select_autoclose_pair(window, cx);
 8431            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8432                let line_mode = s.line_mode;
 8433                s.move_with(|map, selection| {
 8434                    if selection.is_empty() && !line_mode {
 8435                        let cursor = movement::previous_subword_start(map, selection.head());
 8436                        selection.set_head(cursor, SelectionGoal::None);
 8437                    }
 8438                });
 8439            });
 8440            this.insert("", window, cx);
 8441        });
 8442    }
 8443
 8444    pub fn move_to_next_word_end(
 8445        &mut self,
 8446        _: &MoveToNextWordEnd,
 8447        window: &mut Window,
 8448        cx: &mut Context<Self>,
 8449    ) {
 8450        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8451            s.move_cursors_with(|map, head, _| {
 8452                (movement::next_word_end(map, head), SelectionGoal::None)
 8453            });
 8454        })
 8455    }
 8456
 8457    pub fn move_to_next_subword_end(
 8458        &mut self,
 8459        _: &MoveToNextSubwordEnd,
 8460        window: &mut Window,
 8461        cx: &mut Context<Self>,
 8462    ) {
 8463        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8464            s.move_cursors_with(|map, head, _| {
 8465                (movement::next_subword_end(map, head), SelectionGoal::None)
 8466            });
 8467        })
 8468    }
 8469
 8470    pub fn select_to_next_word_end(
 8471        &mut self,
 8472        _: &SelectToNextWordEnd,
 8473        window: &mut Window,
 8474        cx: &mut Context<Self>,
 8475    ) {
 8476        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8477            s.move_heads_with(|map, head, _| {
 8478                (movement::next_word_end(map, head), SelectionGoal::None)
 8479            });
 8480        })
 8481    }
 8482
 8483    pub fn select_to_next_subword_end(
 8484        &mut self,
 8485        _: &SelectToNextSubwordEnd,
 8486        window: &mut Window,
 8487        cx: &mut Context<Self>,
 8488    ) {
 8489        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8490            s.move_heads_with(|map, head, _| {
 8491                (movement::next_subword_end(map, head), SelectionGoal::None)
 8492            });
 8493        })
 8494    }
 8495
 8496    pub fn delete_to_next_word_end(
 8497        &mut self,
 8498        action: &DeleteToNextWordEnd,
 8499        window: &mut Window,
 8500        cx: &mut Context<Self>,
 8501    ) {
 8502        self.transact(window, cx, |this, window, cx| {
 8503            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8504                let line_mode = s.line_mode;
 8505                s.move_with(|map, selection| {
 8506                    if selection.is_empty() && !line_mode {
 8507                        let cursor = if action.ignore_newlines {
 8508                            movement::next_word_end(map, selection.head())
 8509                        } else {
 8510                            movement::next_word_end_or_newline(map, selection.head())
 8511                        };
 8512                        selection.set_head(cursor, SelectionGoal::None);
 8513                    }
 8514                });
 8515            });
 8516            this.insert("", window, cx);
 8517        });
 8518    }
 8519
 8520    pub fn delete_to_next_subword_end(
 8521        &mut self,
 8522        _: &DeleteToNextSubwordEnd,
 8523        window: &mut Window,
 8524        cx: &mut Context<Self>,
 8525    ) {
 8526        self.transact(window, cx, |this, window, cx| {
 8527            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8528                s.move_with(|map, selection| {
 8529                    if selection.is_empty() {
 8530                        let cursor = movement::next_subword_end(map, selection.head());
 8531                        selection.set_head(cursor, SelectionGoal::None);
 8532                    }
 8533                });
 8534            });
 8535            this.insert("", window, cx);
 8536        });
 8537    }
 8538
 8539    pub fn move_to_beginning_of_line(
 8540        &mut self,
 8541        action: &MoveToBeginningOfLine,
 8542        window: &mut Window,
 8543        cx: &mut Context<Self>,
 8544    ) {
 8545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8546            s.move_cursors_with(|map, head, _| {
 8547                (
 8548                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8549                    SelectionGoal::None,
 8550                )
 8551            });
 8552        })
 8553    }
 8554
 8555    pub fn select_to_beginning_of_line(
 8556        &mut self,
 8557        action: &SelectToBeginningOfLine,
 8558        window: &mut Window,
 8559        cx: &mut Context<Self>,
 8560    ) {
 8561        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8562            s.move_heads_with(|map, head, _| {
 8563                (
 8564                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8565                    SelectionGoal::None,
 8566                )
 8567            });
 8568        });
 8569    }
 8570
 8571    pub fn delete_to_beginning_of_line(
 8572        &mut self,
 8573        _: &DeleteToBeginningOfLine,
 8574        window: &mut Window,
 8575        cx: &mut Context<Self>,
 8576    ) {
 8577        self.transact(window, cx, |this, window, cx| {
 8578            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8579                s.move_with(|_, selection| {
 8580                    selection.reversed = true;
 8581                });
 8582            });
 8583
 8584            this.select_to_beginning_of_line(
 8585                &SelectToBeginningOfLine {
 8586                    stop_at_soft_wraps: false,
 8587                },
 8588                window,
 8589                cx,
 8590            );
 8591            this.backspace(&Backspace, window, cx);
 8592        });
 8593    }
 8594
 8595    pub fn move_to_end_of_line(
 8596        &mut self,
 8597        action: &MoveToEndOfLine,
 8598        window: &mut Window,
 8599        cx: &mut Context<Self>,
 8600    ) {
 8601        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8602            s.move_cursors_with(|map, head, _| {
 8603                (
 8604                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8605                    SelectionGoal::None,
 8606                )
 8607            });
 8608        })
 8609    }
 8610
 8611    pub fn select_to_end_of_line(
 8612        &mut self,
 8613        action: &SelectToEndOfLine,
 8614        window: &mut Window,
 8615        cx: &mut Context<Self>,
 8616    ) {
 8617        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8618            s.move_heads_with(|map, head, _| {
 8619                (
 8620                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8621                    SelectionGoal::None,
 8622                )
 8623            });
 8624        })
 8625    }
 8626
 8627    pub fn delete_to_end_of_line(
 8628        &mut self,
 8629        _: &DeleteToEndOfLine,
 8630        window: &mut Window,
 8631        cx: &mut Context<Self>,
 8632    ) {
 8633        self.transact(window, cx, |this, window, cx| {
 8634            this.select_to_end_of_line(
 8635                &SelectToEndOfLine {
 8636                    stop_at_soft_wraps: false,
 8637                },
 8638                window,
 8639                cx,
 8640            );
 8641            this.delete(&Delete, window, cx);
 8642        });
 8643    }
 8644
 8645    pub fn cut_to_end_of_line(
 8646        &mut self,
 8647        _: &CutToEndOfLine,
 8648        window: &mut Window,
 8649        cx: &mut Context<Self>,
 8650    ) {
 8651        self.transact(window, cx, |this, window, cx| {
 8652            this.select_to_end_of_line(
 8653                &SelectToEndOfLine {
 8654                    stop_at_soft_wraps: false,
 8655                },
 8656                window,
 8657                cx,
 8658            );
 8659            this.cut(&Cut, window, cx);
 8660        });
 8661    }
 8662
 8663    pub fn move_to_start_of_paragraph(
 8664        &mut self,
 8665        _: &MoveToStartOfParagraph,
 8666        window: &mut Window,
 8667        cx: &mut Context<Self>,
 8668    ) {
 8669        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8670            cx.propagate();
 8671            return;
 8672        }
 8673
 8674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8675            s.move_with(|map, selection| {
 8676                selection.collapse_to(
 8677                    movement::start_of_paragraph(map, selection.head(), 1),
 8678                    SelectionGoal::None,
 8679                )
 8680            });
 8681        })
 8682    }
 8683
 8684    pub fn move_to_end_of_paragraph(
 8685        &mut self,
 8686        _: &MoveToEndOfParagraph,
 8687        window: &mut Window,
 8688        cx: &mut Context<Self>,
 8689    ) {
 8690        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8691            cx.propagate();
 8692            return;
 8693        }
 8694
 8695        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8696            s.move_with(|map, selection| {
 8697                selection.collapse_to(
 8698                    movement::end_of_paragraph(map, selection.head(), 1),
 8699                    SelectionGoal::None,
 8700                )
 8701            });
 8702        })
 8703    }
 8704
 8705    pub fn select_to_start_of_paragraph(
 8706        &mut self,
 8707        _: &SelectToStartOfParagraph,
 8708        window: &mut Window,
 8709        cx: &mut Context<Self>,
 8710    ) {
 8711        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8712            cx.propagate();
 8713            return;
 8714        }
 8715
 8716        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8717            s.move_heads_with(|map, head, _| {
 8718                (
 8719                    movement::start_of_paragraph(map, head, 1),
 8720                    SelectionGoal::None,
 8721                )
 8722            });
 8723        })
 8724    }
 8725
 8726    pub fn select_to_end_of_paragraph(
 8727        &mut self,
 8728        _: &SelectToEndOfParagraph,
 8729        window: &mut Window,
 8730        cx: &mut Context<Self>,
 8731    ) {
 8732        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8733            cx.propagate();
 8734            return;
 8735        }
 8736
 8737        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8738            s.move_heads_with(|map, head, _| {
 8739                (
 8740                    movement::end_of_paragraph(map, head, 1),
 8741                    SelectionGoal::None,
 8742                )
 8743            });
 8744        })
 8745    }
 8746
 8747    pub fn move_to_beginning(
 8748        &mut self,
 8749        _: &MoveToBeginning,
 8750        window: &mut Window,
 8751        cx: &mut Context<Self>,
 8752    ) {
 8753        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8754            cx.propagate();
 8755            return;
 8756        }
 8757
 8758        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8759            s.select_ranges(vec![0..0]);
 8760        });
 8761    }
 8762
 8763    pub fn select_to_beginning(
 8764        &mut self,
 8765        _: &SelectToBeginning,
 8766        window: &mut Window,
 8767        cx: &mut Context<Self>,
 8768    ) {
 8769        let mut selection = self.selections.last::<Point>(cx);
 8770        selection.set_head(Point::zero(), SelectionGoal::None);
 8771
 8772        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8773            s.select(vec![selection]);
 8774        });
 8775    }
 8776
 8777    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8778        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8779            cx.propagate();
 8780            return;
 8781        }
 8782
 8783        let cursor = self.buffer.read(cx).read(cx).len();
 8784        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8785            s.select_ranges(vec![cursor..cursor])
 8786        });
 8787    }
 8788
 8789    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8790        self.nav_history = nav_history;
 8791    }
 8792
 8793    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8794        self.nav_history.as_ref()
 8795    }
 8796
 8797    fn push_to_nav_history(
 8798        &mut self,
 8799        cursor_anchor: Anchor,
 8800        new_position: Option<Point>,
 8801        cx: &mut Context<Self>,
 8802    ) {
 8803        if let Some(nav_history) = self.nav_history.as_mut() {
 8804            let buffer = self.buffer.read(cx).read(cx);
 8805            let cursor_position = cursor_anchor.to_point(&buffer);
 8806            let scroll_state = self.scroll_manager.anchor();
 8807            let scroll_top_row = scroll_state.top_row(&buffer);
 8808            drop(buffer);
 8809
 8810            if let Some(new_position) = new_position {
 8811                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8812                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8813                    return;
 8814                }
 8815            }
 8816
 8817            nav_history.push(
 8818                Some(NavigationData {
 8819                    cursor_anchor,
 8820                    cursor_position,
 8821                    scroll_anchor: scroll_state,
 8822                    scroll_top_row,
 8823                }),
 8824                cx,
 8825            );
 8826        }
 8827    }
 8828
 8829    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8830        let buffer = self.buffer.read(cx).snapshot(cx);
 8831        let mut selection = self.selections.first::<usize>(cx);
 8832        selection.set_head(buffer.len(), SelectionGoal::None);
 8833        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8834            s.select(vec![selection]);
 8835        });
 8836    }
 8837
 8838    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8839        let end = self.buffer.read(cx).read(cx).len();
 8840        self.change_selections(None, window, cx, |s| {
 8841            s.select_ranges(vec![0..end]);
 8842        });
 8843    }
 8844
 8845    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8846        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8847        let mut selections = self.selections.all::<Point>(cx);
 8848        let max_point = display_map.buffer_snapshot.max_point();
 8849        for selection in &mut selections {
 8850            let rows = selection.spanned_rows(true, &display_map);
 8851            selection.start = Point::new(rows.start.0, 0);
 8852            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8853            selection.reversed = false;
 8854        }
 8855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8856            s.select(selections);
 8857        });
 8858    }
 8859
 8860    pub fn split_selection_into_lines(
 8861        &mut self,
 8862        _: &SplitSelectionIntoLines,
 8863        window: &mut Window,
 8864        cx: &mut Context<Self>,
 8865    ) {
 8866        let mut to_unfold = Vec::new();
 8867        let mut new_selection_ranges = Vec::new();
 8868        {
 8869            let selections = self.selections.all::<Point>(cx);
 8870            let buffer = self.buffer.read(cx).read(cx);
 8871            for selection in selections {
 8872                for row in selection.start.row..selection.end.row {
 8873                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8874                    new_selection_ranges.push(cursor..cursor);
 8875                }
 8876                new_selection_ranges.push(selection.end..selection.end);
 8877                to_unfold.push(selection.start..selection.end);
 8878            }
 8879        }
 8880        self.unfold_ranges(&to_unfold, true, true, cx);
 8881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8882            s.select_ranges(new_selection_ranges);
 8883        });
 8884    }
 8885
 8886    pub fn add_selection_above(
 8887        &mut self,
 8888        _: &AddSelectionAbove,
 8889        window: &mut Window,
 8890        cx: &mut Context<Self>,
 8891    ) {
 8892        self.add_selection(true, window, cx);
 8893    }
 8894
 8895    pub fn add_selection_below(
 8896        &mut self,
 8897        _: &AddSelectionBelow,
 8898        window: &mut Window,
 8899        cx: &mut Context<Self>,
 8900    ) {
 8901        self.add_selection(false, window, cx);
 8902    }
 8903
 8904    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8906        let mut selections = self.selections.all::<Point>(cx);
 8907        let text_layout_details = self.text_layout_details(window);
 8908        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8909            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8910            let range = oldest_selection.display_range(&display_map).sorted();
 8911
 8912            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8913            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8914            let positions = start_x.min(end_x)..start_x.max(end_x);
 8915
 8916            selections.clear();
 8917            let mut stack = Vec::new();
 8918            for row in range.start.row().0..=range.end.row().0 {
 8919                if let Some(selection) = self.selections.build_columnar_selection(
 8920                    &display_map,
 8921                    DisplayRow(row),
 8922                    &positions,
 8923                    oldest_selection.reversed,
 8924                    &text_layout_details,
 8925                ) {
 8926                    stack.push(selection.id);
 8927                    selections.push(selection);
 8928                }
 8929            }
 8930
 8931            if above {
 8932                stack.reverse();
 8933            }
 8934
 8935            AddSelectionsState { above, stack }
 8936        });
 8937
 8938        let last_added_selection = *state.stack.last().unwrap();
 8939        let mut new_selections = Vec::new();
 8940        if above == state.above {
 8941            let end_row = if above {
 8942                DisplayRow(0)
 8943            } else {
 8944                display_map.max_point().row()
 8945            };
 8946
 8947            'outer: for selection in selections {
 8948                if selection.id == last_added_selection {
 8949                    let range = selection.display_range(&display_map).sorted();
 8950                    debug_assert_eq!(range.start.row(), range.end.row());
 8951                    let mut row = range.start.row();
 8952                    let positions =
 8953                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8954                            px(start)..px(end)
 8955                        } else {
 8956                            let start_x =
 8957                                display_map.x_for_display_point(range.start, &text_layout_details);
 8958                            let end_x =
 8959                                display_map.x_for_display_point(range.end, &text_layout_details);
 8960                            start_x.min(end_x)..start_x.max(end_x)
 8961                        };
 8962
 8963                    while row != end_row {
 8964                        if above {
 8965                            row.0 -= 1;
 8966                        } else {
 8967                            row.0 += 1;
 8968                        }
 8969
 8970                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8971                            &display_map,
 8972                            row,
 8973                            &positions,
 8974                            selection.reversed,
 8975                            &text_layout_details,
 8976                        ) {
 8977                            state.stack.push(new_selection.id);
 8978                            if above {
 8979                                new_selections.push(new_selection);
 8980                                new_selections.push(selection);
 8981                            } else {
 8982                                new_selections.push(selection);
 8983                                new_selections.push(new_selection);
 8984                            }
 8985
 8986                            continue 'outer;
 8987                        }
 8988                    }
 8989                }
 8990
 8991                new_selections.push(selection);
 8992            }
 8993        } else {
 8994            new_selections = selections;
 8995            new_selections.retain(|s| s.id != last_added_selection);
 8996            state.stack.pop();
 8997        }
 8998
 8999        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9000            s.select(new_selections);
 9001        });
 9002        if state.stack.len() > 1 {
 9003            self.add_selections_state = Some(state);
 9004        }
 9005    }
 9006
 9007    pub fn select_next_match_internal(
 9008        &mut self,
 9009        display_map: &DisplaySnapshot,
 9010        replace_newest: bool,
 9011        autoscroll: Option<Autoscroll>,
 9012        window: &mut Window,
 9013        cx: &mut Context<Self>,
 9014    ) -> Result<()> {
 9015        fn select_next_match_ranges(
 9016            this: &mut Editor,
 9017            range: Range<usize>,
 9018            replace_newest: bool,
 9019            auto_scroll: Option<Autoscroll>,
 9020            window: &mut Window,
 9021            cx: &mut Context<Editor>,
 9022        ) {
 9023            this.unfold_ranges(&[range.clone()], false, true, cx);
 9024            this.change_selections(auto_scroll, window, cx, |s| {
 9025                if replace_newest {
 9026                    s.delete(s.newest_anchor().id);
 9027                }
 9028                s.insert_range(range.clone());
 9029            });
 9030        }
 9031
 9032        let buffer = &display_map.buffer_snapshot;
 9033        let mut selections = self.selections.all::<usize>(cx);
 9034        if let Some(mut select_next_state) = self.select_next_state.take() {
 9035            let query = &select_next_state.query;
 9036            if !select_next_state.done {
 9037                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9038                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9039                let mut next_selected_range = None;
 9040
 9041                let bytes_after_last_selection =
 9042                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9043                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9044                let query_matches = query
 9045                    .stream_find_iter(bytes_after_last_selection)
 9046                    .map(|result| (last_selection.end, result))
 9047                    .chain(
 9048                        query
 9049                            .stream_find_iter(bytes_before_first_selection)
 9050                            .map(|result| (0, result)),
 9051                    );
 9052
 9053                for (start_offset, query_match) in query_matches {
 9054                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9055                    let offset_range =
 9056                        start_offset + query_match.start()..start_offset + query_match.end();
 9057                    let display_range = offset_range.start.to_display_point(display_map)
 9058                        ..offset_range.end.to_display_point(display_map);
 9059
 9060                    if !select_next_state.wordwise
 9061                        || (!movement::is_inside_word(display_map, display_range.start)
 9062                            && !movement::is_inside_word(display_map, display_range.end))
 9063                    {
 9064                        // TODO: This is n^2, because we might check all the selections
 9065                        if !selections
 9066                            .iter()
 9067                            .any(|selection| selection.range().overlaps(&offset_range))
 9068                        {
 9069                            next_selected_range = Some(offset_range);
 9070                            break;
 9071                        }
 9072                    }
 9073                }
 9074
 9075                if let Some(next_selected_range) = next_selected_range {
 9076                    select_next_match_ranges(
 9077                        self,
 9078                        next_selected_range,
 9079                        replace_newest,
 9080                        autoscroll,
 9081                        window,
 9082                        cx,
 9083                    );
 9084                } else {
 9085                    select_next_state.done = true;
 9086                }
 9087            }
 9088
 9089            self.select_next_state = Some(select_next_state);
 9090        } else {
 9091            let mut only_carets = true;
 9092            let mut same_text_selected = true;
 9093            let mut selected_text = None;
 9094
 9095            let mut selections_iter = selections.iter().peekable();
 9096            while let Some(selection) = selections_iter.next() {
 9097                if selection.start != selection.end {
 9098                    only_carets = false;
 9099                }
 9100
 9101                if same_text_selected {
 9102                    if selected_text.is_none() {
 9103                        selected_text =
 9104                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9105                    }
 9106
 9107                    if let Some(next_selection) = selections_iter.peek() {
 9108                        if next_selection.range().len() == selection.range().len() {
 9109                            let next_selected_text = buffer
 9110                                .text_for_range(next_selection.range())
 9111                                .collect::<String>();
 9112                            if Some(next_selected_text) != selected_text {
 9113                                same_text_selected = false;
 9114                                selected_text = None;
 9115                            }
 9116                        } else {
 9117                            same_text_selected = false;
 9118                            selected_text = None;
 9119                        }
 9120                    }
 9121                }
 9122            }
 9123
 9124            if only_carets {
 9125                for selection in &mut selections {
 9126                    let word_range = movement::surrounding_word(
 9127                        display_map,
 9128                        selection.start.to_display_point(display_map),
 9129                    );
 9130                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9131                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9132                    selection.goal = SelectionGoal::None;
 9133                    selection.reversed = false;
 9134                    select_next_match_ranges(
 9135                        self,
 9136                        selection.start..selection.end,
 9137                        replace_newest,
 9138                        autoscroll,
 9139                        window,
 9140                        cx,
 9141                    );
 9142                }
 9143
 9144                if selections.len() == 1 {
 9145                    let selection = selections
 9146                        .last()
 9147                        .expect("ensured that there's only one selection");
 9148                    let query = buffer
 9149                        .text_for_range(selection.start..selection.end)
 9150                        .collect::<String>();
 9151                    let is_empty = query.is_empty();
 9152                    let select_state = SelectNextState {
 9153                        query: AhoCorasick::new(&[query])?,
 9154                        wordwise: true,
 9155                        done: is_empty,
 9156                    };
 9157                    self.select_next_state = Some(select_state);
 9158                } else {
 9159                    self.select_next_state = None;
 9160                }
 9161            } else if let Some(selected_text) = selected_text {
 9162                self.select_next_state = Some(SelectNextState {
 9163                    query: AhoCorasick::new(&[selected_text])?,
 9164                    wordwise: false,
 9165                    done: false,
 9166                });
 9167                self.select_next_match_internal(
 9168                    display_map,
 9169                    replace_newest,
 9170                    autoscroll,
 9171                    window,
 9172                    cx,
 9173                )?;
 9174            }
 9175        }
 9176        Ok(())
 9177    }
 9178
 9179    pub fn select_all_matches(
 9180        &mut self,
 9181        _action: &SelectAllMatches,
 9182        window: &mut Window,
 9183        cx: &mut Context<Self>,
 9184    ) -> Result<()> {
 9185        self.push_to_selection_history();
 9186        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9187
 9188        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9189        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9190            return Ok(());
 9191        };
 9192        if select_next_state.done {
 9193            return Ok(());
 9194        }
 9195
 9196        let mut new_selections = self.selections.all::<usize>(cx);
 9197
 9198        let buffer = &display_map.buffer_snapshot;
 9199        let query_matches = select_next_state
 9200            .query
 9201            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9202
 9203        for query_match in query_matches {
 9204            let query_match = query_match.unwrap(); // can only fail due to I/O
 9205            let offset_range = query_match.start()..query_match.end();
 9206            let display_range = offset_range.start.to_display_point(&display_map)
 9207                ..offset_range.end.to_display_point(&display_map);
 9208
 9209            if !select_next_state.wordwise
 9210                || (!movement::is_inside_word(&display_map, display_range.start)
 9211                    && !movement::is_inside_word(&display_map, display_range.end))
 9212            {
 9213                self.selections.change_with(cx, |selections| {
 9214                    new_selections.push(Selection {
 9215                        id: selections.new_selection_id(),
 9216                        start: offset_range.start,
 9217                        end: offset_range.end,
 9218                        reversed: false,
 9219                        goal: SelectionGoal::None,
 9220                    });
 9221                });
 9222            }
 9223        }
 9224
 9225        new_selections.sort_by_key(|selection| selection.start);
 9226        let mut ix = 0;
 9227        while ix + 1 < new_selections.len() {
 9228            let current_selection = &new_selections[ix];
 9229            let next_selection = &new_selections[ix + 1];
 9230            if current_selection.range().overlaps(&next_selection.range()) {
 9231                if current_selection.id < next_selection.id {
 9232                    new_selections.remove(ix + 1);
 9233                } else {
 9234                    new_selections.remove(ix);
 9235                }
 9236            } else {
 9237                ix += 1;
 9238            }
 9239        }
 9240
 9241        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9242
 9243        for selection in new_selections.iter_mut() {
 9244            selection.reversed = reversed;
 9245        }
 9246
 9247        select_next_state.done = true;
 9248        self.unfold_ranges(
 9249            &new_selections
 9250                .iter()
 9251                .map(|selection| selection.range())
 9252                .collect::<Vec<_>>(),
 9253            false,
 9254            false,
 9255            cx,
 9256        );
 9257        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9258            selections.select(new_selections)
 9259        });
 9260
 9261        Ok(())
 9262    }
 9263
 9264    pub fn select_next(
 9265        &mut self,
 9266        action: &SelectNext,
 9267        window: &mut Window,
 9268        cx: &mut Context<Self>,
 9269    ) -> Result<()> {
 9270        self.push_to_selection_history();
 9271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9272        self.select_next_match_internal(
 9273            &display_map,
 9274            action.replace_newest,
 9275            Some(Autoscroll::newest()),
 9276            window,
 9277            cx,
 9278        )?;
 9279        Ok(())
 9280    }
 9281
 9282    pub fn select_previous(
 9283        &mut self,
 9284        action: &SelectPrevious,
 9285        window: &mut Window,
 9286        cx: &mut Context<Self>,
 9287    ) -> Result<()> {
 9288        self.push_to_selection_history();
 9289        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9290        let buffer = &display_map.buffer_snapshot;
 9291        let mut selections = self.selections.all::<usize>(cx);
 9292        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9293            let query = &select_prev_state.query;
 9294            if !select_prev_state.done {
 9295                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9296                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9297                let mut next_selected_range = None;
 9298                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9299                let bytes_before_last_selection =
 9300                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9301                let bytes_after_first_selection =
 9302                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9303                let query_matches = query
 9304                    .stream_find_iter(bytes_before_last_selection)
 9305                    .map(|result| (last_selection.start, result))
 9306                    .chain(
 9307                        query
 9308                            .stream_find_iter(bytes_after_first_selection)
 9309                            .map(|result| (buffer.len(), result)),
 9310                    );
 9311                for (end_offset, query_match) in query_matches {
 9312                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9313                    let offset_range =
 9314                        end_offset - query_match.end()..end_offset - query_match.start();
 9315                    let display_range = offset_range.start.to_display_point(&display_map)
 9316                        ..offset_range.end.to_display_point(&display_map);
 9317
 9318                    if !select_prev_state.wordwise
 9319                        || (!movement::is_inside_word(&display_map, display_range.start)
 9320                            && !movement::is_inside_word(&display_map, display_range.end))
 9321                    {
 9322                        next_selected_range = Some(offset_range);
 9323                        break;
 9324                    }
 9325                }
 9326
 9327                if let Some(next_selected_range) = next_selected_range {
 9328                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9329                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9330                        if action.replace_newest {
 9331                            s.delete(s.newest_anchor().id);
 9332                        }
 9333                        s.insert_range(next_selected_range);
 9334                    });
 9335                } else {
 9336                    select_prev_state.done = true;
 9337                }
 9338            }
 9339
 9340            self.select_prev_state = Some(select_prev_state);
 9341        } else {
 9342            let mut only_carets = true;
 9343            let mut same_text_selected = true;
 9344            let mut selected_text = None;
 9345
 9346            let mut selections_iter = selections.iter().peekable();
 9347            while let Some(selection) = selections_iter.next() {
 9348                if selection.start != selection.end {
 9349                    only_carets = false;
 9350                }
 9351
 9352                if same_text_selected {
 9353                    if selected_text.is_none() {
 9354                        selected_text =
 9355                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9356                    }
 9357
 9358                    if let Some(next_selection) = selections_iter.peek() {
 9359                        if next_selection.range().len() == selection.range().len() {
 9360                            let next_selected_text = buffer
 9361                                .text_for_range(next_selection.range())
 9362                                .collect::<String>();
 9363                            if Some(next_selected_text) != selected_text {
 9364                                same_text_selected = false;
 9365                                selected_text = None;
 9366                            }
 9367                        } else {
 9368                            same_text_selected = false;
 9369                            selected_text = None;
 9370                        }
 9371                    }
 9372                }
 9373            }
 9374
 9375            if only_carets {
 9376                for selection in &mut selections {
 9377                    let word_range = movement::surrounding_word(
 9378                        &display_map,
 9379                        selection.start.to_display_point(&display_map),
 9380                    );
 9381                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9382                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9383                    selection.goal = SelectionGoal::None;
 9384                    selection.reversed = false;
 9385                }
 9386                if selections.len() == 1 {
 9387                    let selection = selections
 9388                        .last()
 9389                        .expect("ensured that there's only one selection");
 9390                    let query = buffer
 9391                        .text_for_range(selection.start..selection.end)
 9392                        .collect::<String>();
 9393                    let is_empty = query.is_empty();
 9394                    let select_state = SelectNextState {
 9395                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9396                        wordwise: true,
 9397                        done: is_empty,
 9398                    };
 9399                    self.select_prev_state = Some(select_state);
 9400                } else {
 9401                    self.select_prev_state = None;
 9402                }
 9403
 9404                self.unfold_ranges(
 9405                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9406                    false,
 9407                    true,
 9408                    cx,
 9409                );
 9410                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9411                    s.select(selections);
 9412                });
 9413            } else if let Some(selected_text) = selected_text {
 9414                self.select_prev_state = Some(SelectNextState {
 9415                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9416                    wordwise: false,
 9417                    done: false,
 9418                });
 9419                self.select_previous(action, window, cx)?;
 9420            }
 9421        }
 9422        Ok(())
 9423    }
 9424
 9425    pub fn toggle_comments(
 9426        &mut self,
 9427        action: &ToggleComments,
 9428        window: &mut Window,
 9429        cx: &mut Context<Self>,
 9430    ) {
 9431        if self.read_only(cx) {
 9432            return;
 9433        }
 9434        let text_layout_details = &self.text_layout_details(window);
 9435        self.transact(window, cx, |this, window, cx| {
 9436            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9437            let mut edits = Vec::new();
 9438            let mut selection_edit_ranges = Vec::new();
 9439            let mut last_toggled_row = None;
 9440            let snapshot = this.buffer.read(cx).read(cx);
 9441            let empty_str: Arc<str> = Arc::default();
 9442            let mut suffixes_inserted = Vec::new();
 9443            let ignore_indent = action.ignore_indent;
 9444
 9445            fn comment_prefix_range(
 9446                snapshot: &MultiBufferSnapshot,
 9447                row: MultiBufferRow,
 9448                comment_prefix: &str,
 9449                comment_prefix_whitespace: &str,
 9450                ignore_indent: bool,
 9451            ) -> Range<Point> {
 9452                let indent_size = if ignore_indent {
 9453                    0
 9454                } else {
 9455                    snapshot.indent_size_for_line(row).len
 9456                };
 9457
 9458                let start = Point::new(row.0, indent_size);
 9459
 9460                let mut line_bytes = snapshot
 9461                    .bytes_in_range(start..snapshot.max_point())
 9462                    .flatten()
 9463                    .copied();
 9464
 9465                // If this line currently begins with the line comment prefix, then record
 9466                // the range containing the prefix.
 9467                if line_bytes
 9468                    .by_ref()
 9469                    .take(comment_prefix.len())
 9470                    .eq(comment_prefix.bytes())
 9471                {
 9472                    // Include any whitespace that matches the comment prefix.
 9473                    let matching_whitespace_len = line_bytes
 9474                        .zip(comment_prefix_whitespace.bytes())
 9475                        .take_while(|(a, b)| a == b)
 9476                        .count() as u32;
 9477                    let end = Point::new(
 9478                        start.row,
 9479                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9480                    );
 9481                    start..end
 9482                } else {
 9483                    start..start
 9484                }
 9485            }
 9486
 9487            fn comment_suffix_range(
 9488                snapshot: &MultiBufferSnapshot,
 9489                row: MultiBufferRow,
 9490                comment_suffix: &str,
 9491                comment_suffix_has_leading_space: bool,
 9492            ) -> Range<Point> {
 9493                let end = Point::new(row.0, snapshot.line_len(row));
 9494                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9495
 9496                let mut line_end_bytes = snapshot
 9497                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9498                    .flatten()
 9499                    .copied();
 9500
 9501                let leading_space_len = if suffix_start_column > 0
 9502                    && line_end_bytes.next() == Some(b' ')
 9503                    && comment_suffix_has_leading_space
 9504                {
 9505                    1
 9506                } else {
 9507                    0
 9508                };
 9509
 9510                // If this line currently begins with the line comment prefix, then record
 9511                // the range containing the prefix.
 9512                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9513                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9514                    start..end
 9515                } else {
 9516                    end..end
 9517                }
 9518            }
 9519
 9520            // TODO: Handle selections that cross excerpts
 9521            for selection in &mut selections {
 9522                let start_column = snapshot
 9523                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9524                    .len;
 9525                let language = if let Some(language) =
 9526                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9527                {
 9528                    language
 9529                } else {
 9530                    continue;
 9531                };
 9532
 9533                selection_edit_ranges.clear();
 9534
 9535                // If multiple selections contain a given row, avoid processing that
 9536                // row more than once.
 9537                let mut start_row = MultiBufferRow(selection.start.row);
 9538                if last_toggled_row == Some(start_row) {
 9539                    start_row = start_row.next_row();
 9540                }
 9541                let end_row =
 9542                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9543                        MultiBufferRow(selection.end.row - 1)
 9544                    } else {
 9545                        MultiBufferRow(selection.end.row)
 9546                    };
 9547                last_toggled_row = Some(end_row);
 9548
 9549                if start_row > end_row {
 9550                    continue;
 9551                }
 9552
 9553                // If the language has line comments, toggle those.
 9554                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9555
 9556                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9557                if ignore_indent {
 9558                    full_comment_prefixes = full_comment_prefixes
 9559                        .into_iter()
 9560                        .map(|s| Arc::from(s.trim_end()))
 9561                        .collect();
 9562                }
 9563
 9564                if !full_comment_prefixes.is_empty() {
 9565                    let first_prefix = full_comment_prefixes
 9566                        .first()
 9567                        .expect("prefixes is non-empty");
 9568                    let prefix_trimmed_lengths = full_comment_prefixes
 9569                        .iter()
 9570                        .map(|p| p.trim_end_matches(' ').len())
 9571                        .collect::<SmallVec<[usize; 4]>>();
 9572
 9573                    let mut all_selection_lines_are_comments = true;
 9574
 9575                    for row in start_row.0..=end_row.0 {
 9576                        let row = MultiBufferRow(row);
 9577                        if start_row < end_row && snapshot.is_line_blank(row) {
 9578                            continue;
 9579                        }
 9580
 9581                        let prefix_range = full_comment_prefixes
 9582                            .iter()
 9583                            .zip(prefix_trimmed_lengths.iter().copied())
 9584                            .map(|(prefix, trimmed_prefix_len)| {
 9585                                comment_prefix_range(
 9586                                    snapshot.deref(),
 9587                                    row,
 9588                                    &prefix[..trimmed_prefix_len],
 9589                                    &prefix[trimmed_prefix_len..],
 9590                                    ignore_indent,
 9591                                )
 9592                            })
 9593                            .max_by_key(|range| range.end.column - range.start.column)
 9594                            .expect("prefixes is non-empty");
 9595
 9596                        if prefix_range.is_empty() {
 9597                            all_selection_lines_are_comments = false;
 9598                        }
 9599
 9600                        selection_edit_ranges.push(prefix_range);
 9601                    }
 9602
 9603                    if all_selection_lines_are_comments {
 9604                        edits.extend(
 9605                            selection_edit_ranges
 9606                                .iter()
 9607                                .cloned()
 9608                                .map(|range| (range, empty_str.clone())),
 9609                        );
 9610                    } else {
 9611                        let min_column = selection_edit_ranges
 9612                            .iter()
 9613                            .map(|range| range.start.column)
 9614                            .min()
 9615                            .unwrap_or(0);
 9616                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9617                            let position = Point::new(range.start.row, min_column);
 9618                            (position..position, first_prefix.clone())
 9619                        }));
 9620                    }
 9621                } else if let Some((full_comment_prefix, comment_suffix)) =
 9622                    language.block_comment_delimiters()
 9623                {
 9624                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9625                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9626                    let prefix_range = comment_prefix_range(
 9627                        snapshot.deref(),
 9628                        start_row,
 9629                        comment_prefix,
 9630                        comment_prefix_whitespace,
 9631                        ignore_indent,
 9632                    );
 9633                    let suffix_range = comment_suffix_range(
 9634                        snapshot.deref(),
 9635                        end_row,
 9636                        comment_suffix.trim_start_matches(' '),
 9637                        comment_suffix.starts_with(' '),
 9638                    );
 9639
 9640                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9641                        edits.push((
 9642                            prefix_range.start..prefix_range.start,
 9643                            full_comment_prefix.clone(),
 9644                        ));
 9645                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9646                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9647                    } else {
 9648                        edits.push((prefix_range, empty_str.clone()));
 9649                        edits.push((suffix_range, empty_str.clone()));
 9650                    }
 9651                } else {
 9652                    continue;
 9653                }
 9654            }
 9655
 9656            drop(snapshot);
 9657            this.buffer.update(cx, |buffer, cx| {
 9658                buffer.edit(edits, None, cx);
 9659            });
 9660
 9661            // Adjust selections so that they end before any comment suffixes that
 9662            // were inserted.
 9663            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9664            let mut selections = this.selections.all::<Point>(cx);
 9665            let snapshot = this.buffer.read(cx).read(cx);
 9666            for selection in &mut selections {
 9667                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9668                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9669                        Ordering::Less => {
 9670                            suffixes_inserted.next();
 9671                            continue;
 9672                        }
 9673                        Ordering::Greater => break,
 9674                        Ordering::Equal => {
 9675                            if selection.end.column == snapshot.line_len(row) {
 9676                                if selection.is_empty() {
 9677                                    selection.start.column -= suffix_len as u32;
 9678                                }
 9679                                selection.end.column -= suffix_len as u32;
 9680                            }
 9681                            break;
 9682                        }
 9683                    }
 9684                }
 9685            }
 9686
 9687            drop(snapshot);
 9688            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9689                s.select(selections)
 9690            });
 9691
 9692            let selections = this.selections.all::<Point>(cx);
 9693            let selections_on_single_row = selections.windows(2).all(|selections| {
 9694                selections[0].start.row == selections[1].start.row
 9695                    && selections[0].end.row == selections[1].end.row
 9696                    && selections[0].start.row == selections[0].end.row
 9697            });
 9698            let selections_selecting = selections
 9699                .iter()
 9700                .any(|selection| selection.start != selection.end);
 9701            let advance_downwards = action.advance_downwards
 9702                && selections_on_single_row
 9703                && !selections_selecting
 9704                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9705
 9706            if advance_downwards {
 9707                let snapshot = this.buffer.read(cx).snapshot(cx);
 9708
 9709                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9710                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9711                        let mut point = display_point.to_point(display_snapshot);
 9712                        point.row += 1;
 9713                        point = snapshot.clip_point(point, Bias::Left);
 9714                        let display_point = point.to_display_point(display_snapshot);
 9715                        let goal = SelectionGoal::HorizontalPosition(
 9716                            display_snapshot
 9717                                .x_for_display_point(display_point, text_layout_details)
 9718                                .into(),
 9719                        );
 9720                        (display_point, goal)
 9721                    })
 9722                });
 9723            }
 9724        });
 9725    }
 9726
 9727    pub fn select_enclosing_symbol(
 9728        &mut self,
 9729        _: &SelectEnclosingSymbol,
 9730        window: &mut Window,
 9731        cx: &mut Context<Self>,
 9732    ) {
 9733        let buffer = self.buffer.read(cx).snapshot(cx);
 9734        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9735
 9736        fn update_selection(
 9737            selection: &Selection<usize>,
 9738            buffer_snap: &MultiBufferSnapshot,
 9739        ) -> Option<Selection<usize>> {
 9740            let cursor = selection.head();
 9741            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9742            for symbol in symbols.iter().rev() {
 9743                let start = symbol.range.start.to_offset(buffer_snap);
 9744                let end = symbol.range.end.to_offset(buffer_snap);
 9745                let new_range = start..end;
 9746                if start < selection.start || end > selection.end {
 9747                    return Some(Selection {
 9748                        id: selection.id,
 9749                        start: new_range.start,
 9750                        end: new_range.end,
 9751                        goal: SelectionGoal::None,
 9752                        reversed: selection.reversed,
 9753                    });
 9754                }
 9755            }
 9756            None
 9757        }
 9758
 9759        let mut selected_larger_symbol = false;
 9760        let new_selections = old_selections
 9761            .iter()
 9762            .map(|selection| match update_selection(selection, &buffer) {
 9763                Some(new_selection) => {
 9764                    if new_selection.range() != selection.range() {
 9765                        selected_larger_symbol = true;
 9766                    }
 9767                    new_selection
 9768                }
 9769                None => selection.clone(),
 9770            })
 9771            .collect::<Vec<_>>();
 9772
 9773        if selected_larger_symbol {
 9774            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9775                s.select(new_selections);
 9776            });
 9777        }
 9778    }
 9779
 9780    pub fn select_larger_syntax_node(
 9781        &mut self,
 9782        _: &SelectLargerSyntaxNode,
 9783        window: &mut Window,
 9784        cx: &mut Context<Self>,
 9785    ) {
 9786        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9787        let buffer = self.buffer.read(cx).snapshot(cx);
 9788        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9789
 9790        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9791        let mut selected_larger_node = false;
 9792        let new_selections = old_selections
 9793            .iter()
 9794            .map(|selection| {
 9795                let old_range = selection.start..selection.end;
 9796                let mut new_range = old_range.clone();
 9797                let mut new_node = None;
 9798                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9799                {
 9800                    new_node = Some(node);
 9801                    new_range = containing_range;
 9802                    if !display_map.intersects_fold(new_range.start)
 9803                        && !display_map.intersects_fold(new_range.end)
 9804                    {
 9805                        break;
 9806                    }
 9807                }
 9808
 9809                if let Some(node) = new_node {
 9810                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9811                    // nodes. Parent and grandparent are also logged because this operation will not
 9812                    // visit nodes that have the same range as their parent.
 9813                    log::info!("Node: {node:?}");
 9814                    let parent = node.parent();
 9815                    log::info!("Parent: {parent:?}");
 9816                    let grandparent = parent.and_then(|x| x.parent());
 9817                    log::info!("Grandparent: {grandparent:?}");
 9818                }
 9819
 9820                selected_larger_node |= new_range != old_range;
 9821                Selection {
 9822                    id: selection.id,
 9823                    start: new_range.start,
 9824                    end: new_range.end,
 9825                    goal: SelectionGoal::None,
 9826                    reversed: selection.reversed,
 9827                }
 9828            })
 9829            .collect::<Vec<_>>();
 9830
 9831        if selected_larger_node {
 9832            stack.push(old_selections);
 9833            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9834                s.select(new_selections);
 9835            });
 9836        }
 9837        self.select_larger_syntax_node_stack = stack;
 9838    }
 9839
 9840    pub fn select_smaller_syntax_node(
 9841        &mut self,
 9842        _: &SelectSmallerSyntaxNode,
 9843        window: &mut Window,
 9844        cx: &mut Context<Self>,
 9845    ) {
 9846        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9847        if let Some(selections) = stack.pop() {
 9848            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9849                s.select(selections.to_vec());
 9850            });
 9851        }
 9852        self.select_larger_syntax_node_stack = stack;
 9853    }
 9854
 9855    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9856        if !EditorSettings::get_global(cx).gutter.runnables {
 9857            self.clear_tasks();
 9858            return Task::ready(());
 9859        }
 9860        let project = self.project.as_ref().map(Entity::downgrade);
 9861        cx.spawn_in(window, |this, mut cx| async move {
 9862            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9863            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9864                return;
 9865            };
 9866            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9867                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9868            }) else {
 9869                return;
 9870            };
 9871
 9872            let hide_runnables = project
 9873                .update(&mut cx, |project, cx| {
 9874                    // Do not display any test indicators in non-dev server remote projects.
 9875                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9876                })
 9877                .unwrap_or(true);
 9878            if hide_runnables {
 9879                return;
 9880            }
 9881            let new_rows =
 9882                cx.background_executor()
 9883                    .spawn({
 9884                        let snapshot = display_snapshot.clone();
 9885                        async move {
 9886                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9887                        }
 9888                    })
 9889                    .await;
 9890
 9891            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9892            this.update(&mut cx, |this, _| {
 9893                this.clear_tasks();
 9894                for (key, value) in rows {
 9895                    this.insert_tasks(key, value);
 9896                }
 9897            })
 9898            .ok();
 9899        })
 9900    }
 9901    fn fetch_runnable_ranges(
 9902        snapshot: &DisplaySnapshot,
 9903        range: Range<Anchor>,
 9904    ) -> Vec<language::RunnableRange> {
 9905        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9906    }
 9907
 9908    fn runnable_rows(
 9909        project: Entity<Project>,
 9910        snapshot: DisplaySnapshot,
 9911        runnable_ranges: Vec<RunnableRange>,
 9912        mut cx: AsyncWindowContext,
 9913    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9914        runnable_ranges
 9915            .into_iter()
 9916            .filter_map(|mut runnable| {
 9917                let tasks = cx
 9918                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9919                    .ok()?;
 9920                if tasks.is_empty() {
 9921                    return None;
 9922                }
 9923
 9924                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9925
 9926                let row = snapshot
 9927                    .buffer_snapshot
 9928                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9929                    .1
 9930                    .start
 9931                    .row;
 9932
 9933                let context_range =
 9934                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9935                Some((
 9936                    (runnable.buffer_id, row),
 9937                    RunnableTasks {
 9938                        templates: tasks,
 9939                        offset: MultiBufferOffset(runnable.run_range.start),
 9940                        context_range,
 9941                        column: point.column,
 9942                        extra_variables: runnable.extra_captures,
 9943                    },
 9944                ))
 9945            })
 9946            .collect()
 9947    }
 9948
 9949    fn templates_with_tags(
 9950        project: &Entity<Project>,
 9951        runnable: &mut Runnable,
 9952        cx: &mut App,
 9953    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9954        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9955            let (worktree_id, file) = project
 9956                .buffer_for_id(runnable.buffer, cx)
 9957                .and_then(|buffer| buffer.read(cx).file())
 9958                .map(|file| (file.worktree_id(cx), file.clone()))
 9959                .unzip();
 9960
 9961            (
 9962                project.task_store().read(cx).task_inventory().cloned(),
 9963                worktree_id,
 9964                file,
 9965            )
 9966        });
 9967
 9968        let tags = mem::take(&mut runnable.tags);
 9969        let mut tags: Vec<_> = tags
 9970            .into_iter()
 9971            .flat_map(|tag| {
 9972                let tag = tag.0.clone();
 9973                inventory
 9974                    .as_ref()
 9975                    .into_iter()
 9976                    .flat_map(|inventory| {
 9977                        inventory.read(cx).list_tasks(
 9978                            file.clone(),
 9979                            Some(runnable.language.clone()),
 9980                            worktree_id,
 9981                            cx,
 9982                        )
 9983                    })
 9984                    .filter(move |(_, template)| {
 9985                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9986                    })
 9987            })
 9988            .sorted_by_key(|(kind, _)| kind.to_owned())
 9989            .collect();
 9990        if let Some((leading_tag_source, _)) = tags.first() {
 9991            // Strongest source wins; if we have worktree tag binding, prefer that to
 9992            // global and language bindings;
 9993            // if we have a global binding, prefer that to language binding.
 9994            let first_mismatch = tags
 9995                .iter()
 9996                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9997            if let Some(index) = first_mismatch {
 9998                tags.truncate(index);
 9999            }
10000        }
10001
10002        tags
10003    }
10004
10005    pub fn move_to_enclosing_bracket(
10006        &mut self,
10007        _: &MoveToEnclosingBracket,
10008        window: &mut Window,
10009        cx: &mut Context<Self>,
10010    ) {
10011        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10012            s.move_offsets_with(|snapshot, selection| {
10013                let Some(enclosing_bracket_ranges) =
10014                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10015                else {
10016                    return;
10017                };
10018
10019                let mut best_length = usize::MAX;
10020                let mut best_inside = false;
10021                let mut best_in_bracket_range = false;
10022                let mut best_destination = None;
10023                for (open, close) in enclosing_bracket_ranges {
10024                    let close = close.to_inclusive();
10025                    let length = close.end() - open.start;
10026                    let inside = selection.start >= open.end && selection.end <= *close.start();
10027                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10028                        || close.contains(&selection.head());
10029
10030                    // If best is next to a bracket and current isn't, skip
10031                    if !in_bracket_range && best_in_bracket_range {
10032                        continue;
10033                    }
10034
10035                    // Prefer smaller lengths unless best is inside and current isn't
10036                    if length > best_length && (best_inside || !inside) {
10037                        continue;
10038                    }
10039
10040                    best_length = length;
10041                    best_inside = inside;
10042                    best_in_bracket_range = in_bracket_range;
10043                    best_destination = Some(
10044                        if close.contains(&selection.start) && close.contains(&selection.end) {
10045                            if inside {
10046                                open.end
10047                            } else {
10048                                open.start
10049                            }
10050                        } else if inside {
10051                            *close.start()
10052                        } else {
10053                            *close.end()
10054                        },
10055                    );
10056                }
10057
10058                if let Some(destination) = best_destination {
10059                    selection.collapse_to(destination, SelectionGoal::None);
10060                }
10061            })
10062        });
10063    }
10064
10065    pub fn undo_selection(
10066        &mut self,
10067        _: &UndoSelection,
10068        window: &mut Window,
10069        cx: &mut Context<Self>,
10070    ) {
10071        self.end_selection(window, cx);
10072        self.selection_history.mode = SelectionHistoryMode::Undoing;
10073        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10074            self.change_selections(None, window, cx, |s| {
10075                s.select_anchors(entry.selections.to_vec())
10076            });
10077            self.select_next_state = entry.select_next_state;
10078            self.select_prev_state = entry.select_prev_state;
10079            self.add_selections_state = entry.add_selections_state;
10080            self.request_autoscroll(Autoscroll::newest(), cx);
10081        }
10082        self.selection_history.mode = SelectionHistoryMode::Normal;
10083    }
10084
10085    pub fn redo_selection(
10086        &mut self,
10087        _: &RedoSelection,
10088        window: &mut Window,
10089        cx: &mut Context<Self>,
10090    ) {
10091        self.end_selection(window, cx);
10092        self.selection_history.mode = SelectionHistoryMode::Redoing;
10093        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10094            self.change_selections(None, window, cx, |s| {
10095                s.select_anchors(entry.selections.to_vec())
10096            });
10097            self.select_next_state = entry.select_next_state;
10098            self.select_prev_state = entry.select_prev_state;
10099            self.add_selections_state = entry.add_selections_state;
10100            self.request_autoscroll(Autoscroll::newest(), cx);
10101        }
10102        self.selection_history.mode = SelectionHistoryMode::Normal;
10103    }
10104
10105    pub fn expand_excerpts(
10106        &mut self,
10107        action: &ExpandExcerpts,
10108        _: &mut Window,
10109        cx: &mut Context<Self>,
10110    ) {
10111        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10112    }
10113
10114    pub fn expand_excerpts_down(
10115        &mut self,
10116        action: &ExpandExcerptsDown,
10117        _: &mut Window,
10118        cx: &mut Context<Self>,
10119    ) {
10120        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10121    }
10122
10123    pub fn expand_excerpts_up(
10124        &mut self,
10125        action: &ExpandExcerptsUp,
10126        _: &mut Window,
10127        cx: &mut Context<Self>,
10128    ) {
10129        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10130    }
10131
10132    pub fn expand_excerpts_for_direction(
10133        &mut self,
10134        lines: u32,
10135        direction: ExpandExcerptDirection,
10136
10137        cx: &mut Context<Self>,
10138    ) {
10139        let selections = self.selections.disjoint_anchors();
10140
10141        let lines = if lines == 0 {
10142            EditorSettings::get_global(cx).expand_excerpt_lines
10143        } else {
10144            lines
10145        };
10146
10147        self.buffer.update(cx, |buffer, cx| {
10148            let snapshot = buffer.snapshot(cx);
10149            let mut excerpt_ids = selections
10150                .iter()
10151                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10152                .collect::<Vec<_>>();
10153            excerpt_ids.sort();
10154            excerpt_ids.dedup();
10155            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10156        })
10157    }
10158
10159    pub fn expand_excerpt(
10160        &mut self,
10161        excerpt: ExcerptId,
10162        direction: ExpandExcerptDirection,
10163        cx: &mut Context<Self>,
10164    ) {
10165        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10166        self.buffer.update(cx, |buffer, cx| {
10167            buffer.expand_excerpts([excerpt], lines, direction, cx)
10168        })
10169    }
10170
10171    pub fn go_to_singleton_buffer_point(
10172        &mut self,
10173        point: Point,
10174        window: &mut Window,
10175        cx: &mut Context<Self>,
10176    ) {
10177        self.go_to_singleton_buffer_range(point..point, window, cx);
10178    }
10179
10180    pub fn go_to_singleton_buffer_range(
10181        &mut self,
10182        range: Range<Point>,
10183        window: &mut Window,
10184        cx: &mut Context<Self>,
10185    ) {
10186        let multibuffer = self.buffer().read(cx);
10187        let Some(buffer) = multibuffer.as_singleton() else {
10188            return;
10189        };
10190        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10191            return;
10192        };
10193        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10194            return;
10195        };
10196        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10197            s.select_anchor_ranges([start..end])
10198        });
10199    }
10200
10201    fn go_to_diagnostic(
10202        &mut self,
10203        _: &GoToDiagnostic,
10204        window: &mut Window,
10205        cx: &mut Context<Self>,
10206    ) {
10207        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10208    }
10209
10210    fn go_to_prev_diagnostic(
10211        &mut self,
10212        _: &GoToPrevDiagnostic,
10213        window: &mut Window,
10214        cx: &mut Context<Self>,
10215    ) {
10216        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10217    }
10218
10219    pub fn go_to_diagnostic_impl(
10220        &mut self,
10221        direction: Direction,
10222        window: &mut Window,
10223        cx: &mut Context<Self>,
10224    ) {
10225        let buffer = self.buffer.read(cx).snapshot(cx);
10226        let selection = self.selections.newest::<usize>(cx);
10227
10228        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10229        if direction == Direction::Next {
10230            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10231                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10232                    return;
10233                };
10234                self.activate_diagnostics(
10235                    buffer_id,
10236                    popover.local_diagnostic.diagnostic.group_id,
10237                    window,
10238                    cx,
10239                );
10240                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10241                    let primary_range_start = active_diagnostics.primary_range.start;
10242                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10243                        let mut new_selection = s.newest_anchor().clone();
10244                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10245                        s.select_anchors(vec![new_selection.clone()]);
10246                    });
10247                    self.refresh_inline_completion(false, true, window, cx);
10248                }
10249                return;
10250            }
10251        }
10252
10253        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10254            active_diagnostics
10255                .primary_range
10256                .to_offset(&buffer)
10257                .to_inclusive()
10258        });
10259        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10260            if active_primary_range.contains(&selection.head()) {
10261                *active_primary_range.start()
10262            } else {
10263                selection.head()
10264            }
10265        } else {
10266            selection.head()
10267        };
10268        let snapshot = self.snapshot(window, cx);
10269        loop {
10270            let mut diagnostics;
10271            if direction == Direction::Prev {
10272                diagnostics = buffer
10273                    .diagnostics_in_range::<usize>(0..search_start)
10274                    .collect::<Vec<_>>();
10275                diagnostics.reverse();
10276            } else {
10277                diagnostics = buffer
10278                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10279                    .collect::<Vec<_>>();
10280            };
10281            let group = diagnostics
10282                .into_iter()
10283                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10284                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10285                // be sorted in a stable way
10286                // skip until we are at current active diagnostic, if it exists
10287                .skip_while(|entry| {
10288                    let is_in_range = match direction {
10289                        Direction::Prev => entry.range.end > search_start,
10290                        Direction::Next => entry.range.start < search_start,
10291                    };
10292                    is_in_range
10293                        && self
10294                            .active_diagnostics
10295                            .as_ref()
10296                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10297                })
10298                .find_map(|entry| {
10299                    if entry.diagnostic.is_primary
10300                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10301                        && entry.range.start != entry.range.end
10302                        // if we match with the active diagnostic, skip it
10303                        && Some(entry.diagnostic.group_id)
10304                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10305                    {
10306                        Some((entry.range, entry.diagnostic.group_id))
10307                    } else {
10308                        None
10309                    }
10310                });
10311
10312            if let Some((primary_range, group_id)) = group {
10313                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10314                    return;
10315                };
10316                self.activate_diagnostics(buffer_id, group_id, window, cx);
10317                if self.active_diagnostics.is_some() {
10318                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10319                        s.select(vec![Selection {
10320                            id: selection.id,
10321                            start: primary_range.start,
10322                            end: primary_range.start,
10323                            reversed: false,
10324                            goal: SelectionGoal::None,
10325                        }]);
10326                    });
10327                    self.refresh_inline_completion(false, true, window, cx);
10328                }
10329                break;
10330            } else {
10331                // Cycle around to the start of the buffer, potentially moving back to the start of
10332                // the currently active diagnostic.
10333                active_primary_range.take();
10334                if direction == Direction::Prev {
10335                    if search_start == buffer.len() {
10336                        break;
10337                    } else {
10338                        search_start = buffer.len();
10339                    }
10340                } else if search_start == 0 {
10341                    break;
10342                } else {
10343                    search_start = 0;
10344                }
10345            }
10346        }
10347    }
10348
10349    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10350        let snapshot = self.snapshot(window, cx);
10351        let selection = self.selections.newest::<Point>(cx);
10352        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10353    }
10354
10355    fn go_to_hunk_after_position(
10356        &mut self,
10357        snapshot: &EditorSnapshot,
10358        position: Point,
10359        window: &mut Window,
10360        cx: &mut Context<Editor>,
10361    ) -> Option<MultiBufferDiffHunk> {
10362        let mut hunk = snapshot
10363            .buffer_snapshot
10364            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10365            .find(|hunk| hunk.row_range.start.0 > position.row);
10366        if hunk.is_none() {
10367            hunk = snapshot
10368                .buffer_snapshot
10369                .diff_hunks_in_range(Point::zero()..position)
10370                .find(|hunk| hunk.row_range.end.0 < position.row)
10371        }
10372        if let Some(hunk) = &hunk {
10373            let destination = Point::new(hunk.row_range.start.0, 0);
10374            self.unfold_ranges(&[destination..destination], false, false, cx);
10375            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10376                s.select_ranges(vec![destination..destination]);
10377            });
10378        }
10379
10380        hunk
10381    }
10382
10383    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10384        let snapshot = self.snapshot(window, cx);
10385        let selection = self.selections.newest::<Point>(cx);
10386        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10387    }
10388
10389    fn go_to_hunk_before_position(
10390        &mut self,
10391        snapshot: &EditorSnapshot,
10392        position: Point,
10393        window: &mut Window,
10394        cx: &mut Context<Editor>,
10395    ) -> Option<MultiBufferDiffHunk> {
10396        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10397        if hunk.is_none() {
10398            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10399        }
10400        if let Some(hunk) = &hunk {
10401            let destination = Point::new(hunk.row_range.start.0, 0);
10402            self.unfold_ranges(&[destination..destination], false, false, cx);
10403            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10404                s.select_ranges(vec![destination..destination]);
10405            });
10406        }
10407
10408        hunk
10409    }
10410
10411    pub fn go_to_definition(
10412        &mut self,
10413        _: &GoToDefinition,
10414        window: &mut Window,
10415        cx: &mut Context<Self>,
10416    ) -> Task<Result<Navigated>> {
10417        let definition =
10418            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10419        cx.spawn_in(window, |editor, mut cx| async move {
10420            if definition.await? == Navigated::Yes {
10421                return Ok(Navigated::Yes);
10422            }
10423            match editor.update_in(&mut cx, |editor, window, cx| {
10424                editor.find_all_references(&FindAllReferences, window, cx)
10425            })? {
10426                Some(references) => references.await,
10427                None => Ok(Navigated::No),
10428            }
10429        })
10430    }
10431
10432    pub fn go_to_declaration(
10433        &mut self,
10434        _: &GoToDeclaration,
10435        window: &mut Window,
10436        cx: &mut Context<Self>,
10437    ) -> Task<Result<Navigated>> {
10438        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10439    }
10440
10441    pub fn go_to_declaration_split(
10442        &mut self,
10443        _: &GoToDeclaration,
10444        window: &mut Window,
10445        cx: &mut Context<Self>,
10446    ) -> Task<Result<Navigated>> {
10447        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10448    }
10449
10450    pub fn go_to_implementation(
10451        &mut self,
10452        _: &GoToImplementation,
10453        window: &mut Window,
10454        cx: &mut Context<Self>,
10455    ) -> Task<Result<Navigated>> {
10456        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10457    }
10458
10459    pub fn go_to_implementation_split(
10460        &mut self,
10461        _: &GoToImplementationSplit,
10462        window: &mut Window,
10463        cx: &mut Context<Self>,
10464    ) -> Task<Result<Navigated>> {
10465        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10466    }
10467
10468    pub fn go_to_type_definition(
10469        &mut self,
10470        _: &GoToTypeDefinition,
10471        window: &mut Window,
10472        cx: &mut Context<Self>,
10473    ) -> Task<Result<Navigated>> {
10474        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10475    }
10476
10477    pub fn go_to_definition_split(
10478        &mut self,
10479        _: &GoToDefinitionSplit,
10480        window: &mut Window,
10481        cx: &mut Context<Self>,
10482    ) -> Task<Result<Navigated>> {
10483        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10484    }
10485
10486    pub fn go_to_type_definition_split(
10487        &mut self,
10488        _: &GoToTypeDefinitionSplit,
10489        window: &mut Window,
10490        cx: &mut Context<Self>,
10491    ) -> Task<Result<Navigated>> {
10492        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10493    }
10494
10495    fn go_to_definition_of_kind(
10496        &mut self,
10497        kind: GotoDefinitionKind,
10498        split: bool,
10499        window: &mut Window,
10500        cx: &mut Context<Self>,
10501    ) -> Task<Result<Navigated>> {
10502        let Some(provider) = self.semantics_provider.clone() else {
10503            return Task::ready(Ok(Navigated::No));
10504        };
10505        let head = self.selections.newest::<usize>(cx).head();
10506        let buffer = self.buffer.read(cx);
10507        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10508            text_anchor
10509        } else {
10510            return Task::ready(Ok(Navigated::No));
10511        };
10512
10513        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10514            return Task::ready(Ok(Navigated::No));
10515        };
10516
10517        cx.spawn_in(window, |editor, mut cx| async move {
10518            let definitions = definitions.await?;
10519            let navigated = editor
10520                .update_in(&mut cx, |editor, window, cx| {
10521                    editor.navigate_to_hover_links(
10522                        Some(kind),
10523                        definitions
10524                            .into_iter()
10525                            .filter(|location| {
10526                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10527                            })
10528                            .map(HoverLink::Text)
10529                            .collect::<Vec<_>>(),
10530                        split,
10531                        window,
10532                        cx,
10533                    )
10534                })?
10535                .await?;
10536            anyhow::Ok(navigated)
10537        })
10538    }
10539
10540    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10541        let selection = self.selections.newest_anchor();
10542        let head = selection.head();
10543        let tail = selection.tail();
10544
10545        let Some((buffer, start_position)) =
10546            self.buffer.read(cx).text_anchor_for_position(head, cx)
10547        else {
10548            return;
10549        };
10550
10551        let end_position = if head != tail {
10552            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10553                return;
10554            };
10555            Some(pos)
10556        } else {
10557            None
10558        };
10559
10560        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10561            let url = if let Some(end_pos) = end_position {
10562                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10563            } else {
10564                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10565            };
10566
10567            if let Some(url) = url {
10568                editor.update(&mut cx, |_, cx| {
10569                    cx.open_url(&url);
10570                })
10571            } else {
10572                Ok(())
10573            }
10574        });
10575
10576        url_finder.detach();
10577    }
10578
10579    pub fn open_selected_filename(
10580        &mut self,
10581        _: &OpenSelectedFilename,
10582        window: &mut Window,
10583        cx: &mut Context<Self>,
10584    ) {
10585        let Some(workspace) = self.workspace() else {
10586            return;
10587        };
10588
10589        let position = self.selections.newest_anchor().head();
10590
10591        let Some((buffer, buffer_position)) =
10592            self.buffer.read(cx).text_anchor_for_position(position, cx)
10593        else {
10594            return;
10595        };
10596
10597        let project = self.project.clone();
10598
10599        cx.spawn_in(window, |_, mut cx| async move {
10600            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10601
10602            if let Some((_, path)) = result {
10603                workspace
10604                    .update_in(&mut cx, |workspace, window, cx| {
10605                        workspace.open_resolved_path(path, window, cx)
10606                    })?
10607                    .await?;
10608            }
10609            anyhow::Ok(())
10610        })
10611        .detach();
10612    }
10613
10614    pub(crate) fn navigate_to_hover_links(
10615        &mut self,
10616        kind: Option<GotoDefinitionKind>,
10617        mut definitions: Vec<HoverLink>,
10618        split: bool,
10619        window: &mut Window,
10620        cx: &mut Context<Editor>,
10621    ) -> Task<Result<Navigated>> {
10622        // If there is one definition, just open it directly
10623        if definitions.len() == 1 {
10624            let definition = definitions.pop().unwrap();
10625
10626            enum TargetTaskResult {
10627                Location(Option<Location>),
10628                AlreadyNavigated,
10629            }
10630
10631            let target_task = match definition {
10632                HoverLink::Text(link) => {
10633                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10634                }
10635                HoverLink::InlayHint(lsp_location, server_id) => {
10636                    let computation =
10637                        self.compute_target_location(lsp_location, server_id, window, cx);
10638                    cx.background_executor().spawn(async move {
10639                        let location = computation.await?;
10640                        Ok(TargetTaskResult::Location(location))
10641                    })
10642                }
10643                HoverLink::Url(url) => {
10644                    cx.open_url(&url);
10645                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10646                }
10647                HoverLink::File(path) => {
10648                    if let Some(workspace) = self.workspace() {
10649                        cx.spawn_in(window, |_, mut cx| async move {
10650                            workspace
10651                                .update_in(&mut cx, |workspace, window, cx| {
10652                                    workspace.open_resolved_path(path, window, cx)
10653                                })?
10654                                .await
10655                                .map(|_| TargetTaskResult::AlreadyNavigated)
10656                        })
10657                    } else {
10658                        Task::ready(Ok(TargetTaskResult::Location(None)))
10659                    }
10660                }
10661            };
10662            cx.spawn_in(window, |editor, mut cx| async move {
10663                let target = match target_task.await.context("target resolution task")? {
10664                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10665                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10666                    TargetTaskResult::Location(Some(target)) => target,
10667                };
10668
10669                editor.update_in(&mut cx, |editor, window, cx| {
10670                    let Some(workspace) = editor.workspace() else {
10671                        return Navigated::No;
10672                    };
10673                    let pane = workspace.read(cx).active_pane().clone();
10674
10675                    let range = target.range.to_point(target.buffer.read(cx));
10676                    let range = editor.range_for_match(&range);
10677                    let range = collapse_multiline_range(range);
10678
10679                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10680                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10681                    } else {
10682                        window.defer(cx, move |window, cx| {
10683                            let target_editor: Entity<Self> =
10684                                workspace.update(cx, |workspace, cx| {
10685                                    let pane = if split {
10686                                        workspace.adjacent_pane(window, cx)
10687                                    } else {
10688                                        workspace.active_pane().clone()
10689                                    };
10690
10691                                    workspace.open_project_item(
10692                                        pane,
10693                                        target.buffer.clone(),
10694                                        true,
10695                                        true,
10696                                        window,
10697                                        cx,
10698                                    )
10699                                });
10700                            target_editor.update(cx, |target_editor, cx| {
10701                                // When selecting a definition in a different buffer, disable the nav history
10702                                // to avoid creating a history entry at the previous cursor location.
10703                                pane.update(cx, |pane, _| pane.disable_history());
10704                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10705                                pane.update(cx, |pane, _| pane.enable_history());
10706                            });
10707                        });
10708                    }
10709                    Navigated::Yes
10710                })
10711            })
10712        } else if !definitions.is_empty() {
10713            cx.spawn_in(window, |editor, mut cx| async move {
10714                let (title, location_tasks, workspace) = editor
10715                    .update_in(&mut cx, |editor, window, cx| {
10716                        let tab_kind = match kind {
10717                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10718                            _ => "Definitions",
10719                        };
10720                        let title = definitions
10721                            .iter()
10722                            .find_map(|definition| match definition {
10723                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10724                                    let buffer = origin.buffer.read(cx);
10725                                    format!(
10726                                        "{} for {}",
10727                                        tab_kind,
10728                                        buffer
10729                                            .text_for_range(origin.range.clone())
10730                                            .collect::<String>()
10731                                    )
10732                                }),
10733                                HoverLink::InlayHint(_, _) => None,
10734                                HoverLink::Url(_) => None,
10735                                HoverLink::File(_) => None,
10736                            })
10737                            .unwrap_or(tab_kind.to_string());
10738                        let location_tasks = definitions
10739                            .into_iter()
10740                            .map(|definition| match definition {
10741                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10742                                HoverLink::InlayHint(lsp_location, server_id) => editor
10743                                    .compute_target_location(lsp_location, server_id, window, cx),
10744                                HoverLink::Url(_) => Task::ready(Ok(None)),
10745                                HoverLink::File(_) => Task::ready(Ok(None)),
10746                            })
10747                            .collect::<Vec<_>>();
10748                        (title, location_tasks, editor.workspace().clone())
10749                    })
10750                    .context("location tasks preparation")?;
10751
10752                let locations = future::join_all(location_tasks)
10753                    .await
10754                    .into_iter()
10755                    .filter_map(|location| location.transpose())
10756                    .collect::<Result<_>>()
10757                    .context("location tasks")?;
10758
10759                let Some(workspace) = workspace else {
10760                    return Ok(Navigated::No);
10761                };
10762                let opened = workspace
10763                    .update_in(&mut cx, |workspace, window, cx| {
10764                        Self::open_locations_in_multibuffer(
10765                            workspace,
10766                            locations,
10767                            title,
10768                            split,
10769                            MultibufferSelectionMode::First,
10770                            window,
10771                            cx,
10772                        )
10773                    })
10774                    .ok();
10775
10776                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10777            })
10778        } else {
10779            Task::ready(Ok(Navigated::No))
10780        }
10781    }
10782
10783    fn compute_target_location(
10784        &self,
10785        lsp_location: lsp::Location,
10786        server_id: LanguageServerId,
10787        window: &mut Window,
10788        cx: &mut Context<Self>,
10789    ) -> Task<anyhow::Result<Option<Location>>> {
10790        let Some(project) = self.project.clone() else {
10791            return Task::ready(Ok(None));
10792        };
10793
10794        cx.spawn_in(window, move |editor, mut cx| async move {
10795            let location_task = editor.update(&mut cx, |_, cx| {
10796                project.update(cx, |project, cx| {
10797                    let language_server_name = project
10798                        .language_server_statuses(cx)
10799                        .find(|(id, _)| server_id == *id)
10800                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10801                    language_server_name.map(|language_server_name| {
10802                        project.open_local_buffer_via_lsp(
10803                            lsp_location.uri.clone(),
10804                            server_id,
10805                            language_server_name,
10806                            cx,
10807                        )
10808                    })
10809                })
10810            })?;
10811            let location = match location_task {
10812                Some(task) => Some({
10813                    let target_buffer_handle = task.await.context("open local buffer")?;
10814                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10815                        let target_start = target_buffer
10816                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10817                        let target_end = target_buffer
10818                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10819                        target_buffer.anchor_after(target_start)
10820                            ..target_buffer.anchor_before(target_end)
10821                    })?;
10822                    Location {
10823                        buffer: target_buffer_handle,
10824                        range,
10825                    }
10826                }),
10827                None => None,
10828            };
10829            Ok(location)
10830        })
10831    }
10832
10833    pub fn find_all_references(
10834        &mut self,
10835        _: &FindAllReferences,
10836        window: &mut Window,
10837        cx: &mut Context<Self>,
10838    ) -> Option<Task<Result<Navigated>>> {
10839        let selection = self.selections.newest::<usize>(cx);
10840        let multi_buffer = self.buffer.read(cx);
10841        let head = selection.head();
10842
10843        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10844        let head_anchor = multi_buffer_snapshot.anchor_at(
10845            head,
10846            if head < selection.tail() {
10847                Bias::Right
10848            } else {
10849                Bias::Left
10850            },
10851        );
10852
10853        match self
10854            .find_all_references_task_sources
10855            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10856        {
10857            Ok(_) => {
10858                log::info!(
10859                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10860                );
10861                return None;
10862            }
10863            Err(i) => {
10864                self.find_all_references_task_sources.insert(i, head_anchor);
10865            }
10866        }
10867
10868        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10869        let workspace = self.workspace()?;
10870        let project = workspace.read(cx).project().clone();
10871        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10872        Some(cx.spawn_in(window, |editor, mut cx| async move {
10873            let _cleanup = defer({
10874                let mut cx = cx.clone();
10875                move || {
10876                    let _ = editor.update(&mut cx, |editor, _| {
10877                        if let Ok(i) =
10878                            editor
10879                                .find_all_references_task_sources
10880                                .binary_search_by(|anchor| {
10881                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10882                                })
10883                        {
10884                            editor.find_all_references_task_sources.remove(i);
10885                        }
10886                    });
10887                }
10888            });
10889
10890            let locations = references.await?;
10891            if locations.is_empty() {
10892                return anyhow::Ok(Navigated::No);
10893            }
10894
10895            workspace.update_in(&mut cx, |workspace, window, cx| {
10896                let title = locations
10897                    .first()
10898                    .as_ref()
10899                    .map(|location| {
10900                        let buffer = location.buffer.read(cx);
10901                        format!(
10902                            "References to `{}`",
10903                            buffer
10904                                .text_for_range(location.range.clone())
10905                                .collect::<String>()
10906                        )
10907                    })
10908                    .unwrap();
10909                Self::open_locations_in_multibuffer(
10910                    workspace,
10911                    locations,
10912                    title,
10913                    false,
10914                    MultibufferSelectionMode::First,
10915                    window,
10916                    cx,
10917                );
10918                Navigated::Yes
10919            })
10920        }))
10921    }
10922
10923    /// Opens a multibuffer with the given project locations in it
10924    pub fn open_locations_in_multibuffer(
10925        workspace: &mut Workspace,
10926        mut locations: Vec<Location>,
10927        title: String,
10928        split: bool,
10929        multibuffer_selection_mode: MultibufferSelectionMode,
10930        window: &mut Window,
10931        cx: &mut Context<Workspace>,
10932    ) {
10933        // If there are multiple definitions, open them in a multibuffer
10934        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10935        let mut locations = locations.into_iter().peekable();
10936        let mut ranges = Vec::new();
10937        let capability = workspace.project().read(cx).capability();
10938
10939        let excerpt_buffer = cx.new(|cx| {
10940            let mut multibuffer = MultiBuffer::new(capability);
10941            while let Some(location) = locations.next() {
10942                let buffer = location.buffer.read(cx);
10943                let mut ranges_for_buffer = Vec::new();
10944                let range = location.range.to_offset(buffer);
10945                ranges_for_buffer.push(range.clone());
10946
10947                while let Some(next_location) = locations.peek() {
10948                    if next_location.buffer == location.buffer {
10949                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10950                        locations.next();
10951                    } else {
10952                        break;
10953                    }
10954                }
10955
10956                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10957                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10958                    location.buffer.clone(),
10959                    ranges_for_buffer,
10960                    DEFAULT_MULTIBUFFER_CONTEXT,
10961                    cx,
10962                ))
10963            }
10964
10965            multibuffer.with_title(title)
10966        });
10967
10968        let editor = cx.new(|cx| {
10969            Editor::for_multibuffer(
10970                excerpt_buffer,
10971                Some(workspace.project().clone()),
10972                true,
10973                window,
10974                cx,
10975            )
10976        });
10977        editor.update(cx, |editor, cx| {
10978            match multibuffer_selection_mode {
10979                MultibufferSelectionMode::First => {
10980                    if let Some(first_range) = ranges.first() {
10981                        editor.change_selections(None, window, cx, |selections| {
10982                            selections.clear_disjoint();
10983                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10984                        });
10985                    }
10986                    editor.highlight_background::<Self>(
10987                        &ranges,
10988                        |theme| theme.editor_highlighted_line_background,
10989                        cx,
10990                    );
10991                }
10992                MultibufferSelectionMode::All => {
10993                    editor.change_selections(None, window, cx, |selections| {
10994                        selections.clear_disjoint();
10995                        selections.select_anchor_ranges(ranges);
10996                    });
10997                }
10998            }
10999            editor.register_buffers_with_language_servers(cx);
11000        });
11001
11002        let item = Box::new(editor);
11003        let item_id = item.item_id();
11004
11005        if split {
11006            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11007        } else {
11008            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11009                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11010                    pane.close_current_preview_item(window, cx)
11011                } else {
11012                    None
11013                }
11014            });
11015            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11016        }
11017        workspace.active_pane().update(cx, |pane, cx| {
11018            pane.set_preview_item_id(Some(item_id), cx);
11019        });
11020    }
11021
11022    pub fn rename(
11023        &mut self,
11024        _: &Rename,
11025        window: &mut Window,
11026        cx: &mut Context<Self>,
11027    ) -> Option<Task<Result<()>>> {
11028        use language::ToOffset as _;
11029
11030        let provider = self.semantics_provider.clone()?;
11031        let selection = self.selections.newest_anchor().clone();
11032        let (cursor_buffer, cursor_buffer_position) = self
11033            .buffer
11034            .read(cx)
11035            .text_anchor_for_position(selection.head(), cx)?;
11036        let (tail_buffer, cursor_buffer_position_end) = self
11037            .buffer
11038            .read(cx)
11039            .text_anchor_for_position(selection.tail(), cx)?;
11040        if tail_buffer != cursor_buffer {
11041            return None;
11042        }
11043
11044        let snapshot = cursor_buffer.read(cx).snapshot();
11045        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11046        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11047        let prepare_rename = provider
11048            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11049            .unwrap_or_else(|| Task::ready(Ok(None)));
11050        drop(snapshot);
11051
11052        Some(cx.spawn_in(window, |this, mut cx| async move {
11053            let rename_range = if let Some(range) = prepare_rename.await? {
11054                Some(range)
11055            } else {
11056                this.update(&mut cx, |this, cx| {
11057                    let buffer = this.buffer.read(cx).snapshot(cx);
11058                    let mut buffer_highlights = this
11059                        .document_highlights_for_position(selection.head(), &buffer)
11060                        .filter(|highlight| {
11061                            highlight.start.excerpt_id == selection.head().excerpt_id
11062                                && highlight.end.excerpt_id == selection.head().excerpt_id
11063                        });
11064                    buffer_highlights
11065                        .next()
11066                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11067                })?
11068            };
11069            if let Some(rename_range) = rename_range {
11070                this.update_in(&mut cx, |this, window, cx| {
11071                    let snapshot = cursor_buffer.read(cx).snapshot();
11072                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11073                    let cursor_offset_in_rename_range =
11074                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11075                    let cursor_offset_in_rename_range_end =
11076                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11077
11078                    this.take_rename(false, window, cx);
11079                    let buffer = this.buffer.read(cx).read(cx);
11080                    let cursor_offset = selection.head().to_offset(&buffer);
11081                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11082                    let rename_end = rename_start + rename_buffer_range.len();
11083                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11084                    let mut old_highlight_id = None;
11085                    let old_name: Arc<str> = buffer
11086                        .chunks(rename_start..rename_end, true)
11087                        .map(|chunk| {
11088                            if old_highlight_id.is_none() {
11089                                old_highlight_id = chunk.syntax_highlight_id;
11090                            }
11091                            chunk.text
11092                        })
11093                        .collect::<String>()
11094                        .into();
11095
11096                    drop(buffer);
11097
11098                    // Position the selection in the rename editor so that it matches the current selection.
11099                    this.show_local_selections = false;
11100                    let rename_editor = cx.new(|cx| {
11101                        let mut editor = Editor::single_line(window, cx);
11102                        editor.buffer.update(cx, |buffer, cx| {
11103                            buffer.edit([(0..0, old_name.clone())], None, cx)
11104                        });
11105                        let rename_selection_range = match cursor_offset_in_rename_range
11106                            .cmp(&cursor_offset_in_rename_range_end)
11107                        {
11108                            Ordering::Equal => {
11109                                editor.select_all(&SelectAll, window, cx);
11110                                return editor;
11111                            }
11112                            Ordering::Less => {
11113                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11114                            }
11115                            Ordering::Greater => {
11116                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11117                            }
11118                        };
11119                        if rename_selection_range.end > old_name.len() {
11120                            editor.select_all(&SelectAll, window, cx);
11121                        } else {
11122                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11123                                s.select_ranges([rename_selection_range]);
11124                            });
11125                        }
11126                        editor
11127                    });
11128                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11129                        if e == &EditorEvent::Focused {
11130                            cx.emit(EditorEvent::FocusedIn)
11131                        }
11132                    })
11133                    .detach();
11134
11135                    let write_highlights =
11136                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11137                    let read_highlights =
11138                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11139                    let ranges = write_highlights
11140                        .iter()
11141                        .flat_map(|(_, ranges)| ranges.iter())
11142                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11143                        .cloned()
11144                        .collect();
11145
11146                    this.highlight_text::<Rename>(
11147                        ranges,
11148                        HighlightStyle {
11149                            fade_out: Some(0.6),
11150                            ..Default::default()
11151                        },
11152                        cx,
11153                    );
11154                    let rename_focus_handle = rename_editor.focus_handle(cx);
11155                    window.focus(&rename_focus_handle);
11156                    let block_id = this.insert_blocks(
11157                        [BlockProperties {
11158                            style: BlockStyle::Flex,
11159                            placement: BlockPlacement::Below(range.start),
11160                            height: 1,
11161                            render: Arc::new({
11162                                let rename_editor = rename_editor.clone();
11163                                move |cx: &mut BlockContext| {
11164                                    let mut text_style = cx.editor_style.text.clone();
11165                                    if let Some(highlight_style) = old_highlight_id
11166                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11167                                    {
11168                                        text_style = text_style.highlight(highlight_style);
11169                                    }
11170                                    div()
11171                                        .block_mouse_down()
11172                                        .pl(cx.anchor_x)
11173                                        .child(EditorElement::new(
11174                                            &rename_editor,
11175                                            EditorStyle {
11176                                                background: cx.theme().system().transparent,
11177                                                local_player: cx.editor_style.local_player,
11178                                                text: text_style,
11179                                                scrollbar_width: cx.editor_style.scrollbar_width,
11180                                                syntax: cx.editor_style.syntax.clone(),
11181                                                status: cx.editor_style.status.clone(),
11182                                                inlay_hints_style: HighlightStyle {
11183                                                    font_weight: Some(FontWeight::BOLD),
11184                                                    ..make_inlay_hints_style(cx.app)
11185                                                },
11186                                                inline_completion_styles: make_suggestion_styles(
11187                                                    cx.app,
11188                                                ),
11189                                                ..EditorStyle::default()
11190                                            },
11191                                        ))
11192                                        .into_any_element()
11193                                }
11194                            }),
11195                            priority: 0,
11196                        }],
11197                        Some(Autoscroll::fit()),
11198                        cx,
11199                    )[0];
11200                    this.pending_rename = Some(RenameState {
11201                        range,
11202                        old_name,
11203                        editor: rename_editor,
11204                        block_id,
11205                    });
11206                })?;
11207            }
11208
11209            Ok(())
11210        }))
11211    }
11212
11213    pub fn confirm_rename(
11214        &mut self,
11215        _: &ConfirmRename,
11216        window: &mut Window,
11217        cx: &mut Context<Self>,
11218    ) -> Option<Task<Result<()>>> {
11219        let rename = self.take_rename(false, window, cx)?;
11220        let workspace = self.workspace()?.downgrade();
11221        let (buffer, start) = self
11222            .buffer
11223            .read(cx)
11224            .text_anchor_for_position(rename.range.start, cx)?;
11225        let (end_buffer, _) = self
11226            .buffer
11227            .read(cx)
11228            .text_anchor_for_position(rename.range.end, cx)?;
11229        if buffer != end_buffer {
11230            return None;
11231        }
11232
11233        let old_name = rename.old_name;
11234        let new_name = rename.editor.read(cx).text(cx);
11235
11236        let rename = self.semantics_provider.as_ref()?.perform_rename(
11237            &buffer,
11238            start,
11239            new_name.clone(),
11240            cx,
11241        )?;
11242
11243        Some(cx.spawn_in(window, |editor, mut cx| async move {
11244            let project_transaction = rename.await?;
11245            Self::open_project_transaction(
11246                &editor,
11247                workspace,
11248                project_transaction,
11249                format!("Rename: {}{}", old_name, new_name),
11250                cx.clone(),
11251            )
11252            .await?;
11253
11254            editor.update(&mut cx, |editor, cx| {
11255                editor.refresh_document_highlights(cx);
11256            })?;
11257            Ok(())
11258        }))
11259    }
11260
11261    fn take_rename(
11262        &mut self,
11263        moving_cursor: bool,
11264        window: &mut Window,
11265        cx: &mut Context<Self>,
11266    ) -> Option<RenameState> {
11267        let rename = self.pending_rename.take()?;
11268        if rename.editor.focus_handle(cx).is_focused(window) {
11269            window.focus(&self.focus_handle);
11270        }
11271
11272        self.remove_blocks(
11273            [rename.block_id].into_iter().collect(),
11274            Some(Autoscroll::fit()),
11275            cx,
11276        );
11277        self.clear_highlights::<Rename>(cx);
11278        self.show_local_selections = true;
11279
11280        if moving_cursor {
11281            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11282                editor.selections.newest::<usize>(cx).head()
11283            });
11284
11285            // Update the selection to match the position of the selection inside
11286            // the rename editor.
11287            let snapshot = self.buffer.read(cx).read(cx);
11288            let rename_range = rename.range.to_offset(&snapshot);
11289            let cursor_in_editor = snapshot
11290                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11291                .min(rename_range.end);
11292            drop(snapshot);
11293
11294            self.change_selections(None, window, cx, |s| {
11295                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11296            });
11297        } else {
11298            self.refresh_document_highlights(cx);
11299        }
11300
11301        Some(rename)
11302    }
11303
11304    pub fn pending_rename(&self) -> Option<&RenameState> {
11305        self.pending_rename.as_ref()
11306    }
11307
11308    fn format(
11309        &mut self,
11310        _: &Format,
11311        window: &mut Window,
11312        cx: &mut Context<Self>,
11313    ) -> Option<Task<Result<()>>> {
11314        let project = match &self.project {
11315            Some(project) => project.clone(),
11316            None => return None,
11317        };
11318
11319        Some(self.perform_format(
11320            project,
11321            FormatTrigger::Manual,
11322            FormatTarget::Buffers,
11323            window,
11324            cx,
11325        ))
11326    }
11327
11328    fn format_selections(
11329        &mut self,
11330        _: &FormatSelections,
11331        window: &mut Window,
11332        cx: &mut Context<Self>,
11333    ) -> Option<Task<Result<()>>> {
11334        let project = match &self.project {
11335            Some(project) => project.clone(),
11336            None => return None,
11337        };
11338
11339        let ranges = self
11340            .selections
11341            .all_adjusted(cx)
11342            .into_iter()
11343            .map(|selection| selection.range())
11344            .collect_vec();
11345
11346        Some(self.perform_format(
11347            project,
11348            FormatTrigger::Manual,
11349            FormatTarget::Ranges(ranges),
11350            window,
11351            cx,
11352        ))
11353    }
11354
11355    fn perform_format(
11356        &mut self,
11357        project: Entity<Project>,
11358        trigger: FormatTrigger,
11359        target: FormatTarget,
11360        window: &mut Window,
11361        cx: &mut Context<Self>,
11362    ) -> Task<Result<()>> {
11363        let buffer = self.buffer.clone();
11364        let (buffers, target) = match target {
11365            FormatTarget::Buffers => {
11366                let mut buffers = buffer.read(cx).all_buffers();
11367                if trigger == FormatTrigger::Save {
11368                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11369                }
11370                (buffers, LspFormatTarget::Buffers)
11371            }
11372            FormatTarget::Ranges(selection_ranges) => {
11373                let multi_buffer = buffer.read(cx);
11374                let snapshot = multi_buffer.read(cx);
11375                let mut buffers = HashSet::default();
11376                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11377                    BTreeMap::new();
11378                for selection_range in selection_ranges {
11379                    for (buffer, buffer_range, _) in
11380                        snapshot.range_to_buffer_ranges(selection_range)
11381                    {
11382                        let buffer_id = buffer.remote_id();
11383                        let start = buffer.anchor_before(buffer_range.start);
11384                        let end = buffer.anchor_after(buffer_range.end);
11385                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11386                        buffer_id_to_ranges
11387                            .entry(buffer_id)
11388                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11389                            .or_insert_with(|| vec![start..end]);
11390                    }
11391                }
11392                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11393            }
11394        };
11395
11396        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11397        let format = project.update(cx, |project, cx| {
11398            project.format(buffers, target, true, trigger, cx)
11399        });
11400
11401        cx.spawn_in(window, |_, mut cx| async move {
11402            let transaction = futures::select_biased! {
11403                () = timeout => {
11404                    log::warn!("timed out waiting for formatting");
11405                    None
11406                }
11407                transaction = format.log_err().fuse() => transaction,
11408            };
11409
11410            buffer
11411                .update(&mut cx, |buffer, cx| {
11412                    if let Some(transaction) = transaction {
11413                        if !buffer.is_singleton() {
11414                            buffer.push_transaction(&transaction.0, cx);
11415                        }
11416                    }
11417
11418                    cx.notify();
11419                })
11420                .ok();
11421
11422            Ok(())
11423        })
11424    }
11425
11426    fn restart_language_server(
11427        &mut self,
11428        _: &RestartLanguageServer,
11429        _: &mut Window,
11430        cx: &mut Context<Self>,
11431    ) {
11432        if let Some(project) = self.project.clone() {
11433            self.buffer.update(cx, |multi_buffer, cx| {
11434                project.update(cx, |project, cx| {
11435                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11436                });
11437            })
11438        }
11439    }
11440
11441    fn cancel_language_server_work(
11442        workspace: &mut Workspace,
11443        _: &actions::CancelLanguageServerWork,
11444        _: &mut Window,
11445        cx: &mut Context<Workspace>,
11446    ) {
11447        let project = workspace.project();
11448        let buffers = workspace
11449            .active_item(cx)
11450            .and_then(|item| item.act_as::<Editor>(cx))
11451            .map_or(HashSet::default(), |editor| {
11452                editor.read(cx).buffer.read(cx).all_buffers()
11453            });
11454        project.update(cx, |project, cx| {
11455            project.cancel_language_server_work_for_buffers(buffers, cx);
11456        });
11457    }
11458
11459    fn show_character_palette(
11460        &mut self,
11461        _: &ShowCharacterPalette,
11462        window: &mut Window,
11463        _: &mut Context<Self>,
11464    ) {
11465        window.show_character_palette();
11466    }
11467
11468    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11469        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11470            let buffer = self.buffer.read(cx).snapshot(cx);
11471            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11472            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11473            let is_valid = buffer
11474                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11475                .any(|entry| {
11476                    entry.diagnostic.is_primary
11477                        && !entry.range.is_empty()
11478                        && entry.range.start == primary_range_start
11479                        && entry.diagnostic.message == active_diagnostics.primary_message
11480                });
11481
11482            if is_valid != active_diagnostics.is_valid {
11483                active_diagnostics.is_valid = is_valid;
11484                let mut new_styles = HashMap::default();
11485                for (block_id, diagnostic) in &active_diagnostics.blocks {
11486                    new_styles.insert(
11487                        *block_id,
11488                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11489                    );
11490                }
11491                self.display_map.update(cx, |display_map, _cx| {
11492                    display_map.replace_blocks(new_styles)
11493                });
11494            }
11495        }
11496    }
11497
11498    fn activate_diagnostics(
11499        &mut self,
11500        buffer_id: BufferId,
11501        group_id: usize,
11502        window: &mut Window,
11503        cx: &mut Context<Self>,
11504    ) {
11505        self.dismiss_diagnostics(cx);
11506        let snapshot = self.snapshot(window, cx);
11507        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11508            let buffer = self.buffer.read(cx).snapshot(cx);
11509
11510            let mut primary_range = None;
11511            let mut primary_message = None;
11512            let diagnostic_group = buffer
11513                .diagnostic_group(buffer_id, group_id)
11514                .filter_map(|entry| {
11515                    let start = entry.range.start;
11516                    let end = entry.range.end;
11517                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11518                        && (start.row == end.row
11519                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11520                    {
11521                        return None;
11522                    }
11523                    if entry.diagnostic.is_primary {
11524                        primary_range = Some(entry.range.clone());
11525                        primary_message = Some(entry.diagnostic.message.clone());
11526                    }
11527                    Some(entry)
11528                })
11529                .collect::<Vec<_>>();
11530            let primary_range = primary_range?;
11531            let primary_message = primary_message?;
11532
11533            let blocks = display_map
11534                .insert_blocks(
11535                    diagnostic_group.iter().map(|entry| {
11536                        let diagnostic = entry.diagnostic.clone();
11537                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11538                        BlockProperties {
11539                            style: BlockStyle::Fixed,
11540                            placement: BlockPlacement::Below(
11541                                buffer.anchor_after(entry.range.start),
11542                            ),
11543                            height: message_height,
11544                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11545                            priority: 0,
11546                        }
11547                    }),
11548                    cx,
11549                )
11550                .into_iter()
11551                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11552                .collect();
11553
11554            Some(ActiveDiagnosticGroup {
11555                primary_range: buffer.anchor_before(primary_range.start)
11556                    ..buffer.anchor_after(primary_range.end),
11557                primary_message,
11558                group_id,
11559                blocks,
11560                is_valid: true,
11561            })
11562        });
11563    }
11564
11565    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11566        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11567            self.display_map.update(cx, |display_map, cx| {
11568                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11569            });
11570            cx.notify();
11571        }
11572    }
11573
11574    pub fn set_selections_from_remote(
11575        &mut self,
11576        selections: Vec<Selection<Anchor>>,
11577        pending_selection: Option<Selection<Anchor>>,
11578        window: &mut Window,
11579        cx: &mut Context<Self>,
11580    ) {
11581        let old_cursor_position = self.selections.newest_anchor().head();
11582        self.selections.change_with(cx, |s| {
11583            s.select_anchors(selections);
11584            if let Some(pending_selection) = pending_selection {
11585                s.set_pending(pending_selection, SelectMode::Character);
11586            } else {
11587                s.clear_pending();
11588            }
11589        });
11590        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11591    }
11592
11593    fn push_to_selection_history(&mut self) {
11594        self.selection_history.push(SelectionHistoryEntry {
11595            selections: self.selections.disjoint_anchors(),
11596            select_next_state: self.select_next_state.clone(),
11597            select_prev_state: self.select_prev_state.clone(),
11598            add_selections_state: self.add_selections_state.clone(),
11599        });
11600    }
11601
11602    pub fn transact(
11603        &mut self,
11604        window: &mut Window,
11605        cx: &mut Context<Self>,
11606        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11607    ) -> Option<TransactionId> {
11608        self.start_transaction_at(Instant::now(), window, cx);
11609        update(self, window, cx);
11610        self.end_transaction_at(Instant::now(), cx)
11611    }
11612
11613    pub fn start_transaction_at(
11614        &mut self,
11615        now: Instant,
11616        window: &mut Window,
11617        cx: &mut Context<Self>,
11618    ) {
11619        self.end_selection(window, cx);
11620        if let Some(tx_id) = self
11621            .buffer
11622            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11623        {
11624            self.selection_history
11625                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11626            cx.emit(EditorEvent::TransactionBegun {
11627                transaction_id: tx_id,
11628            })
11629        }
11630    }
11631
11632    pub fn end_transaction_at(
11633        &mut self,
11634        now: Instant,
11635        cx: &mut Context<Self>,
11636    ) -> Option<TransactionId> {
11637        if let Some(transaction_id) = self
11638            .buffer
11639            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11640        {
11641            if let Some((_, end_selections)) =
11642                self.selection_history.transaction_mut(transaction_id)
11643            {
11644                *end_selections = Some(self.selections.disjoint_anchors());
11645            } else {
11646                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11647            }
11648
11649            cx.emit(EditorEvent::Edited { transaction_id });
11650            Some(transaction_id)
11651        } else {
11652            None
11653        }
11654    }
11655
11656    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11657        if self.selection_mark_mode {
11658            self.change_selections(None, window, cx, |s| {
11659                s.move_with(|_, sel| {
11660                    sel.collapse_to(sel.head(), SelectionGoal::None);
11661                });
11662            })
11663        }
11664        self.selection_mark_mode = true;
11665        cx.notify();
11666    }
11667
11668    pub fn swap_selection_ends(
11669        &mut self,
11670        _: &actions::SwapSelectionEnds,
11671        window: &mut Window,
11672        cx: &mut Context<Self>,
11673    ) {
11674        self.change_selections(None, window, cx, |s| {
11675            s.move_with(|_, sel| {
11676                if sel.start != sel.end {
11677                    sel.reversed = !sel.reversed
11678                }
11679            });
11680        });
11681        self.request_autoscroll(Autoscroll::newest(), cx);
11682        cx.notify();
11683    }
11684
11685    pub fn toggle_fold(
11686        &mut self,
11687        _: &actions::ToggleFold,
11688        window: &mut Window,
11689        cx: &mut Context<Self>,
11690    ) {
11691        if self.is_singleton(cx) {
11692            let selection = self.selections.newest::<Point>(cx);
11693
11694            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11695            let range = if selection.is_empty() {
11696                let point = selection.head().to_display_point(&display_map);
11697                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11698                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11699                    .to_point(&display_map);
11700                start..end
11701            } else {
11702                selection.range()
11703            };
11704            if display_map.folds_in_range(range).next().is_some() {
11705                self.unfold_lines(&Default::default(), window, cx)
11706            } else {
11707                self.fold(&Default::default(), window, cx)
11708            }
11709        } else {
11710            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11711            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11712                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11713                .map(|(snapshot, _, _)| snapshot.remote_id())
11714                .collect();
11715
11716            for buffer_id in buffer_ids {
11717                if self.is_buffer_folded(buffer_id, cx) {
11718                    self.unfold_buffer(buffer_id, cx);
11719                } else {
11720                    self.fold_buffer(buffer_id, cx);
11721                }
11722            }
11723        }
11724    }
11725
11726    pub fn toggle_fold_recursive(
11727        &mut self,
11728        _: &actions::ToggleFoldRecursive,
11729        window: &mut Window,
11730        cx: &mut Context<Self>,
11731    ) {
11732        let selection = self.selections.newest::<Point>(cx);
11733
11734        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11735        let range = if selection.is_empty() {
11736            let point = selection.head().to_display_point(&display_map);
11737            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11738            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11739                .to_point(&display_map);
11740            start..end
11741        } else {
11742            selection.range()
11743        };
11744        if display_map.folds_in_range(range).next().is_some() {
11745            self.unfold_recursive(&Default::default(), window, cx)
11746        } else {
11747            self.fold_recursive(&Default::default(), window, cx)
11748        }
11749    }
11750
11751    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11752        if self.is_singleton(cx) {
11753            let mut to_fold = Vec::new();
11754            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11755            let selections = self.selections.all_adjusted(cx);
11756
11757            for selection in selections {
11758                let range = selection.range().sorted();
11759                let buffer_start_row = range.start.row;
11760
11761                if range.start.row != range.end.row {
11762                    let mut found = false;
11763                    let mut row = range.start.row;
11764                    while row <= range.end.row {
11765                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11766                        {
11767                            found = true;
11768                            row = crease.range().end.row + 1;
11769                            to_fold.push(crease);
11770                        } else {
11771                            row += 1
11772                        }
11773                    }
11774                    if found {
11775                        continue;
11776                    }
11777                }
11778
11779                for row in (0..=range.start.row).rev() {
11780                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11781                        if crease.range().end.row >= buffer_start_row {
11782                            to_fold.push(crease);
11783                            if row <= range.start.row {
11784                                break;
11785                            }
11786                        }
11787                    }
11788                }
11789            }
11790
11791            self.fold_creases(to_fold, true, window, cx);
11792        } else {
11793            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11794
11795            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11796                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11797                .map(|(snapshot, _, _)| snapshot.remote_id())
11798                .collect();
11799            for buffer_id in buffer_ids {
11800                self.fold_buffer(buffer_id, cx);
11801            }
11802        }
11803    }
11804
11805    fn fold_at_level(
11806        &mut self,
11807        fold_at: &FoldAtLevel,
11808        window: &mut Window,
11809        cx: &mut Context<Self>,
11810    ) {
11811        if !self.buffer.read(cx).is_singleton() {
11812            return;
11813        }
11814
11815        let fold_at_level = fold_at.0;
11816        let snapshot = self.buffer.read(cx).snapshot(cx);
11817        let mut to_fold = Vec::new();
11818        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11819
11820        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11821            while start_row < end_row {
11822                match self
11823                    .snapshot(window, cx)
11824                    .crease_for_buffer_row(MultiBufferRow(start_row))
11825                {
11826                    Some(crease) => {
11827                        let nested_start_row = crease.range().start.row + 1;
11828                        let nested_end_row = crease.range().end.row;
11829
11830                        if current_level < fold_at_level {
11831                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11832                        } else if current_level == fold_at_level {
11833                            to_fold.push(crease);
11834                        }
11835
11836                        start_row = nested_end_row + 1;
11837                    }
11838                    None => start_row += 1,
11839                }
11840            }
11841        }
11842
11843        self.fold_creases(to_fold, true, window, cx);
11844    }
11845
11846    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11847        if self.buffer.read(cx).is_singleton() {
11848            let mut fold_ranges = Vec::new();
11849            let snapshot = self.buffer.read(cx).snapshot(cx);
11850
11851            for row in 0..snapshot.max_row().0 {
11852                if let Some(foldable_range) = self
11853                    .snapshot(window, cx)
11854                    .crease_for_buffer_row(MultiBufferRow(row))
11855                {
11856                    fold_ranges.push(foldable_range);
11857                }
11858            }
11859
11860            self.fold_creases(fold_ranges, true, window, cx);
11861        } else {
11862            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11863                editor
11864                    .update_in(&mut cx, |editor, _, cx| {
11865                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11866                            editor.fold_buffer(buffer_id, cx);
11867                        }
11868                    })
11869                    .ok();
11870            });
11871        }
11872    }
11873
11874    pub fn fold_function_bodies(
11875        &mut self,
11876        _: &actions::FoldFunctionBodies,
11877        window: &mut Window,
11878        cx: &mut Context<Self>,
11879    ) {
11880        let snapshot = self.buffer.read(cx).snapshot(cx);
11881
11882        let ranges = snapshot
11883            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11884            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11885            .collect::<Vec<_>>();
11886
11887        let creases = ranges
11888            .into_iter()
11889            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11890            .collect();
11891
11892        self.fold_creases(creases, true, window, cx);
11893    }
11894
11895    pub fn fold_recursive(
11896        &mut self,
11897        _: &actions::FoldRecursive,
11898        window: &mut Window,
11899        cx: &mut Context<Self>,
11900    ) {
11901        let mut to_fold = Vec::new();
11902        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11903        let selections = self.selections.all_adjusted(cx);
11904
11905        for selection in selections {
11906            let range = selection.range().sorted();
11907            let buffer_start_row = range.start.row;
11908
11909            if range.start.row != range.end.row {
11910                let mut found = false;
11911                for row in range.start.row..=range.end.row {
11912                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11913                        found = true;
11914                        to_fold.push(crease);
11915                    }
11916                }
11917                if found {
11918                    continue;
11919                }
11920            }
11921
11922            for row in (0..=range.start.row).rev() {
11923                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11924                    if crease.range().end.row >= buffer_start_row {
11925                        to_fold.push(crease);
11926                    } else {
11927                        break;
11928                    }
11929                }
11930            }
11931        }
11932
11933        self.fold_creases(to_fold, true, window, cx);
11934    }
11935
11936    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11937        let buffer_row = fold_at.buffer_row;
11938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11939
11940        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11941            let autoscroll = self
11942                .selections
11943                .all::<Point>(cx)
11944                .iter()
11945                .any(|selection| crease.range().overlaps(&selection.range()));
11946
11947            self.fold_creases(vec![crease], autoscroll, window, cx);
11948        }
11949    }
11950
11951    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11952        if self.is_singleton(cx) {
11953            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11954            let buffer = &display_map.buffer_snapshot;
11955            let selections = self.selections.all::<Point>(cx);
11956            let ranges = selections
11957                .iter()
11958                .map(|s| {
11959                    let range = s.display_range(&display_map).sorted();
11960                    let mut start = range.start.to_point(&display_map);
11961                    let mut end = range.end.to_point(&display_map);
11962                    start.column = 0;
11963                    end.column = buffer.line_len(MultiBufferRow(end.row));
11964                    start..end
11965                })
11966                .collect::<Vec<_>>();
11967
11968            self.unfold_ranges(&ranges, true, true, cx);
11969        } else {
11970            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11971            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11972                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11973                .map(|(snapshot, _, _)| snapshot.remote_id())
11974                .collect();
11975            for buffer_id in buffer_ids {
11976                self.unfold_buffer(buffer_id, cx);
11977            }
11978        }
11979    }
11980
11981    pub fn unfold_recursive(
11982        &mut self,
11983        _: &UnfoldRecursive,
11984        _window: &mut Window,
11985        cx: &mut Context<Self>,
11986    ) {
11987        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11988        let selections = self.selections.all::<Point>(cx);
11989        let ranges = selections
11990            .iter()
11991            .map(|s| {
11992                let mut range = s.display_range(&display_map).sorted();
11993                *range.start.column_mut() = 0;
11994                *range.end.column_mut() = display_map.line_len(range.end.row());
11995                let start = range.start.to_point(&display_map);
11996                let end = range.end.to_point(&display_map);
11997                start..end
11998            })
11999            .collect::<Vec<_>>();
12000
12001        self.unfold_ranges(&ranges, true, true, cx);
12002    }
12003
12004    pub fn unfold_at(
12005        &mut self,
12006        unfold_at: &UnfoldAt,
12007        _window: &mut Window,
12008        cx: &mut Context<Self>,
12009    ) {
12010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12011
12012        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12013            ..Point::new(
12014                unfold_at.buffer_row.0,
12015                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12016            );
12017
12018        let autoscroll = self
12019            .selections
12020            .all::<Point>(cx)
12021            .iter()
12022            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12023
12024        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12025    }
12026
12027    pub fn unfold_all(
12028        &mut self,
12029        _: &actions::UnfoldAll,
12030        _window: &mut Window,
12031        cx: &mut Context<Self>,
12032    ) {
12033        if self.buffer.read(cx).is_singleton() {
12034            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12035            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12036        } else {
12037            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12038                editor
12039                    .update(&mut cx, |editor, cx| {
12040                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12041                            editor.unfold_buffer(buffer_id, cx);
12042                        }
12043                    })
12044                    .ok();
12045            });
12046        }
12047    }
12048
12049    pub fn fold_selected_ranges(
12050        &mut self,
12051        _: &FoldSelectedRanges,
12052        window: &mut Window,
12053        cx: &mut Context<Self>,
12054    ) {
12055        let selections = self.selections.all::<Point>(cx);
12056        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12057        let line_mode = self.selections.line_mode;
12058        let ranges = selections
12059            .into_iter()
12060            .map(|s| {
12061                if line_mode {
12062                    let start = Point::new(s.start.row, 0);
12063                    let end = Point::new(
12064                        s.end.row,
12065                        display_map
12066                            .buffer_snapshot
12067                            .line_len(MultiBufferRow(s.end.row)),
12068                    );
12069                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12070                } else {
12071                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12072                }
12073            })
12074            .collect::<Vec<_>>();
12075        self.fold_creases(ranges, true, window, cx);
12076    }
12077
12078    pub fn fold_ranges<T: ToOffset + Clone>(
12079        &mut self,
12080        ranges: Vec<Range<T>>,
12081        auto_scroll: bool,
12082        window: &mut Window,
12083        cx: &mut Context<Self>,
12084    ) {
12085        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12086        let ranges = ranges
12087            .into_iter()
12088            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12089            .collect::<Vec<_>>();
12090        self.fold_creases(ranges, auto_scroll, window, cx);
12091    }
12092
12093    pub fn fold_creases<T: ToOffset + Clone>(
12094        &mut self,
12095        creases: Vec<Crease<T>>,
12096        auto_scroll: bool,
12097        window: &mut Window,
12098        cx: &mut Context<Self>,
12099    ) {
12100        if creases.is_empty() {
12101            return;
12102        }
12103
12104        let mut buffers_affected = HashSet::default();
12105        let multi_buffer = self.buffer().read(cx);
12106        for crease in &creases {
12107            if let Some((_, buffer, _)) =
12108                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12109            {
12110                buffers_affected.insert(buffer.read(cx).remote_id());
12111            };
12112        }
12113
12114        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12115
12116        if auto_scroll {
12117            self.request_autoscroll(Autoscroll::fit(), cx);
12118        }
12119
12120        cx.notify();
12121
12122        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12123            // Clear diagnostics block when folding a range that contains it.
12124            let snapshot = self.snapshot(window, cx);
12125            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12126                drop(snapshot);
12127                self.active_diagnostics = Some(active_diagnostics);
12128                self.dismiss_diagnostics(cx);
12129            } else {
12130                self.active_diagnostics = Some(active_diagnostics);
12131            }
12132        }
12133
12134        self.scrollbar_marker_state.dirty = true;
12135    }
12136
12137    /// Removes any folds whose ranges intersect any of the given ranges.
12138    pub fn unfold_ranges<T: ToOffset + Clone>(
12139        &mut self,
12140        ranges: &[Range<T>],
12141        inclusive: bool,
12142        auto_scroll: bool,
12143        cx: &mut Context<Self>,
12144    ) {
12145        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12146            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12147        });
12148    }
12149
12150    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12151        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12152            return;
12153        }
12154        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12155        self.display_map
12156            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12157        cx.emit(EditorEvent::BufferFoldToggled {
12158            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12159            folded: true,
12160        });
12161        cx.notify();
12162    }
12163
12164    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12165        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12166            return;
12167        }
12168        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12169        self.display_map.update(cx, |display_map, cx| {
12170            display_map.unfold_buffer(buffer_id, cx);
12171        });
12172        cx.emit(EditorEvent::BufferFoldToggled {
12173            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12174            folded: false,
12175        });
12176        cx.notify();
12177    }
12178
12179    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12180        self.display_map.read(cx).is_buffer_folded(buffer)
12181    }
12182
12183    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12184        self.display_map.read(cx).folded_buffers()
12185    }
12186
12187    /// Removes any folds with the given ranges.
12188    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12189        &mut self,
12190        ranges: &[Range<T>],
12191        type_id: TypeId,
12192        auto_scroll: bool,
12193        cx: &mut Context<Self>,
12194    ) {
12195        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12196            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12197        });
12198    }
12199
12200    fn remove_folds_with<T: ToOffset + Clone>(
12201        &mut self,
12202        ranges: &[Range<T>],
12203        auto_scroll: bool,
12204        cx: &mut Context<Self>,
12205        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12206    ) {
12207        if ranges.is_empty() {
12208            return;
12209        }
12210
12211        let mut buffers_affected = HashSet::default();
12212        let multi_buffer = self.buffer().read(cx);
12213        for range in ranges {
12214            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12215                buffers_affected.insert(buffer.read(cx).remote_id());
12216            };
12217        }
12218
12219        self.display_map.update(cx, update);
12220
12221        if auto_scroll {
12222            self.request_autoscroll(Autoscroll::fit(), cx);
12223        }
12224
12225        cx.notify();
12226        self.scrollbar_marker_state.dirty = true;
12227        self.active_indent_guides_state.dirty = true;
12228    }
12229
12230    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12231        self.display_map.read(cx).fold_placeholder.clone()
12232    }
12233
12234    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12235        self.buffer.update(cx, |buffer, cx| {
12236            buffer.set_all_diff_hunks_expanded(cx);
12237        });
12238    }
12239
12240    pub fn expand_all_diff_hunks(
12241        &mut self,
12242        _: &ExpandAllHunkDiffs,
12243        _window: &mut Window,
12244        cx: &mut Context<Self>,
12245    ) {
12246        self.buffer.update(cx, |buffer, cx| {
12247            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12248        });
12249    }
12250
12251    pub fn toggle_selected_diff_hunks(
12252        &mut self,
12253        _: &ToggleSelectedDiffHunks,
12254        _window: &mut Window,
12255        cx: &mut Context<Self>,
12256    ) {
12257        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12258        self.toggle_diff_hunks_in_ranges(ranges, cx);
12259    }
12260
12261    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12262        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12263        self.buffer
12264            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12265    }
12266
12267    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12268        self.buffer.update(cx, |buffer, cx| {
12269            let ranges = vec![Anchor::min()..Anchor::max()];
12270            if !buffer.all_diff_hunks_expanded()
12271                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12272            {
12273                buffer.collapse_diff_hunks(ranges, cx);
12274                true
12275            } else {
12276                false
12277            }
12278        })
12279    }
12280
12281    fn toggle_diff_hunks_in_ranges(
12282        &mut self,
12283        ranges: Vec<Range<Anchor>>,
12284        cx: &mut Context<'_, Editor>,
12285    ) {
12286        self.buffer.update(cx, |buffer, cx| {
12287            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12288            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12289        })
12290    }
12291
12292    fn toggle_diff_hunks_in_ranges_narrow(
12293        &mut self,
12294        ranges: Vec<Range<Anchor>>,
12295        cx: &mut Context<'_, Editor>,
12296    ) {
12297        self.buffer.update(cx, |buffer, cx| {
12298            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12299            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12300        })
12301    }
12302
12303    pub(crate) fn apply_all_diff_hunks(
12304        &mut self,
12305        _: &ApplyAllDiffHunks,
12306        window: &mut Window,
12307        cx: &mut Context<Self>,
12308    ) {
12309        let buffers = self.buffer.read(cx).all_buffers();
12310        for branch_buffer in buffers {
12311            branch_buffer.update(cx, |branch_buffer, cx| {
12312                branch_buffer.merge_into_base(Vec::new(), cx);
12313            });
12314        }
12315
12316        if let Some(project) = self.project.clone() {
12317            self.save(true, project, window, cx).detach_and_log_err(cx);
12318        }
12319    }
12320
12321    pub(crate) fn apply_selected_diff_hunks(
12322        &mut self,
12323        _: &ApplyDiffHunk,
12324        window: &mut Window,
12325        cx: &mut Context<Self>,
12326    ) {
12327        let snapshot = self.snapshot(window, cx);
12328        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12329        let mut ranges_by_buffer = HashMap::default();
12330        self.transact(window, cx, |editor, _window, cx| {
12331            for hunk in hunks {
12332                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12333                    ranges_by_buffer
12334                        .entry(buffer.clone())
12335                        .or_insert_with(Vec::new)
12336                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12337                }
12338            }
12339
12340            for (buffer, ranges) in ranges_by_buffer {
12341                buffer.update(cx, |buffer, cx| {
12342                    buffer.merge_into_base(ranges, cx);
12343                });
12344            }
12345        });
12346
12347        if let Some(project) = self.project.clone() {
12348            self.save(true, project, window, cx).detach_and_log_err(cx);
12349        }
12350    }
12351
12352    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12353        if hovered != self.gutter_hovered {
12354            self.gutter_hovered = hovered;
12355            cx.notify();
12356        }
12357    }
12358
12359    pub fn insert_blocks(
12360        &mut self,
12361        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12362        autoscroll: Option<Autoscroll>,
12363        cx: &mut Context<Self>,
12364    ) -> Vec<CustomBlockId> {
12365        let blocks = self
12366            .display_map
12367            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12368        if let Some(autoscroll) = autoscroll {
12369            self.request_autoscroll(autoscroll, cx);
12370        }
12371        cx.notify();
12372        blocks
12373    }
12374
12375    pub fn resize_blocks(
12376        &mut self,
12377        heights: HashMap<CustomBlockId, u32>,
12378        autoscroll: Option<Autoscroll>,
12379        cx: &mut Context<Self>,
12380    ) {
12381        self.display_map
12382            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12383        if let Some(autoscroll) = autoscroll {
12384            self.request_autoscroll(autoscroll, cx);
12385        }
12386        cx.notify();
12387    }
12388
12389    pub fn replace_blocks(
12390        &mut self,
12391        renderers: HashMap<CustomBlockId, RenderBlock>,
12392        autoscroll: Option<Autoscroll>,
12393        cx: &mut Context<Self>,
12394    ) {
12395        self.display_map
12396            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12397        if let Some(autoscroll) = autoscroll {
12398            self.request_autoscroll(autoscroll, cx);
12399        }
12400        cx.notify();
12401    }
12402
12403    pub fn remove_blocks(
12404        &mut self,
12405        block_ids: HashSet<CustomBlockId>,
12406        autoscroll: Option<Autoscroll>,
12407        cx: &mut Context<Self>,
12408    ) {
12409        self.display_map.update(cx, |display_map, cx| {
12410            display_map.remove_blocks(block_ids, cx)
12411        });
12412        if let Some(autoscroll) = autoscroll {
12413            self.request_autoscroll(autoscroll, cx);
12414        }
12415        cx.notify();
12416    }
12417
12418    pub fn row_for_block(
12419        &self,
12420        block_id: CustomBlockId,
12421        cx: &mut Context<Self>,
12422    ) -> Option<DisplayRow> {
12423        self.display_map
12424            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12425    }
12426
12427    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12428        self.focused_block = Some(focused_block);
12429    }
12430
12431    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12432        self.focused_block.take()
12433    }
12434
12435    pub fn insert_creases(
12436        &mut self,
12437        creases: impl IntoIterator<Item = Crease<Anchor>>,
12438        cx: &mut Context<Self>,
12439    ) -> Vec<CreaseId> {
12440        self.display_map
12441            .update(cx, |map, cx| map.insert_creases(creases, cx))
12442    }
12443
12444    pub fn remove_creases(
12445        &mut self,
12446        ids: impl IntoIterator<Item = CreaseId>,
12447        cx: &mut Context<Self>,
12448    ) {
12449        self.display_map
12450            .update(cx, |map, cx| map.remove_creases(ids, cx));
12451    }
12452
12453    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12454        self.display_map
12455            .update(cx, |map, cx| map.snapshot(cx))
12456            .longest_row()
12457    }
12458
12459    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12460        self.display_map
12461            .update(cx, |map, cx| map.snapshot(cx))
12462            .max_point()
12463    }
12464
12465    pub fn text(&self, cx: &App) -> String {
12466        self.buffer.read(cx).read(cx).text()
12467    }
12468
12469    pub fn is_empty(&self, cx: &App) -> bool {
12470        self.buffer.read(cx).read(cx).is_empty()
12471    }
12472
12473    pub fn text_option(&self, cx: &App) -> Option<String> {
12474        let text = self.text(cx);
12475        let text = text.trim();
12476
12477        if text.is_empty() {
12478            return None;
12479        }
12480
12481        Some(text.to_string())
12482    }
12483
12484    pub fn set_text(
12485        &mut self,
12486        text: impl Into<Arc<str>>,
12487        window: &mut Window,
12488        cx: &mut Context<Self>,
12489    ) {
12490        self.transact(window, cx, |this, _, cx| {
12491            this.buffer
12492                .read(cx)
12493                .as_singleton()
12494                .expect("you can only call set_text on editors for singleton buffers")
12495                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12496        });
12497    }
12498
12499    pub fn display_text(&self, cx: &mut App) -> String {
12500        self.display_map
12501            .update(cx, |map, cx| map.snapshot(cx))
12502            .text()
12503    }
12504
12505    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12506        let mut wrap_guides = smallvec::smallvec![];
12507
12508        if self.show_wrap_guides == Some(false) {
12509            return wrap_guides;
12510        }
12511
12512        let settings = self.buffer.read(cx).settings_at(0, cx);
12513        if settings.show_wrap_guides {
12514            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12515                wrap_guides.push((soft_wrap as usize, true));
12516            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12517                wrap_guides.push((soft_wrap as usize, true));
12518            }
12519            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12520        }
12521
12522        wrap_guides
12523    }
12524
12525    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12526        let settings = self.buffer.read(cx).settings_at(0, cx);
12527        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12528        match mode {
12529            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12530                SoftWrap::None
12531            }
12532            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12533            language_settings::SoftWrap::PreferredLineLength => {
12534                SoftWrap::Column(settings.preferred_line_length)
12535            }
12536            language_settings::SoftWrap::Bounded => {
12537                SoftWrap::Bounded(settings.preferred_line_length)
12538            }
12539        }
12540    }
12541
12542    pub fn set_soft_wrap_mode(
12543        &mut self,
12544        mode: language_settings::SoftWrap,
12545
12546        cx: &mut Context<Self>,
12547    ) {
12548        self.soft_wrap_mode_override = Some(mode);
12549        cx.notify();
12550    }
12551
12552    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12553        self.text_style_refinement = Some(style);
12554    }
12555
12556    /// called by the Element so we know what style we were most recently rendered with.
12557    pub(crate) fn set_style(
12558        &mut self,
12559        style: EditorStyle,
12560        window: &mut Window,
12561        cx: &mut Context<Self>,
12562    ) {
12563        let rem_size = window.rem_size();
12564        self.display_map.update(cx, |map, cx| {
12565            map.set_font(
12566                style.text.font(),
12567                style.text.font_size.to_pixels(rem_size),
12568                cx,
12569            )
12570        });
12571        self.style = Some(style);
12572    }
12573
12574    pub fn style(&self) -> Option<&EditorStyle> {
12575        self.style.as_ref()
12576    }
12577
12578    // Called by the element. This method is not designed to be called outside of the editor
12579    // element's layout code because it does not notify when rewrapping is computed synchronously.
12580    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12581        self.display_map
12582            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12583    }
12584
12585    pub fn set_soft_wrap(&mut self) {
12586        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12587    }
12588
12589    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12590        if self.soft_wrap_mode_override.is_some() {
12591            self.soft_wrap_mode_override.take();
12592        } else {
12593            let soft_wrap = match self.soft_wrap_mode(cx) {
12594                SoftWrap::GitDiff => return,
12595                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12596                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12597                    language_settings::SoftWrap::None
12598                }
12599            };
12600            self.soft_wrap_mode_override = Some(soft_wrap);
12601        }
12602        cx.notify();
12603    }
12604
12605    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12606        let Some(workspace) = self.workspace() else {
12607            return;
12608        };
12609        let fs = workspace.read(cx).app_state().fs.clone();
12610        let current_show = TabBarSettings::get_global(cx).show;
12611        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12612            setting.show = Some(!current_show);
12613        });
12614    }
12615
12616    pub fn toggle_indent_guides(
12617        &mut self,
12618        _: &ToggleIndentGuides,
12619        _: &mut Window,
12620        cx: &mut Context<Self>,
12621    ) {
12622        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12623            self.buffer
12624                .read(cx)
12625                .settings_at(0, cx)
12626                .indent_guides
12627                .enabled
12628        });
12629        self.show_indent_guides = Some(!currently_enabled);
12630        cx.notify();
12631    }
12632
12633    fn should_show_indent_guides(&self) -> Option<bool> {
12634        self.show_indent_guides
12635    }
12636
12637    pub fn toggle_line_numbers(
12638        &mut self,
12639        _: &ToggleLineNumbers,
12640        _: &mut Window,
12641        cx: &mut Context<Self>,
12642    ) {
12643        let mut editor_settings = EditorSettings::get_global(cx).clone();
12644        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12645        EditorSettings::override_global(editor_settings, cx);
12646    }
12647
12648    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12649        self.use_relative_line_numbers
12650            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12651    }
12652
12653    pub fn toggle_relative_line_numbers(
12654        &mut self,
12655        _: &ToggleRelativeLineNumbers,
12656        _: &mut Window,
12657        cx: &mut Context<Self>,
12658    ) {
12659        let is_relative = self.should_use_relative_line_numbers(cx);
12660        self.set_relative_line_number(Some(!is_relative), cx)
12661    }
12662
12663    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12664        self.use_relative_line_numbers = is_relative;
12665        cx.notify();
12666    }
12667
12668    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12669        self.show_gutter = show_gutter;
12670        cx.notify();
12671    }
12672
12673    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12674        self.show_scrollbars = show_scrollbars;
12675        cx.notify();
12676    }
12677
12678    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12679        self.show_line_numbers = Some(show_line_numbers);
12680        cx.notify();
12681    }
12682
12683    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12684        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12685        cx.notify();
12686    }
12687
12688    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12689        self.show_code_actions = Some(show_code_actions);
12690        cx.notify();
12691    }
12692
12693    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12694        self.show_runnables = Some(show_runnables);
12695        cx.notify();
12696    }
12697
12698    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12699        if self.display_map.read(cx).masked != masked {
12700            self.display_map.update(cx, |map, _| map.masked = masked);
12701        }
12702        cx.notify()
12703    }
12704
12705    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12706        self.show_wrap_guides = Some(show_wrap_guides);
12707        cx.notify();
12708    }
12709
12710    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12711        self.show_indent_guides = Some(show_indent_guides);
12712        cx.notify();
12713    }
12714
12715    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12716        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12717            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12718                if let Some(dir) = file.abs_path(cx).parent() {
12719                    return Some(dir.to_owned());
12720                }
12721            }
12722
12723            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12724                return Some(project_path.path.to_path_buf());
12725            }
12726        }
12727
12728        None
12729    }
12730
12731    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12732        self.active_excerpt(cx)?
12733            .1
12734            .read(cx)
12735            .file()
12736            .and_then(|f| f.as_local())
12737    }
12738
12739    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12740        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12741            let project_path = buffer.read(cx).project_path(cx)?;
12742            let project = self.project.as_ref()?.read(cx);
12743            project.absolute_path(&project_path, cx)
12744        })
12745    }
12746
12747    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12748        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12749            let project_path = buffer.read(cx).project_path(cx)?;
12750            let project = self.project.as_ref()?.read(cx);
12751            let entry = project.entry_for_path(&project_path, cx)?;
12752            let path = entry.path.to_path_buf();
12753            Some(path)
12754        })
12755    }
12756
12757    pub fn reveal_in_finder(
12758        &mut self,
12759        _: &RevealInFileManager,
12760        _window: &mut Window,
12761        cx: &mut Context<Self>,
12762    ) {
12763        if let Some(target) = self.target_file(cx) {
12764            cx.reveal_path(&target.abs_path(cx));
12765        }
12766    }
12767
12768    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12769        if let Some(path) = self.target_file_abs_path(cx) {
12770            if let Some(path) = path.to_str() {
12771                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12772            }
12773        }
12774    }
12775
12776    pub fn copy_relative_path(
12777        &mut self,
12778        _: &CopyRelativePath,
12779        _window: &mut Window,
12780        cx: &mut Context<Self>,
12781    ) {
12782        if let Some(path) = self.target_file_path(cx) {
12783            if let Some(path) = path.to_str() {
12784                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12785            }
12786        }
12787    }
12788
12789    pub fn toggle_git_blame(
12790        &mut self,
12791        _: &ToggleGitBlame,
12792        window: &mut Window,
12793        cx: &mut Context<Self>,
12794    ) {
12795        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12796
12797        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12798            self.start_git_blame(true, window, cx);
12799        }
12800
12801        cx.notify();
12802    }
12803
12804    pub fn toggle_git_blame_inline(
12805        &mut self,
12806        _: &ToggleGitBlameInline,
12807        window: &mut Window,
12808        cx: &mut Context<Self>,
12809    ) {
12810        self.toggle_git_blame_inline_internal(true, window, cx);
12811        cx.notify();
12812    }
12813
12814    pub fn git_blame_inline_enabled(&self) -> bool {
12815        self.git_blame_inline_enabled
12816    }
12817
12818    pub fn toggle_selection_menu(
12819        &mut self,
12820        _: &ToggleSelectionMenu,
12821        _: &mut Window,
12822        cx: &mut Context<Self>,
12823    ) {
12824        self.show_selection_menu = self
12825            .show_selection_menu
12826            .map(|show_selections_menu| !show_selections_menu)
12827            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12828
12829        cx.notify();
12830    }
12831
12832    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12833        self.show_selection_menu
12834            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12835    }
12836
12837    fn start_git_blame(
12838        &mut self,
12839        user_triggered: bool,
12840        window: &mut Window,
12841        cx: &mut Context<Self>,
12842    ) {
12843        if let Some(project) = self.project.as_ref() {
12844            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12845                return;
12846            };
12847
12848            if buffer.read(cx).file().is_none() {
12849                return;
12850            }
12851
12852            let focused = self.focus_handle(cx).contains_focused(window, cx);
12853
12854            let project = project.clone();
12855            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12856            self.blame_subscription =
12857                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12858            self.blame = Some(blame);
12859        }
12860    }
12861
12862    fn toggle_git_blame_inline_internal(
12863        &mut self,
12864        user_triggered: bool,
12865        window: &mut Window,
12866        cx: &mut Context<Self>,
12867    ) {
12868        if self.git_blame_inline_enabled {
12869            self.git_blame_inline_enabled = false;
12870            self.show_git_blame_inline = false;
12871            self.show_git_blame_inline_delay_task.take();
12872        } else {
12873            self.git_blame_inline_enabled = true;
12874            self.start_git_blame_inline(user_triggered, window, cx);
12875        }
12876
12877        cx.notify();
12878    }
12879
12880    fn start_git_blame_inline(
12881        &mut self,
12882        user_triggered: bool,
12883        window: &mut Window,
12884        cx: &mut Context<Self>,
12885    ) {
12886        self.start_git_blame(user_triggered, window, cx);
12887
12888        if ProjectSettings::get_global(cx)
12889            .git
12890            .inline_blame_delay()
12891            .is_some()
12892        {
12893            self.start_inline_blame_timer(window, cx);
12894        } else {
12895            self.show_git_blame_inline = true
12896        }
12897    }
12898
12899    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12900        self.blame.as_ref()
12901    }
12902
12903    pub fn show_git_blame_gutter(&self) -> bool {
12904        self.show_git_blame_gutter
12905    }
12906
12907    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12908        self.show_git_blame_gutter && self.has_blame_entries(cx)
12909    }
12910
12911    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12912        self.show_git_blame_inline
12913            && self.focus_handle.is_focused(window)
12914            && !self.newest_selection_head_on_empty_line(cx)
12915            && self.has_blame_entries(cx)
12916    }
12917
12918    fn has_blame_entries(&self, cx: &App) -> bool {
12919        self.blame()
12920            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12921    }
12922
12923    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12924        let cursor_anchor = self.selections.newest_anchor().head();
12925
12926        let snapshot = self.buffer.read(cx).snapshot(cx);
12927        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12928
12929        snapshot.line_len(buffer_row) == 0
12930    }
12931
12932    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12933        let buffer_and_selection = maybe!({
12934            let selection = self.selections.newest::<Point>(cx);
12935            let selection_range = selection.range();
12936
12937            let multi_buffer = self.buffer().read(cx);
12938            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12939            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12940
12941            let (buffer, range, _) = if selection.reversed {
12942                buffer_ranges.first()
12943            } else {
12944                buffer_ranges.last()
12945            }?;
12946
12947            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12948                ..text::ToPoint::to_point(&range.end, &buffer).row;
12949            Some((
12950                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12951                selection,
12952            ))
12953        });
12954
12955        let Some((buffer, selection)) = buffer_and_selection else {
12956            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12957        };
12958
12959        let Some(project) = self.project.as_ref() else {
12960            return Task::ready(Err(anyhow!("editor does not have project")));
12961        };
12962
12963        project.update(cx, |project, cx| {
12964            project.get_permalink_to_line(&buffer, selection, cx)
12965        })
12966    }
12967
12968    pub fn copy_permalink_to_line(
12969        &mut self,
12970        _: &CopyPermalinkToLine,
12971        window: &mut Window,
12972        cx: &mut Context<Self>,
12973    ) {
12974        let permalink_task = self.get_permalink_to_line(cx);
12975        let workspace = self.workspace();
12976
12977        cx.spawn_in(window, |_, mut cx| async move {
12978            match permalink_task.await {
12979                Ok(permalink) => {
12980                    cx.update(|_, cx| {
12981                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12982                    })
12983                    .ok();
12984                }
12985                Err(err) => {
12986                    let message = format!("Failed to copy permalink: {err}");
12987
12988                    Err::<(), anyhow::Error>(err).log_err();
12989
12990                    if let Some(workspace) = workspace {
12991                        workspace
12992                            .update_in(&mut cx, |workspace, _, cx| {
12993                                struct CopyPermalinkToLine;
12994
12995                                workspace.show_toast(
12996                                    Toast::new(
12997                                        NotificationId::unique::<CopyPermalinkToLine>(),
12998                                        message,
12999                                    ),
13000                                    cx,
13001                                )
13002                            })
13003                            .ok();
13004                    }
13005                }
13006            }
13007        })
13008        .detach();
13009    }
13010
13011    pub fn copy_file_location(
13012        &mut self,
13013        _: &CopyFileLocation,
13014        _: &mut Window,
13015        cx: &mut Context<Self>,
13016    ) {
13017        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13018        if let Some(file) = self.target_file(cx) {
13019            if let Some(path) = file.path().to_str() {
13020                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13021            }
13022        }
13023    }
13024
13025    pub fn open_permalink_to_line(
13026        &mut self,
13027        _: &OpenPermalinkToLine,
13028        window: &mut Window,
13029        cx: &mut Context<Self>,
13030    ) {
13031        let permalink_task = self.get_permalink_to_line(cx);
13032        let workspace = self.workspace();
13033
13034        cx.spawn_in(window, |_, mut cx| async move {
13035            match permalink_task.await {
13036                Ok(permalink) => {
13037                    cx.update(|_, cx| {
13038                        cx.open_url(permalink.as_ref());
13039                    })
13040                    .ok();
13041                }
13042                Err(err) => {
13043                    let message = format!("Failed to open permalink: {err}");
13044
13045                    Err::<(), anyhow::Error>(err).log_err();
13046
13047                    if let Some(workspace) = workspace {
13048                        workspace
13049                            .update(&mut cx, |workspace, cx| {
13050                                struct OpenPermalinkToLine;
13051
13052                                workspace.show_toast(
13053                                    Toast::new(
13054                                        NotificationId::unique::<OpenPermalinkToLine>(),
13055                                        message,
13056                                    ),
13057                                    cx,
13058                                )
13059                            })
13060                            .ok();
13061                    }
13062                }
13063            }
13064        })
13065        .detach();
13066    }
13067
13068    pub fn insert_uuid_v4(
13069        &mut self,
13070        _: &InsertUuidV4,
13071        window: &mut Window,
13072        cx: &mut Context<Self>,
13073    ) {
13074        self.insert_uuid(UuidVersion::V4, window, cx);
13075    }
13076
13077    pub fn insert_uuid_v7(
13078        &mut self,
13079        _: &InsertUuidV7,
13080        window: &mut Window,
13081        cx: &mut Context<Self>,
13082    ) {
13083        self.insert_uuid(UuidVersion::V7, window, cx);
13084    }
13085
13086    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13087        self.transact(window, cx, |this, window, cx| {
13088            let edits = this
13089                .selections
13090                .all::<Point>(cx)
13091                .into_iter()
13092                .map(|selection| {
13093                    let uuid = match version {
13094                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13095                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13096                    };
13097
13098                    (selection.range(), uuid.to_string())
13099                });
13100            this.edit(edits, cx);
13101            this.refresh_inline_completion(true, false, window, cx);
13102        });
13103    }
13104
13105    pub fn open_selections_in_multibuffer(
13106        &mut self,
13107        _: &OpenSelectionsInMultibuffer,
13108        window: &mut Window,
13109        cx: &mut Context<Self>,
13110    ) {
13111        let multibuffer = self.buffer.read(cx);
13112
13113        let Some(buffer) = multibuffer.as_singleton() else {
13114            return;
13115        };
13116
13117        let Some(workspace) = self.workspace() else {
13118            return;
13119        };
13120
13121        let locations = self
13122            .selections
13123            .disjoint_anchors()
13124            .iter()
13125            .map(|range| Location {
13126                buffer: buffer.clone(),
13127                range: range.start.text_anchor..range.end.text_anchor,
13128            })
13129            .collect::<Vec<_>>();
13130
13131        let title = multibuffer.title(cx).to_string();
13132
13133        cx.spawn_in(window, |_, mut cx| async move {
13134            workspace.update_in(&mut cx, |workspace, window, cx| {
13135                Self::open_locations_in_multibuffer(
13136                    workspace,
13137                    locations,
13138                    format!("Selections for '{title}'"),
13139                    false,
13140                    MultibufferSelectionMode::All,
13141                    window,
13142                    cx,
13143                );
13144            })
13145        })
13146        .detach();
13147    }
13148
13149    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13150    /// last highlight added will be used.
13151    ///
13152    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13153    pub fn highlight_rows<T: 'static>(
13154        &mut self,
13155        range: Range<Anchor>,
13156        color: Hsla,
13157        should_autoscroll: bool,
13158        cx: &mut Context<Self>,
13159    ) {
13160        let snapshot = self.buffer().read(cx).snapshot(cx);
13161        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13162        let ix = row_highlights.binary_search_by(|highlight| {
13163            Ordering::Equal
13164                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13165                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13166        });
13167
13168        if let Err(mut ix) = ix {
13169            let index = post_inc(&mut self.highlight_order);
13170
13171            // If this range intersects with the preceding highlight, then merge it with
13172            // the preceding highlight. Otherwise insert a new highlight.
13173            let mut merged = false;
13174            if ix > 0 {
13175                let prev_highlight = &mut row_highlights[ix - 1];
13176                if prev_highlight
13177                    .range
13178                    .end
13179                    .cmp(&range.start, &snapshot)
13180                    .is_ge()
13181                {
13182                    ix -= 1;
13183                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13184                        prev_highlight.range.end = range.end;
13185                    }
13186                    merged = true;
13187                    prev_highlight.index = index;
13188                    prev_highlight.color = color;
13189                    prev_highlight.should_autoscroll = should_autoscroll;
13190                }
13191            }
13192
13193            if !merged {
13194                row_highlights.insert(
13195                    ix,
13196                    RowHighlight {
13197                        range: range.clone(),
13198                        index,
13199                        color,
13200                        should_autoscroll,
13201                    },
13202                );
13203            }
13204
13205            // If any of the following highlights intersect with this one, merge them.
13206            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13207                let highlight = &row_highlights[ix];
13208                if next_highlight
13209                    .range
13210                    .start
13211                    .cmp(&highlight.range.end, &snapshot)
13212                    .is_le()
13213                {
13214                    if next_highlight
13215                        .range
13216                        .end
13217                        .cmp(&highlight.range.end, &snapshot)
13218                        .is_gt()
13219                    {
13220                        row_highlights[ix].range.end = next_highlight.range.end;
13221                    }
13222                    row_highlights.remove(ix + 1);
13223                } else {
13224                    break;
13225                }
13226            }
13227        }
13228    }
13229
13230    /// Remove any highlighted row ranges of the given type that intersect the
13231    /// given ranges.
13232    pub fn remove_highlighted_rows<T: 'static>(
13233        &mut self,
13234        ranges_to_remove: Vec<Range<Anchor>>,
13235        cx: &mut Context<Self>,
13236    ) {
13237        let snapshot = self.buffer().read(cx).snapshot(cx);
13238        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13239        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13240        row_highlights.retain(|highlight| {
13241            while let Some(range_to_remove) = ranges_to_remove.peek() {
13242                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13243                    Ordering::Less | Ordering::Equal => {
13244                        ranges_to_remove.next();
13245                    }
13246                    Ordering::Greater => {
13247                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13248                            Ordering::Less | Ordering::Equal => {
13249                                return false;
13250                            }
13251                            Ordering::Greater => break,
13252                        }
13253                    }
13254                }
13255            }
13256
13257            true
13258        })
13259    }
13260
13261    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13262    pub fn clear_row_highlights<T: 'static>(&mut self) {
13263        self.highlighted_rows.remove(&TypeId::of::<T>());
13264    }
13265
13266    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13267    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13268        self.highlighted_rows
13269            .get(&TypeId::of::<T>())
13270            .map_or(&[] as &[_], |vec| vec.as_slice())
13271            .iter()
13272            .map(|highlight| (highlight.range.clone(), highlight.color))
13273    }
13274
13275    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13276    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13277    /// Allows to ignore certain kinds of highlights.
13278    pub fn highlighted_display_rows(
13279        &self,
13280        window: &mut Window,
13281        cx: &mut App,
13282    ) -> BTreeMap<DisplayRow, Hsla> {
13283        let snapshot = self.snapshot(window, cx);
13284        let mut used_highlight_orders = HashMap::default();
13285        self.highlighted_rows
13286            .iter()
13287            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13288            .fold(
13289                BTreeMap::<DisplayRow, Hsla>::new(),
13290                |mut unique_rows, highlight| {
13291                    let start = highlight.range.start.to_display_point(&snapshot);
13292                    let end = highlight.range.end.to_display_point(&snapshot);
13293                    let start_row = start.row().0;
13294                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13295                        && end.column() == 0
13296                    {
13297                        end.row().0.saturating_sub(1)
13298                    } else {
13299                        end.row().0
13300                    };
13301                    for row in start_row..=end_row {
13302                        let used_index =
13303                            used_highlight_orders.entry(row).or_insert(highlight.index);
13304                        if highlight.index >= *used_index {
13305                            *used_index = highlight.index;
13306                            unique_rows.insert(DisplayRow(row), highlight.color);
13307                        }
13308                    }
13309                    unique_rows
13310                },
13311            )
13312    }
13313
13314    pub fn highlighted_display_row_for_autoscroll(
13315        &self,
13316        snapshot: &DisplaySnapshot,
13317    ) -> Option<DisplayRow> {
13318        self.highlighted_rows
13319            .values()
13320            .flat_map(|highlighted_rows| highlighted_rows.iter())
13321            .filter_map(|highlight| {
13322                if highlight.should_autoscroll {
13323                    Some(highlight.range.start.to_display_point(snapshot).row())
13324                } else {
13325                    None
13326                }
13327            })
13328            .min()
13329    }
13330
13331    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13332        self.highlight_background::<SearchWithinRange>(
13333            ranges,
13334            |colors| colors.editor_document_highlight_read_background,
13335            cx,
13336        )
13337    }
13338
13339    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13340        self.breadcrumb_header = Some(new_header);
13341    }
13342
13343    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13344        self.clear_background_highlights::<SearchWithinRange>(cx);
13345    }
13346
13347    pub fn highlight_background<T: 'static>(
13348        &mut self,
13349        ranges: &[Range<Anchor>],
13350        color_fetcher: fn(&ThemeColors) -> Hsla,
13351        cx: &mut Context<Self>,
13352    ) {
13353        self.background_highlights
13354            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13355        self.scrollbar_marker_state.dirty = true;
13356        cx.notify();
13357    }
13358
13359    pub fn clear_background_highlights<T: 'static>(
13360        &mut self,
13361        cx: &mut Context<Self>,
13362    ) -> Option<BackgroundHighlight> {
13363        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13364        if !text_highlights.1.is_empty() {
13365            self.scrollbar_marker_state.dirty = true;
13366            cx.notify();
13367        }
13368        Some(text_highlights)
13369    }
13370
13371    pub fn highlight_gutter<T: 'static>(
13372        &mut self,
13373        ranges: &[Range<Anchor>],
13374        color_fetcher: fn(&App) -> Hsla,
13375        cx: &mut Context<Self>,
13376    ) {
13377        self.gutter_highlights
13378            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13379        cx.notify();
13380    }
13381
13382    pub fn clear_gutter_highlights<T: 'static>(
13383        &mut self,
13384        cx: &mut Context<Self>,
13385    ) -> Option<GutterHighlight> {
13386        cx.notify();
13387        self.gutter_highlights.remove(&TypeId::of::<T>())
13388    }
13389
13390    #[cfg(feature = "test-support")]
13391    pub fn all_text_background_highlights(
13392        &self,
13393        window: &mut Window,
13394        cx: &mut Context<Self>,
13395    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13396        let snapshot = self.snapshot(window, cx);
13397        let buffer = &snapshot.buffer_snapshot;
13398        let start = buffer.anchor_before(0);
13399        let end = buffer.anchor_after(buffer.len());
13400        let theme = cx.theme().colors();
13401        self.background_highlights_in_range(start..end, &snapshot, theme)
13402    }
13403
13404    #[cfg(feature = "test-support")]
13405    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13406        let snapshot = self.buffer().read(cx).snapshot(cx);
13407
13408        let highlights = self
13409            .background_highlights
13410            .get(&TypeId::of::<items::BufferSearchHighlights>());
13411
13412        if let Some((_color, ranges)) = highlights {
13413            ranges
13414                .iter()
13415                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13416                .collect_vec()
13417        } else {
13418            vec![]
13419        }
13420    }
13421
13422    fn document_highlights_for_position<'a>(
13423        &'a self,
13424        position: Anchor,
13425        buffer: &'a MultiBufferSnapshot,
13426    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13427        let read_highlights = self
13428            .background_highlights
13429            .get(&TypeId::of::<DocumentHighlightRead>())
13430            .map(|h| &h.1);
13431        let write_highlights = self
13432            .background_highlights
13433            .get(&TypeId::of::<DocumentHighlightWrite>())
13434            .map(|h| &h.1);
13435        let left_position = position.bias_left(buffer);
13436        let right_position = position.bias_right(buffer);
13437        read_highlights
13438            .into_iter()
13439            .chain(write_highlights)
13440            .flat_map(move |ranges| {
13441                let start_ix = match ranges.binary_search_by(|probe| {
13442                    let cmp = probe.end.cmp(&left_position, buffer);
13443                    if cmp.is_ge() {
13444                        Ordering::Greater
13445                    } else {
13446                        Ordering::Less
13447                    }
13448                }) {
13449                    Ok(i) | Err(i) => i,
13450                };
13451
13452                ranges[start_ix..]
13453                    .iter()
13454                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13455            })
13456    }
13457
13458    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13459        self.background_highlights
13460            .get(&TypeId::of::<T>())
13461            .map_or(false, |(_, highlights)| !highlights.is_empty())
13462    }
13463
13464    pub fn background_highlights_in_range(
13465        &self,
13466        search_range: Range<Anchor>,
13467        display_snapshot: &DisplaySnapshot,
13468        theme: &ThemeColors,
13469    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13470        let mut results = Vec::new();
13471        for (color_fetcher, ranges) in self.background_highlights.values() {
13472            let color = color_fetcher(theme);
13473            let start_ix = match ranges.binary_search_by(|probe| {
13474                let cmp = probe
13475                    .end
13476                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13477                if cmp.is_gt() {
13478                    Ordering::Greater
13479                } else {
13480                    Ordering::Less
13481                }
13482            }) {
13483                Ok(i) | Err(i) => i,
13484            };
13485            for range in &ranges[start_ix..] {
13486                if range
13487                    .start
13488                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13489                    .is_ge()
13490                {
13491                    break;
13492                }
13493
13494                let start = range.start.to_display_point(display_snapshot);
13495                let end = range.end.to_display_point(display_snapshot);
13496                results.push((start..end, color))
13497            }
13498        }
13499        results
13500    }
13501
13502    pub fn background_highlight_row_ranges<T: 'static>(
13503        &self,
13504        search_range: Range<Anchor>,
13505        display_snapshot: &DisplaySnapshot,
13506        count: usize,
13507    ) -> Vec<RangeInclusive<DisplayPoint>> {
13508        let mut results = Vec::new();
13509        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13510            return vec![];
13511        };
13512
13513        let start_ix = match ranges.binary_search_by(|probe| {
13514            let cmp = probe
13515                .end
13516                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13517            if cmp.is_gt() {
13518                Ordering::Greater
13519            } else {
13520                Ordering::Less
13521            }
13522        }) {
13523            Ok(i) | Err(i) => i,
13524        };
13525        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13526            if let (Some(start_display), Some(end_display)) = (start, end) {
13527                results.push(
13528                    start_display.to_display_point(display_snapshot)
13529                        ..=end_display.to_display_point(display_snapshot),
13530                );
13531            }
13532        };
13533        let mut start_row: Option<Point> = None;
13534        let mut end_row: Option<Point> = None;
13535        if ranges.len() > count {
13536            return Vec::new();
13537        }
13538        for range in &ranges[start_ix..] {
13539            if range
13540                .start
13541                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13542                .is_ge()
13543            {
13544                break;
13545            }
13546            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13547            if let Some(current_row) = &end_row {
13548                if end.row == current_row.row {
13549                    continue;
13550                }
13551            }
13552            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13553            if start_row.is_none() {
13554                assert_eq!(end_row, None);
13555                start_row = Some(start);
13556                end_row = Some(end);
13557                continue;
13558            }
13559            if let Some(current_end) = end_row.as_mut() {
13560                if start.row > current_end.row + 1 {
13561                    push_region(start_row, end_row);
13562                    start_row = Some(start);
13563                    end_row = Some(end);
13564                } else {
13565                    // Merge two hunks.
13566                    *current_end = end;
13567                }
13568            } else {
13569                unreachable!();
13570            }
13571        }
13572        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13573        push_region(start_row, end_row);
13574        results
13575    }
13576
13577    pub fn gutter_highlights_in_range(
13578        &self,
13579        search_range: Range<Anchor>,
13580        display_snapshot: &DisplaySnapshot,
13581        cx: &App,
13582    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13583        let mut results = Vec::new();
13584        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13585            let color = color_fetcher(cx);
13586            let start_ix = match ranges.binary_search_by(|probe| {
13587                let cmp = probe
13588                    .end
13589                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13590                if cmp.is_gt() {
13591                    Ordering::Greater
13592                } else {
13593                    Ordering::Less
13594                }
13595            }) {
13596                Ok(i) | Err(i) => i,
13597            };
13598            for range in &ranges[start_ix..] {
13599                if range
13600                    .start
13601                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13602                    .is_ge()
13603                {
13604                    break;
13605                }
13606
13607                let start = range.start.to_display_point(display_snapshot);
13608                let end = range.end.to_display_point(display_snapshot);
13609                results.push((start..end, color))
13610            }
13611        }
13612        results
13613    }
13614
13615    /// Get the text ranges corresponding to the redaction query
13616    pub fn redacted_ranges(
13617        &self,
13618        search_range: Range<Anchor>,
13619        display_snapshot: &DisplaySnapshot,
13620        cx: &App,
13621    ) -> Vec<Range<DisplayPoint>> {
13622        display_snapshot
13623            .buffer_snapshot
13624            .redacted_ranges(search_range, |file| {
13625                if let Some(file) = file {
13626                    file.is_private()
13627                        && EditorSettings::get(
13628                            Some(SettingsLocation {
13629                                worktree_id: file.worktree_id(cx),
13630                                path: file.path().as_ref(),
13631                            }),
13632                            cx,
13633                        )
13634                        .redact_private_values
13635                } else {
13636                    false
13637                }
13638            })
13639            .map(|range| {
13640                range.start.to_display_point(display_snapshot)
13641                    ..range.end.to_display_point(display_snapshot)
13642            })
13643            .collect()
13644    }
13645
13646    pub fn highlight_text<T: 'static>(
13647        &mut self,
13648        ranges: Vec<Range<Anchor>>,
13649        style: HighlightStyle,
13650        cx: &mut Context<Self>,
13651    ) {
13652        self.display_map.update(cx, |map, _| {
13653            map.highlight_text(TypeId::of::<T>(), ranges, style)
13654        });
13655        cx.notify();
13656    }
13657
13658    pub(crate) fn highlight_inlays<T: 'static>(
13659        &mut self,
13660        highlights: Vec<InlayHighlight>,
13661        style: HighlightStyle,
13662        cx: &mut Context<Self>,
13663    ) {
13664        self.display_map.update(cx, |map, _| {
13665            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13666        });
13667        cx.notify();
13668    }
13669
13670    pub fn text_highlights<'a, T: 'static>(
13671        &'a self,
13672        cx: &'a App,
13673    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13674        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13675    }
13676
13677    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13678        let cleared = self
13679            .display_map
13680            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13681        if cleared {
13682            cx.notify();
13683        }
13684    }
13685
13686    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13687        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13688            && self.focus_handle.is_focused(window)
13689    }
13690
13691    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13692        self.show_cursor_when_unfocused = is_enabled;
13693        cx.notify();
13694    }
13695
13696    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13697        self.project
13698            .as_ref()
13699            .map(|project| project.read(cx).lsp_store())
13700    }
13701
13702    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13703        cx.notify();
13704    }
13705
13706    fn on_buffer_event(
13707        &mut self,
13708        multibuffer: &Entity<MultiBuffer>,
13709        event: &multi_buffer::Event,
13710        window: &mut Window,
13711        cx: &mut Context<Self>,
13712    ) {
13713        match event {
13714            multi_buffer::Event::Edited {
13715                singleton_buffer_edited,
13716                edited_buffer: buffer_edited,
13717            } => {
13718                self.scrollbar_marker_state.dirty = true;
13719                self.active_indent_guides_state.dirty = true;
13720                self.refresh_active_diagnostics(cx);
13721                self.refresh_code_actions(window, cx);
13722                if self.has_active_inline_completion() {
13723                    self.update_visible_inline_completion(window, cx);
13724                }
13725                if let Some(buffer) = buffer_edited {
13726                    let buffer_id = buffer.read(cx).remote_id();
13727                    if !self.registered_buffers.contains_key(&buffer_id) {
13728                        if let Some(lsp_store) = self.lsp_store(cx) {
13729                            lsp_store.update(cx, |lsp_store, cx| {
13730                                self.registered_buffers.insert(
13731                                    buffer_id,
13732                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13733                                );
13734                            })
13735                        }
13736                    }
13737                }
13738                cx.emit(EditorEvent::BufferEdited);
13739                cx.emit(SearchEvent::MatchesInvalidated);
13740                if *singleton_buffer_edited {
13741                    if let Some(project) = &self.project {
13742                        let project = project.read(cx);
13743                        #[allow(clippy::mutable_key_type)]
13744                        let languages_affected = multibuffer
13745                            .read(cx)
13746                            .all_buffers()
13747                            .into_iter()
13748                            .filter_map(|buffer| {
13749                                let buffer = buffer.read(cx);
13750                                let language = buffer.language()?;
13751                                if project.is_local()
13752                                    && project
13753                                        .language_servers_for_local_buffer(buffer, cx)
13754                                        .count()
13755                                        == 0
13756                                {
13757                                    None
13758                                } else {
13759                                    Some(language)
13760                                }
13761                            })
13762                            .cloned()
13763                            .collect::<HashSet<_>>();
13764                        if !languages_affected.is_empty() {
13765                            self.refresh_inlay_hints(
13766                                InlayHintRefreshReason::BufferEdited(languages_affected),
13767                                cx,
13768                            );
13769                        }
13770                    }
13771                }
13772
13773                let Some(project) = &self.project else { return };
13774                let (telemetry, is_via_ssh) = {
13775                    let project = project.read(cx);
13776                    let telemetry = project.client().telemetry().clone();
13777                    let is_via_ssh = project.is_via_ssh();
13778                    (telemetry, is_via_ssh)
13779                };
13780                refresh_linked_ranges(self, window, cx);
13781                telemetry.log_edit_event("editor", is_via_ssh);
13782            }
13783            multi_buffer::Event::ExcerptsAdded {
13784                buffer,
13785                predecessor,
13786                excerpts,
13787            } => {
13788                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13789                let buffer_id = buffer.read(cx).remote_id();
13790                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13791                    if let Some(project) = &self.project {
13792                        get_uncommitted_diff_for_buffer(
13793                            project,
13794                            [buffer.clone()],
13795                            self.buffer.clone(),
13796                            cx,
13797                        );
13798                    }
13799                }
13800                cx.emit(EditorEvent::ExcerptsAdded {
13801                    buffer: buffer.clone(),
13802                    predecessor: *predecessor,
13803                    excerpts: excerpts.clone(),
13804                });
13805                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13806            }
13807            multi_buffer::Event::ExcerptsRemoved { ids } => {
13808                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13809                let buffer = self.buffer.read(cx);
13810                self.registered_buffers
13811                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13812                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13813            }
13814            multi_buffer::Event::ExcerptsEdited { ids } => {
13815                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13816            }
13817            multi_buffer::Event::ExcerptsExpanded { ids } => {
13818                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13819                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13820            }
13821            multi_buffer::Event::Reparsed(buffer_id) => {
13822                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13823
13824                cx.emit(EditorEvent::Reparsed(*buffer_id));
13825            }
13826            multi_buffer::Event::DiffHunksToggled => {
13827                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13828            }
13829            multi_buffer::Event::LanguageChanged(buffer_id) => {
13830                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13831                cx.emit(EditorEvent::Reparsed(*buffer_id));
13832                cx.notify();
13833            }
13834            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13835            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13836            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13837                cx.emit(EditorEvent::TitleChanged)
13838            }
13839            // multi_buffer::Event::DiffBaseChanged => {
13840            //     self.scrollbar_marker_state.dirty = true;
13841            //     cx.emit(EditorEvent::DiffBaseChanged);
13842            //     cx.notify();
13843            // }
13844            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13845            multi_buffer::Event::DiagnosticsUpdated => {
13846                self.refresh_active_diagnostics(cx);
13847                self.scrollbar_marker_state.dirty = true;
13848                cx.notify();
13849            }
13850            _ => {}
13851        };
13852    }
13853
13854    fn on_display_map_changed(
13855        &mut self,
13856        _: Entity<DisplayMap>,
13857        _: &mut Window,
13858        cx: &mut Context<Self>,
13859    ) {
13860        cx.notify();
13861    }
13862
13863    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13864        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13865        self.refresh_inline_completion(true, false, window, cx);
13866        self.refresh_inlay_hints(
13867            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13868                self.selections.newest_anchor().head(),
13869                &self.buffer.read(cx).snapshot(cx),
13870                cx,
13871            )),
13872            cx,
13873        );
13874
13875        let old_cursor_shape = self.cursor_shape;
13876
13877        {
13878            let editor_settings = EditorSettings::get_global(cx);
13879            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13880            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13881            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13882        }
13883
13884        if old_cursor_shape != self.cursor_shape {
13885            cx.emit(EditorEvent::CursorShapeChanged);
13886        }
13887
13888        let project_settings = ProjectSettings::get_global(cx);
13889        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13890
13891        if self.mode == EditorMode::Full {
13892            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13893            if self.git_blame_inline_enabled != inline_blame_enabled {
13894                self.toggle_git_blame_inline_internal(false, window, cx);
13895            }
13896        }
13897
13898        cx.notify();
13899    }
13900
13901    pub fn set_searchable(&mut self, searchable: bool) {
13902        self.searchable = searchable;
13903    }
13904
13905    pub fn searchable(&self) -> bool {
13906        self.searchable
13907    }
13908
13909    fn open_proposed_changes_editor(
13910        &mut self,
13911        _: &OpenProposedChangesEditor,
13912        window: &mut Window,
13913        cx: &mut Context<Self>,
13914    ) {
13915        let Some(workspace) = self.workspace() else {
13916            cx.propagate();
13917            return;
13918        };
13919
13920        let selections = self.selections.all::<usize>(cx);
13921        let multi_buffer = self.buffer.read(cx);
13922        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13923        let mut new_selections_by_buffer = HashMap::default();
13924        for selection in selections {
13925            for (buffer, range, _) in
13926                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13927            {
13928                let mut range = range.to_point(buffer);
13929                range.start.column = 0;
13930                range.end.column = buffer.line_len(range.end.row);
13931                new_selections_by_buffer
13932                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13933                    .or_insert(Vec::new())
13934                    .push(range)
13935            }
13936        }
13937
13938        let proposed_changes_buffers = new_selections_by_buffer
13939            .into_iter()
13940            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13941            .collect::<Vec<_>>();
13942        let proposed_changes_editor = cx.new(|cx| {
13943            ProposedChangesEditor::new(
13944                "Proposed changes",
13945                proposed_changes_buffers,
13946                self.project.clone(),
13947                window,
13948                cx,
13949            )
13950        });
13951
13952        window.defer(cx, move |window, cx| {
13953            workspace.update(cx, |workspace, cx| {
13954                workspace.active_pane().update(cx, |pane, cx| {
13955                    pane.add_item(
13956                        Box::new(proposed_changes_editor),
13957                        true,
13958                        true,
13959                        None,
13960                        window,
13961                        cx,
13962                    );
13963                });
13964            });
13965        });
13966    }
13967
13968    pub fn open_excerpts_in_split(
13969        &mut self,
13970        _: &OpenExcerptsSplit,
13971        window: &mut Window,
13972        cx: &mut Context<Self>,
13973    ) {
13974        self.open_excerpts_common(None, true, window, cx)
13975    }
13976
13977    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13978        self.open_excerpts_common(None, false, window, cx)
13979    }
13980
13981    fn open_excerpts_common(
13982        &mut self,
13983        jump_data: Option<JumpData>,
13984        split: bool,
13985        window: &mut Window,
13986        cx: &mut Context<Self>,
13987    ) {
13988        let Some(workspace) = self.workspace() else {
13989            cx.propagate();
13990            return;
13991        };
13992
13993        if self.buffer.read(cx).is_singleton() {
13994            cx.propagate();
13995            return;
13996        }
13997
13998        let mut new_selections_by_buffer = HashMap::default();
13999        match &jump_data {
14000            Some(JumpData::MultiBufferPoint {
14001                excerpt_id,
14002                position,
14003                anchor,
14004                line_offset_from_top,
14005            }) => {
14006                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14007                if let Some(buffer) = multi_buffer_snapshot
14008                    .buffer_id_for_excerpt(*excerpt_id)
14009                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14010                {
14011                    let buffer_snapshot = buffer.read(cx).snapshot();
14012                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14013                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14014                    } else {
14015                        buffer_snapshot.clip_point(*position, Bias::Left)
14016                    };
14017                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14018                    new_selections_by_buffer.insert(
14019                        buffer,
14020                        (
14021                            vec![jump_to_offset..jump_to_offset],
14022                            Some(*line_offset_from_top),
14023                        ),
14024                    );
14025                }
14026            }
14027            Some(JumpData::MultiBufferRow {
14028                row,
14029                line_offset_from_top,
14030            }) => {
14031                let point = MultiBufferPoint::new(row.0, 0);
14032                if let Some((buffer, buffer_point, _)) =
14033                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14034                {
14035                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14036                    new_selections_by_buffer
14037                        .entry(buffer)
14038                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14039                        .0
14040                        .push(buffer_offset..buffer_offset)
14041                }
14042            }
14043            None => {
14044                let selections = self.selections.all::<usize>(cx);
14045                let multi_buffer = self.buffer.read(cx);
14046                for selection in selections {
14047                    for (buffer, mut range, _) in multi_buffer
14048                        .snapshot(cx)
14049                        .range_to_buffer_ranges(selection.range())
14050                    {
14051                        // When editing branch buffers, jump to the corresponding location
14052                        // in their base buffer.
14053                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14054                        let buffer = buffer_handle.read(cx);
14055                        if let Some(base_buffer) = buffer.base_buffer() {
14056                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14057                            buffer_handle = base_buffer;
14058                        }
14059
14060                        if selection.reversed {
14061                            mem::swap(&mut range.start, &mut range.end);
14062                        }
14063                        new_selections_by_buffer
14064                            .entry(buffer_handle)
14065                            .or_insert((Vec::new(), None))
14066                            .0
14067                            .push(range)
14068                    }
14069                }
14070            }
14071        }
14072
14073        if new_selections_by_buffer.is_empty() {
14074            return;
14075        }
14076
14077        // We defer the pane interaction because we ourselves are a workspace item
14078        // and activating a new item causes the pane to call a method on us reentrantly,
14079        // which panics if we're on the stack.
14080        window.defer(cx, move |window, cx| {
14081            workspace.update(cx, |workspace, cx| {
14082                let pane = if split {
14083                    workspace.adjacent_pane(window, cx)
14084                } else {
14085                    workspace.active_pane().clone()
14086                };
14087
14088                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14089                    let editor = buffer
14090                        .read(cx)
14091                        .file()
14092                        .is_none()
14093                        .then(|| {
14094                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14095                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14096                            // Instead, we try to activate the existing editor in the pane first.
14097                            let (editor, pane_item_index) =
14098                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14099                                    let editor = item.downcast::<Editor>()?;
14100                                    let singleton_buffer =
14101                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14102                                    if singleton_buffer == buffer {
14103                                        Some((editor, i))
14104                                    } else {
14105                                        None
14106                                    }
14107                                })?;
14108                            pane.update(cx, |pane, cx| {
14109                                pane.activate_item(pane_item_index, true, true, window, cx)
14110                            });
14111                            Some(editor)
14112                        })
14113                        .flatten()
14114                        .unwrap_or_else(|| {
14115                            workspace.open_project_item::<Self>(
14116                                pane.clone(),
14117                                buffer,
14118                                true,
14119                                true,
14120                                window,
14121                                cx,
14122                            )
14123                        });
14124
14125                    editor.update(cx, |editor, cx| {
14126                        let autoscroll = match scroll_offset {
14127                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14128                            None => Autoscroll::newest(),
14129                        };
14130                        let nav_history = editor.nav_history.take();
14131                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14132                            s.select_ranges(ranges);
14133                        });
14134                        editor.nav_history = nav_history;
14135                    });
14136                }
14137            })
14138        });
14139    }
14140
14141    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14142        let snapshot = self.buffer.read(cx).read(cx);
14143        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14144        Some(
14145            ranges
14146                .iter()
14147                .map(move |range| {
14148                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14149                })
14150                .collect(),
14151        )
14152    }
14153
14154    fn selection_replacement_ranges(
14155        &self,
14156        range: Range<OffsetUtf16>,
14157        cx: &mut App,
14158    ) -> Vec<Range<OffsetUtf16>> {
14159        let selections = self.selections.all::<OffsetUtf16>(cx);
14160        let newest_selection = selections
14161            .iter()
14162            .max_by_key(|selection| selection.id)
14163            .unwrap();
14164        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14165        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14166        let snapshot = self.buffer.read(cx).read(cx);
14167        selections
14168            .into_iter()
14169            .map(|mut selection| {
14170                selection.start.0 =
14171                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14172                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14173                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14174                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14175            })
14176            .collect()
14177    }
14178
14179    fn report_editor_event(
14180        &self,
14181        event_type: &'static str,
14182        file_extension: Option<String>,
14183        cx: &App,
14184    ) {
14185        if cfg!(any(test, feature = "test-support")) {
14186            return;
14187        }
14188
14189        let Some(project) = &self.project else { return };
14190
14191        // If None, we are in a file without an extension
14192        let file = self
14193            .buffer
14194            .read(cx)
14195            .as_singleton()
14196            .and_then(|b| b.read(cx).file());
14197        let file_extension = file_extension.or(file
14198            .as_ref()
14199            .and_then(|file| Path::new(file.file_name(cx)).extension())
14200            .and_then(|e| e.to_str())
14201            .map(|a| a.to_string()));
14202
14203        let vim_mode = cx
14204            .global::<SettingsStore>()
14205            .raw_user_settings()
14206            .get("vim_mode")
14207            == Some(&serde_json::Value::Bool(true));
14208
14209        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14210        let copilot_enabled = edit_predictions_provider
14211            == language::language_settings::EditPredictionProvider::Copilot;
14212        let copilot_enabled_for_language = self
14213            .buffer
14214            .read(cx)
14215            .settings_at(0, cx)
14216            .show_edit_predictions;
14217
14218        let project = project.read(cx);
14219        telemetry::event!(
14220            event_type,
14221            file_extension,
14222            vim_mode,
14223            copilot_enabled,
14224            copilot_enabled_for_language,
14225            edit_predictions_provider,
14226            is_via_ssh = project.is_via_ssh(),
14227        );
14228    }
14229
14230    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14231    /// with each line being an array of {text, highlight} objects.
14232    fn copy_highlight_json(
14233        &mut self,
14234        _: &CopyHighlightJson,
14235        window: &mut Window,
14236        cx: &mut Context<Self>,
14237    ) {
14238        #[derive(Serialize)]
14239        struct Chunk<'a> {
14240            text: String,
14241            highlight: Option<&'a str>,
14242        }
14243
14244        let snapshot = self.buffer.read(cx).snapshot(cx);
14245        let range = self
14246            .selected_text_range(false, window, cx)
14247            .and_then(|selection| {
14248                if selection.range.is_empty() {
14249                    None
14250                } else {
14251                    Some(selection.range)
14252                }
14253            })
14254            .unwrap_or_else(|| 0..snapshot.len());
14255
14256        let chunks = snapshot.chunks(range, true);
14257        let mut lines = Vec::new();
14258        let mut line: VecDeque<Chunk> = VecDeque::new();
14259
14260        let Some(style) = self.style.as_ref() else {
14261            return;
14262        };
14263
14264        for chunk in chunks {
14265            let highlight = chunk
14266                .syntax_highlight_id
14267                .and_then(|id| id.name(&style.syntax));
14268            let mut chunk_lines = chunk.text.split('\n').peekable();
14269            while let Some(text) = chunk_lines.next() {
14270                let mut merged_with_last_token = false;
14271                if let Some(last_token) = line.back_mut() {
14272                    if last_token.highlight == highlight {
14273                        last_token.text.push_str(text);
14274                        merged_with_last_token = true;
14275                    }
14276                }
14277
14278                if !merged_with_last_token {
14279                    line.push_back(Chunk {
14280                        text: text.into(),
14281                        highlight,
14282                    });
14283                }
14284
14285                if chunk_lines.peek().is_some() {
14286                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14287                        line.pop_front();
14288                    }
14289                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14290                        line.pop_back();
14291                    }
14292
14293                    lines.push(mem::take(&mut line));
14294                }
14295            }
14296        }
14297
14298        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14299            return;
14300        };
14301        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14302    }
14303
14304    pub fn open_context_menu(
14305        &mut self,
14306        _: &OpenContextMenu,
14307        window: &mut Window,
14308        cx: &mut Context<Self>,
14309    ) {
14310        self.request_autoscroll(Autoscroll::newest(), cx);
14311        let position = self.selections.newest_display(cx).start;
14312        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14313    }
14314
14315    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14316        &self.inlay_hint_cache
14317    }
14318
14319    pub fn replay_insert_event(
14320        &mut self,
14321        text: &str,
14322        relative_utf16_range: Option<Range<isize>>,
14323        window: &mut Window,
14324        cx: &mut Context<Self>,
14325    ) {
14326        if !self.input_enabled {
14327            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14328            return;
14329        }
14330        if let Some(relative_utf16_range) = relative_utf16_range {
14331            let selections = self.selections.all::<OffsetUtf16>(cx);
14332            self.change_selections(None, window, cx, |s| {
14333                let new_ranges = selections.into_iter().map(|range| {
14334                    let start = OffsetUtf16(
14335                        range
14336                            .head()
14337                            .0
14338                            .saturating_add_signed(relative_utf16_range.start),
14339                    );
14340                    let end = OffsetUtf16(
14341                        range
14342                            .head()
14343                            .0
14344                            .saturating_add_signed(relative_utf16_range.end),
14345                    );
14346                    start..end
14347                });
14348                s.select_ranges(new_ranges);
14349            });
14350        }
14351
14352        self.handle_input(text, window, cx);
14353    }
14354
14355    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14356        let Some(provider) = self.semantics_provider.as_ref() else {
14357            return false;
14358        };
14359
14360        let mut supports = false;
14361        self.buffer().read(cx).for_each_buffer(|buffer| {
14362            supports |= provider.supports_inlay_hints(buffer, cx);
14363        });
14364        supports
14365    }
14366    pub fn is_focused(&self, window: &mut Window) -> bool {
14367        self.focus_handle.is_focused(window)
14368    }
14369
14370    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14371        cx.emit(EditorEvent::Focused);
14372
14373        if let Some(descendant) = self
14374            .last_focused_descendant
14375            .take()
14376            .and_then(|descendant| descendant.upgrade())
14377        {
14378            window.focus(&descendant);
14379        } else {
14380            if let Some(blame) = self.blame.as_ref() {
14381                blame.update(cx, GitBlame::focus)
14382            }
14383
14384            self.blink_manager.update(cx, BlinkManager::enable);
14385            self.show_cursor_names(window, cx);
14386            self.buffer.update(cx, |buffer, cx| {
14387                buffer.finalize_last_transaction(cx);
14388                if self.leader_peer_id.is_none() {
14389                    buffer.set_active_selections(
14390                        &self.selections.disjoint_anchors(),
14391                        self.selections.line_mode,
14392                        self.cursor_shape,
14393                        cx,
14394                    );
14395                }
14396            });
14397        }
14398    }
14399
14400    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14401        cx.emit(EditorEvent::FocusedIn)
14402    }
14403
14404    fn handle_focus_out(
14405        &mut self,
14406        event: FocusOutEvent,
14407        _window: &mut Window,
14408        _cx: &mut Context<Self>,
14409    ) {
14410        if event.blurred != self.focus_handle {
14411            self.last_focused_descendant = Some(event.blurred);
14412        }
14413    }
14414
14415    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14416        self.blink_manager.update(cx, BlinkManager::disable);
14417        self.buffer
14418            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14419
14420        if let Some(blame) = self.blame.as_ref() {
14421            blame.update(cx, GitBlame::blur)
14422        }
14423        if !self.hover_state.focused(window, cx) {
14424            hide_hover(self, cx);
14425        }
14426
14427        self.hide_context_menu(window, cx);
14428        cx.emit(EditorEvent::Blurred);
14429        cx.notify();
14430    }
14431
14432    pub fn register_action<A: Action>(
14433        &mut self,
14434        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14435    ) -> Subscription {
14436        let id = self.next_editor_action_id.post_inc();
14437        let listener = Arc::new(listener);
14438        self.editor_actions.borrow_mut().insert(
14439            id,
14440            Box::new(move |window, _| {
14441                let listener = listener.clone();
14442                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14443                    let action = action.downcast_ref().unwrap();
14444                    if phase == DispatchPhase::Bubble {
14445                        listener(action, window, cx)
14446                    }
14447                })
14448            }),
14449        );
14450
14451        let editor_actions = self.editor_actions.clone();
14452        Subscription::new(move || {
14453            editor_actions.borrow_mut().remove(&id);
14454        })
14455    }
14456
14457    pub fn file_header_size(&self) -> u32 {
14458        FILE_HEADER_HEIGHT
14459    }
14460
14461    pub fn revert(
14462        &mut self,
14463        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14464        window: &mut Window,
14465        cx: &mut Context<Self>,
14466    ) {
14467        self.buffer().update(cx, |multi_buffer, cx| {
14468            for (buffer_id, changes) in revert_changes {
14469                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14470                    buffer.update(cx, |buffer, cx| {
14471                        buffer.edit(
14472                            changes.into_iter().map(|(range, text)| {
14473                                (range, text.to_string().map(Arc::<str>::from))
14474                            }),
14475                            None,
14476                            cx,
14477                        );
14478                    });
14479                }
14480            }
14481        });
14482        self.change_selections(None, window, cx, |selections| selections.refresh());
14483    }
14484
14485    pub fn to_pixel_point(
14486        &self,
14487        source: multi_buffer::Anchor,
14488        editor_snapshot: &EditorSnapshot,
14489        window: &mut Window,
14490    ) -> Option<gpui::Point<Pixels>> {
14491        let source_point = source.to_display_point(editor_snapshot);
14492        self.display_to_pixel_point(source_point, editor_snapshot, window)
14493    }
14494
14495    pub fn display_to_pixel_point(
14496        &self,
14497        source: DisplayPoint,
14498        editor_snapshot: &EditorSnapshot,
14499        window: &mut Window,
14500    ) -> Option<gpui::Point<Pixels>> {
14501        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14502        let text_layout_details = self.text_layout_details(window);
14503        let scroll_top = text_layout_details
14504            .scroll_anchor
14505            .scroll_position(editor_snapshot)
14506            .y;
14507
14508        if source.row().as_f32() < scroll_top.floor() {
14509            return None;
14510        }
14511        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14512        let source_y = line_height * (source.row().as_f32() - scroll_top);
14513        Some(gpui::Point::new(source_x, source_y))
14514    }
14515
14516    pub fn has_visible_completions_menu(&self) -> bool {
14517        !self.previewing_inline_completion
14518            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14519                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14520            })
14521    }
14522
14523    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14524        self.addons
14525            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14526    }
14527
14528    pub fn unregister_addon<T: Addon>(&mut self) {
14529        self.addons.remove(&std::any::TypeId::of::<T>());
14530    }
14531
14532    pub fn addon<T: Addon>(&self) -> Option<&T> {
14533        let type_id = std::any::TypeId::of::<T>();
14534        self.addons
14535            .get(&type_id)
14536            .and_then(|item| item.to_any().downcast_ref::<T>())
14537    }
14538
14539    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14540        let text_layout_details = self.text_layout_details(window);
14541        let style = &text_layout_details.editor_style;
14542        let font_id = window.text_system().resolve_font(&style.text.font());
14543        let font_size = style.text.font_size.to_pixels(window.rem_size());
14544        let line_height = style.text.line_height_in_pixels(window.rem_size());
14545        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14546
14547        gpui::Size::new(em_width, line_height)
14548    }
14549}
14550
14551fn get_uncommitted_diff_for_buffer(
14552    project: &Entity<Project>,
14553    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14554    buffer: Entity<MultiBuffer>,
14555    cx: &mut App,
14556) {
14557    let mut tasks = Vec::new();
14558    project.update(cx, |project, cx| {
14559        for buffer in buffers {
14560            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14561        }
14562    });
14563    cx.spawn(|mut cx| async move {
14564        let diffs = futures::future::join_all(tasks).await;
14565        buffer
14566            .update(&mut cx, |buffer, cx| {
14567                for diff in diffs.into_iter().flatten() {
14568                    buffer.add_diff(diff, cx);
14569                }
14570            })
14571            .ok();
14572    })
14573    .detach();
14574}
14575
14576fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14577    let tab_size = tab_size.get() as usize;
14578    let mut width = offset;
14579
14580    for ch in text.chars() {
14581        width += if ch == '\t' {
14582            tab_size - (width % tab_size)
14583        } else {
14584            1
14585        };
14586    }
14587
14588    width - offset
14589}
14590
14591#[cfg(test)]
14592mod tests {
14593    use super::*;
14594
14595    #[test]
14596    fn test_string_size_with_expanded_tabs() {
14597        let nz = |val| NonZeroU32::new(val).unwrap();
14598        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14599        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14600        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14601        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14602        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14603        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14604        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14605        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14606    }
14607}
14608
14609/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14610struct WordBreakingTokenizer<'a> {
14611    input: &'a str,
14612}
14613
14614impl<'a> WordBreakingTokenizer<'a> {
14615    fn new(input: &'a str) -> Self {
14616        Self { input }
14617    }
14618}
14619
14620fn is_char_ideographic(ch: char) -> bool {
14621    use unicode_script::Script::*;
14622    use unicode_script::UnicodeScript;
14623    matches!(ch.script(), Han | Tangut | Yi)
14624}
14625
14626fn is_grapheme_ideographic(text: &str) -> bool {
14627    text.chars().any(is_char_ideographic)
14628}
14629
14630fn is_grapheme_whitespace(text: &str) -> bool {
14631    text.chars().any(|x| x.is_whitespace())
14632}
14633
14634fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14635    text.chars().next().map_or(false, |ch| {
14636        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14637    })
14638}
14639
14640#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14641struct WordBreakToken<'a> {
14642    token: &'a str,
14643    grapheme_len: usize,
14644    is_whitespace: bool,
14645}
14646
14647impl<'a> Iterator for WordBreakingTokenizer<'a> {
14648    /// Yields a span, the count of graphemes in the token, and whether it was
14649    /// whitespace. Note that it also breaks at word boundaries.
14650    type Item = WordBreakToken<'a>;
14651
14652    fn next(&mut self) -> Option<Self::Item> {
14653        use unicode_segmentation::UnicodeSegmentation;
14654        if self.input.is_empty() {
14655            return None;
14656        }
14657
14658        let mut iter = self.input.graphemes(true).peekable();
14659        let mut offset = 0;
14660        let mut graphemes = 0;
14661        if let Some(first_grapheme) = iter.next() {
14662            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14663            offset += first_grapheme.len();
14664            graphemes += 1;
14665            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14666                if let Some(grapheme) = iter.peek().copied() {
14667                    if should_stay_with_preceding_ideograph(grapheme) {
14668                        offset += grapheme.len();
14669                        graphemes += 1;
14670                    }
14671                }
14672            } else {
14673                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14674                let mut next_word_bound = words.peek().copied();
14675                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14676                    next_word_bound = words.next();
14677                }
14678                while let Some(grapheme) = iter.peek().copied() {
14679                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14680                        break;
14681                    };
14682                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14683                        break;
14684                    };
14685                    offset += grapheme.len();
14686                    graphemes += 1;
14687                    iter.next();
14688                }
14689            }
14690            let token = &self.input[..offset];
14691            self.input = &self.input[offset..];
14692            if is_whitespace {
14693                Some(WordBreakToken {
14694                    token: " ",
14695                    grapheme_len: 1,
14696                    is_whitespace: true,
14697                })
14698            } else {
14699                Some(WordBreakToken {
14700                    token,
14701                    grapheme_len: graphemes,
14702                    is_whitespace: false,
14703                })
14704            }
14705        } else {
14706            None
14707        }
14708    }
14709}
14710
14711#[test]
14712fn test_word_breaking_tokenizer() {
14713    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14714        ("", &[]),
14715        ("  ", &[(" ", 1, true)]),
14716        ("Ʒ", &[("Ʒ", 1, false)]),
14717        ("Ǽ", &[("Ǽ", 1, false)]),
14718        ("", &[("", 1, false)]),
14719        ("⋑⋑", &[("⋑⋑", 2, false)]),
14720        (
14721            "原理,进而",
14722            &[
14723                ("", 1, false),
14724                ("理,", 2, false),
14725                ("", 1, false),
14726                ("", 1, false),
14727            ],
14728        ),
14729        (
14730            "hello world",
14731            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14732        ),
14733        (
14734            "hello, world",
14735            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14736        ),
14737        (
14738            "  hello world",
14739            &[
14740                (" ", 1, true),
14741                ("hello", 5, false),
14742                (" ", 1, true),
14743                ("world", 5, false),
14744            ],
14745        ),
14746        (
14747            "这是什么 \n 钢笔",
14748            &[
14749                ("", 1, false),
14750                ("", 1, false),
14751                ("", 1, false),
14752                ("", 1, false),
14753                (" ", 1, true),
14754                ("", 1, false),
14755                ("", 1, false),
14756            ],
14757        ),
14758        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14759    ];
14760
14761    for (input, result) in tests {
14762        assert_eq!(
14763            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14764            result
14765                .iter()
14766                .copied()
14767                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14768                    token,
14769                    grapheme_len,
14770                    is_whitespace,
14771                })
14772                .collect::<Vec<_>>()
14773        );
14774    }
14775}
14776
14777fn wrap_with_prefix(
14778    line_prefix: String,
14779    unwrapped_text: String,
14780    wrap_column: usize,
14781    tab_size: NonZeroU32,
14782) -> String {
14783    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14784    let mut wrapped_text = String::new();
14785    let mut current_line = line_prefix.clone();
14786
14787    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14788    let mut current_line_len = line_prefix_len;
14789    for WordBreakToken {
14790        token,
14791        grapheme_len,
14792        is_whitespace,
14793    } in tokenizer
14794    {
14795        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14796            wrapped_text.push_str(current_line.trim_end());
14797            wrapped_text.push('\n');
14798            current_line.truncate(line_prefix.len());
14799            current_line_len = line_prefix_len;
14800            if !is_whitespace {
14801                current_line.push_str(token);
14802                current_line_len += grapheme_len;
14803            }
14804        } else if !is_whitespace {
14805            current_line.push_str(token);
14806            current_line_len += grapheme_len;
14807        } else if current_line_len != line_prefix_len {
14808            current_line.push(' ');
14809            current_line_len += 1;
14810        }
14811    }
14812
14813    if !current_line.is_empty() {
14814        wrapped_text.push_str(&current_line);
14815    }
14816    wrapped_text
14817}
14818
14819#[test]
14820fn test_wrap_with_prefix() {
14821    assert_eq!(
14822        wrap_with_prefix(
14823            "# ".to_string(),
14824            "abcdefg".to_string(),
14825            4,
14826            NonZeroU32::new(4).unwrap()
14827        ),
14828        "# abcdefg"
14829    );
14830    assert_eq!(
14831        wrap_with_prefix(
14832            "".to_string(),
14833            "\thello world".to_string(),
14834            8,
14835            NonZeroU32::new(4).unwrap()
14836        ),
14837        "hello\nworld"
14838    );
14839    assert_eq!(
14840        wrap_with_prefix(
14841            "// ".to_string(),
14842            "xx \nyy zz aa bb cc".to_string(),
14843            12,
14844            NonZeroU32::new(4).unwrap()
14845        ),
14846        "// xx yy zz\n// aa bb cc"
14847    );
14848    assert_eq!(
14849        wrap_with_prefix(
14850            String::new(),
14851            "这是什么 \n 钢笔".to_string(),
14852            3,
14853            NonZeroU32::new(4).unwrap()
14854        ),
14855        "这是什\n么 钢\n"
14856    );
14857}
14858
14859pub trait CollaborationHub {
14860    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14861    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14862    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14863}
14864
14865impl CollaborationHub for Entity<Project> {
14866    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14867        self.read(cx).collaborators()
14868    }
14869
14870    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14871        self.read(cx).user_store().read(cx).participant_indices()
14872    }
14873
14874    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14875        let this = self.read(cx);
14876        let user_ids = this.collaborators().values().map(|c| c.user_id);
14877        this.user_store().read_with(cx, |user_store, cx| {
14878            user_store.participant_names(user_ids, cx)
14879        })
14880    }
14881}
14882
14883pub trait SemanticsProvider {
14884    fn hover(
14885        &self,
14886        buffer: &Entity<Buffer>,
14887        position: text::Anchor,
14888        cx: &mut App,
14889    ) -> Option<Task<Vec<project::Hover>>>;
14890
14891    fn inlay_hints(
14892        &self,
14893        buffer_handle: Entity<Buffer>,
14894        range: Range<text::Anchor>,
14895        cx: &mut App,
14896    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14897
14898    fn resolve_inlay_hint(
14899        &self,
14900        hint: InlayHint,
14901        buffer_handle: Entity<Buffer>,
14902        server_id: LanguageServerId,
14903        cx: &mut App,
14904    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14905
14906    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14907
14908    fn document_highlights(
14909        &self,
14910        buffer: &Entity<Buffer>,
14911        position: text::Anchor,
14912        cx: &mut App,
14913    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14914
14915    fn definitions(
14916        &self,
14917        buffer: &Entity<Buffer>,
14918        position: text::Anchor,
14919        kind: GotoDefinitionKind,
14920        cx: &mut App,
14921    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14922
14923    fn range_for_rename(
14924        &self,
14925        buffer: &Entity<Buffer>,
14926        position: text::Anchor,
14927        cx: &mut App,
14928    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14929
14930    fn perform_rename(
14931        &self,
14932        buffer: &Entity<Buffer>,
14933        position: text::Anchor,
14934        new_name: String,
14935        cx: &mut App,
14936    ) -> Option<Task<Result<ProjectTransaction>>>;
14937}
14938
14939pub trait CompletionProvider {
14940    fn completions(
14941        &self,
14942        buffer: &Entity<Buffer>,
14943        buffer_position: text::Anchor,
14944        trigger: CompletionContext,
14945        window: &mut Window,
14946        cx: &mut Context<Editor>,
14947    ) -> Task<Result<Vec<Completion>>>;
14948
14949    fn resolve_completions(
14950        &self,
14951        buffer: Entity<Buffer>,
14952        completion_indices: Vec<usize>,
14953        completions: Rc<RefCell<Box<[Completion]>>>,
14954        cx: &mut Context<Editor>,
14955    ) -> Task<Result<bool>>;
14956
14957    fn apply_additional_edits_for_completion(
14958        &self,
14959        _buffer: Entity<Buffer>,
14960        _completions: Rc<RefCell<Box<[Completion]>>>,
14961        _completion_index: usize,
14962        _push_to_history: bool,
14963        _cx: &mut Context<Editor>,
14964    ) -> Task<Result<Option<language::Transaction>>> {
14965        Task::ready(Ok(None))
14966    }
14967
14968    fn is_completion_trigger(
14969        &self,
14970        buffer: &Entity<Buffer>,
14971        position: language::Anchor,
14972        text: &str,
14973        trigger_in_words: bool,
14974        cx: &mut Context<Editor>,
14975    ) -> bool;
14976
14977    fn sort_completions(&self) -> bool {
14978        true
14979    }
14980}
14981
14982pub trait CodeActionProvider {
14983    fn id(&self) -> Arc<str>;
14984
14985    fn code_actions(
14986        &self,
14987        buffer: &Entity<Buffer>,
14988        range: Range<text::Anchor>,
14989        window: &mut Window,
14990        cx: &mut App,
14991    ) -> Task<Result<Vec<CodeAction>>>;
14992
14993    fn apply_code_action(
14994        &self,
14995        buffer_handle: Entity<Buffer>,
14996        action: CodeAction,
14997        excerpt_id: ExcerptId,
14998        push_to_history: bool,
14999        window: &mut Window,
15000        cx: &mut App,
15001    ) -> Task<Result<ProjectTransaction>>;
15002}
15003
15004impl CodeActionProvider for Entity<Project> {
15005    fn id(&self) -> Arc<str> {
15006        "project".into()
15007    }
15008
15009    fn code_actions(
15010        &self,
15011        buffer: &Entity<Buffer>,
15012        range: Range<text::Anchor>,
15013        _window: &mut Window,
15014        cx: &mut App,
15015    ) -> Task<Result<Vec<CodeAction>>> {
15016        self.update(cx, |project, cx| {
15017            project.code_actions(buffer, range, None, cx)
15018        })
15019    }
15020
15021    fn apply_code_action(
15022        &self,
15023        buffer_handle: Entity<Buffer>,
15024        action: CodeAction,
15025        _excerpt_id: ExcerptId,
15026        push_to_history: bool,
15027        _window: &mut Window,
15028        cx: &mut App,
15029    ) -> Task<Result<ProjectTransaction>> {
15030        self.update(cx, |project, cx| {
15031            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15032        })
15033    }
15034}
15035
15036fn snippet_completions(
15037    project: &Project,
15038    buffer: &Entity<Buffer>,
15039    buffer_position: text::Anchor,
15040    cx: &mut App,
15041) -> Task<Result<Vec<Completion>>> {
15042    let language = buffer.read(cx).language_at(buffer_position);
15043    let language_name = language.as_ref().map(|language| language.lsp_id());
15044    let snippet_store = project.snippets().read(cx);
15045    let snippets = snippet_store.snippets_for(language_name, cx);
15046
15047    if snippets.is_empty() {
15048        return Task::ready(Ok(vec![]));
15049    }
15050    let snapshot = buffer.read(cx).text_snapshot();
15051    let chars: String = snapshot
15052        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15053        .collect();
15054
15055    let scope = language.map(|language| language.default_scope());
15056    let executor = cx.background_executor().clone();
15057
15058    cx.background_executor().spawn(async move {
15059        let classifier = CharClassifier::new(scope).for_completion(true);
15060        let mut last_word = chars
15061            .chars()
15062            .take_while(|c| classifier.is_word(*c))
15063            .collect::<String>();
15064        last_word = last_word.chars().rev().collect();
15065
15066        if last_word.is_empty() {
15067            return Ok(vec![]);
15068        }
15069
15070        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15071        let to_lsp = |point: &text::Anchor| {
15072            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15073            point_to_lsp(end)
15074        };
15075        let lsp_end = to_lsp(&buffer_position);
15076
15077        let candidates = snippets
15078            .iter()
15079            .enumerate()
15080            .flat_map(|(ix, snippet)| {
15081                snippet
15082                    .prefix
15083                    .iter()
15084                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15085            })
15086            .collect::<Vec<StringMatchCandidate>>();
15087
15088        let mut matches = fuzzy::match_strings(
15089            &candidates,
15090            &last_word,
15091            last_word.chars().any(|c| c.is_uppercase()),
15092            100,
15093            &Default::default(),
15094            executor,
15095        )
15096        .await;
15097
15098        // Remove all candidates where the query's start does not match the start of any word in the candidate
15099        if let Some(query_start) = last_word.chars().next() {
15100            matches.retain(|string_match| {
15101                split_words(&string_match.string).any(|word| {
15102                    // Check that the first codepoint of the word as lowercase matches the first
15103                    // codepoint of the query as lowercase
15104                    word.chars()
15105                        .flat_map(|codepoint| codepoint.to_lowercase())
15106                        .zip(query_start.to_lowercase())
15107                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15108                })
15109            });
15110        }
15111
15112        let matched_strings = matches
15113            .into_iter()
15114            .map(|m| m.string)
15115            .collect::<HashSet<_>>();
15116
15117        let result: Vec<Completion> = snippets
15118            .into_iter()
15119            .filter_map(|snippet| {
15120                let matching_prefix = snippet
15121                    .prefix
15122                    .iter()
15123                    .find(|prefix| matched_strings.contains(*prefix))?;
15124                let start = as_offset - last_word.len();
15125                let start = snapshot.anchor_before(start);
15126                let range = start..buffer_position;
15127                let lsp_start = to_lsp(&start);
15128                let lsp_range = lsp::Range {
15129                    start: lsp_start,
15130                    end: lsp_end,
15131                };
15132                Some(Completion {
15133                    old_range: range,
15134                    new_text: snippet.body.clone(),
15135                    resolved: false,
15136                    label: CodeLabel {
15137                        text: matching_prefix.clone(),
15138                        runs: vec![],
15139                        filter_range: 0..matching_prefix.len(),
15140                    },
15141                    server_id: LanguageServerId(usize::MAX),
15142                    documentation: snippet
15143                        .description
15144                        .clone()
15145                        .map(CompletionDocumentation::SingleLine),
15146                    lsp_completion: lsp::CompletionItem {
15147                        label: snippet.prefix.first().unwrap().clone(),
15148                        kind: Some(CompletionItemKind::SNIPPET),
15149                        label_details: snippet.description.as_ref().map(|description| {
15150                            lsp::CompletionItemLabelDetails {
15151                                detail: Some(description.clone()),
15152                                description: None,
15153                            }
15154                        }),
15155                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15156                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15157                            lsp::InsertReplaceEdit {
15158                                new_text: snippet.body.clone(),
15159                                insert: lsp_range,
15160                                replace: lsp_range,
15161                            },
15162                        )),
15163                        filter_text: Some(snippet.body.clone()),
15164                        sort_text: Some(char::MAX.to_string()),
15165                        ..Default::default()
15166                    },
15167                    confirm: None,
15168                })
15169            })
15170            .collect();
15171
15172        Ok(result)
15173    })
15174}
15175
15176impl CompletionProvider for Entity<Project> {
15177    fn completions(
15178        &self,
15179        buffer: &Entity<Buffer>,
15180        buffer_position: text::Anchor,
15181        options: CompletionContext,
15182        _window: &mut Window,
15183        cx: &mut Context<Editor>,
15184    ) -> Task<Result<Vec<Completion>>> {
15185        self.update(cx, |project, cx| {
15186            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15187            let project_completions = project.completions(buffer, buffer_position, options, cx);
15188            cx.background_executor().spawn(async move {
15189                let mut completions = project_completions.await?;
15190                let snippets_completions = snippets.await?;
15191                completions.extend(snippets_completions);
15192                Ok(completions)
15193            })
15194        })
15195    }
15196
15197    fn resolve_completions(
15198        &self,
15199        buffer: Entity<Buffer>,
15200        completion_indices: Vec<usize>,
15201        completions: Rc<RefCell<Box<[Completion]>>>,
15202        cx: &mut Context<Editor>,
15203    ) -> Task<Result<bool>> {
15204        self.update(cx, |project, cx| {
15205            project.lsp_store().update(cx, |lsp_store, cx| {
15206                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15207            })
15208        })
15209    }
15210
15211    fn apply_additional_edits_for_completion(
15212        &self,
15213        buffer: Entity<Buffer>,
15214        completions: Rc<RefCell<Box<[Completion]>>>,
15215        completion_index: usize,
15216        push_to_history: bool,
15217        cx: &mut Context<Editor>,
15218    ) -> Task<Result<Option<language::Transaction>>> {
15219        self.update(cx, |project, cx| {
15220            project.lsp_store().update(cx, |lsp_store, cx| {
15221                lsp_store.apply_additional_edits_for_completion(
15222                    buffer,
15223                    completions,
15224                    completion_index,
15225                    push_to_history,
15226                    cx,
15227                )
15228            })
15229        })
15230    }
15231
15232    fn is_completion_trigger(
15233        &self,
15234        buffer: &Entity<Buffer>,
15235        position: language::Anchor,
15236        text: &str,
15237        trigger_in_words: bool,
15238        cx: &mut Context<Editor>,
15239    ) -> bool {
15240        let mut chars = text.chars();
15241        let char = if let Some(char) = chars.next() {
15242            char
15243        } else {
15244            return false;
15245        };
15246        if chars.next().is_some() {
15247            return false;
15248        }
15249
15250        let buffer = buffer.read(cx);
15251        let snapshot = buffer.snapshot();
15252        if !snapshot.settings_at(position, cx).show_completions_on_input {
15253            return false;
15254        }
15255        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15256        if trigger_in_words && classifier.is_word(char) {
15257            return true;
15258        }
15259
15260        buffer.completion_triggers().contains(text)
15261    }
15262}
15263
15264impl SemanticsProvider for Entity<Project> {
15265    fn hover(
15266        &self,
15267        buffer: &Entity<Buffer>,
15268        position: text::Anchor,
15269        cx: &mut App,
15270    ) -> Option<Task<Vec<project::Hover>>> {
15271        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15272    }
15273
15274    fn document_highlights(
15275        &self,
15276        buffer: &Entity<Buffer>,
15277        position: text::Anchor,
15278        cx: &mut App,
15279    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15280        Some(self.update(cx, |project, cx| {
15281            project.document_highlights(buffer, position, cx)
15282        }))
15283    }
15284
15285    fn definitions(
15286        &self,
15287        buffer: &Entity<Buffer>,
15288        position: text::Anchor,
15289        kind: GotoDefinitionKind,
15290        cx: &mut App,
15291    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15292        Some(self.update(cx, |project, cx| match kind {
15293            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15294            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15295            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15296            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15297        }))
15298    }
15299
15300    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15301        // TODO: make this work for remote projects
15302        self.read(cx)
15303            .language_servers_for_local_buffer(buffer.read(cx), cx)
15304            .any(
15305                |(_, server)| match server.capabilities().inlay_hint_provider {
15306                    Some(lsp::OneOf::Left(enabled)) => enabled,
15307                    Some(lsp::OneOf::Right(_)) => true,
15308                    None => false,
15309                },
15310            )
15311    }
15312
15313    fn inlay_hints(
15314        &self,
15315        buffer_handle: Entity<Buffer>,
15316        range: Range<text::Anchor>,
15317        cx: &mut App,
15318    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15319        Some(self.update(cx, |project, cx| {
15320            project.inlay_hints(buffer_handle, range, cx)
15321        }))
15322    }
15323
15324    fn resolve_inlay_hint(
15325        &self,
15326        hint: InlayHint,
15327        buffer_handle: Entity<Buffer>,
15328        server_id: LanguageServerId,
15329        cx: &mut App,
15330    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15331        Some(self.update(cx, |project, cx| {
15332            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15333        }))
15334    }
15335
15336    fn range_for_rename(
15337        &self,
15338        buffer: &Entity<Buffer>,
15339        position: text::Anchor,
15340        cx: &mut App,
15341    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15342        Some(self.update(cx, |project, cx| {
15343            let buffer = buffer.clone();
15344            let task = project.prepare_rename(buffer.clone(), position, cx);
15345            cx.spawn(|_, mut cx| async move {
15346                Ok(match task.await? {
15347                    PrepareRenameResponse::Success(range) => Some(range),
15348                    PrepareRenameResponse::InvalidPosition => None,
15349                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15350                        // Fallback on using TreeSitter info to determine identifier range
15351                        buffer.update(&mut cx, |buffer, _| {
15352                            let snapshot = buffer.snapshot();
15353                            let (range, kind) = snapshot.surrounding_word(position);
15354                            if kind != Some(CharKind::Word) {
15355                                return None;
15356                            }
15357                            Some(
15358                                snapshot.anchor_before(range.start)
15359                                    ..snapshot.anchor_after(range.end),
15360                            )
15361                        })?
15362                    }
15363                })
15364            })
15365        }))
15366    }
15367
15368    fn perform_rename(
15369        &self,
15370        buffer: &Entity<Buffer>,
15371        position: text::Anchor,
15372        new_name: String,
15373        cx: &mut App,
15374    ) -> Option<Task<Result<ProjectTransaction>>> {
15375        Some(self.update(cx, |project, cx| {
15376            project.perform_rename(buffer.clone(), position, new_name, cx)
15377        }))
15378    }
15379}
15380
15381fn inlay_hint_settings(
15382    location: Anchor,
15383    snapshot: &MultiBufferSnapshot,
15384    cx: &mut Context<Editor>,
15385) -> InlayHintSettings {
15386    let file = snapshot.file_at(location);
15387    let language = snapshot.language_at(location).map(|l| l.name());
15388    language_settings(language, file, cx).inlay_hints
15389}
15390
15391fn consume_contiguous_rows(
15392    contiguous_row_selections: &mut Vec<Selection<Point>>,
15393    selection: &Selection<Point>,
15394    display_map: &DisplaySnapshot,
15395    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15396) -> (MultiBufferRow, MultiBufferRow) {
15397    contiguous_row_selections.push(selection.clone());
15398    let start_row = MultiBufferRow(selection.start.row);
15399    let mut end_row = ending_row(selection, display_map);
15400
15401    while let Some(next_selection) = selections.peek() {
15402        if next_selection.start.row <= end_row.0 {
15403            end_row = ending_row(next_selection, display_map);
15404            contiguous_row_selections.push(selections.next().unwrap().clone());
15405        } else {
15406            break;
15407        }
15408    }
15409    (start_row, end_row)
15410}
15411
15412fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15413    if next_selection.end.column > 0 || next_selection.is_empty() {
15414        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15415    } else {
15416        MultiBufferRow(next_selection.end.row)
15417    }
15418}
15419
15420impl EditorSnapshot {
15421    pub fn remote_selections_in_range<'a>(
15422        &'a self,
15423        range: &'a Range<Anchor>,
15424        collaboration_hub: &dyn CollaborationHub,
15425        cx: &'a App,
15426    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15427        let participant_names = collaboration_hub.user_names(cx);
15428        let participant_indices = collaboration_hub.user_participant_indices(cx);
15429        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15430        let collaborators_by_replica_id = collaborators_by_peer_id
15431            .iter()
15432            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15433            .collect::<HashMap<_, _>>();
15434        self.buffer_snapshot
15435            .selections_in_range(range, false)
15436            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15437                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15438                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15439                let user_name = participant_names.get(&collaborator.user_id).cloned();
15440                Some(RemoteSelection {
15441                    replica_id,
15442                    selection,
15443                    cursor_shape,
15444                    line_mode,
15445                    participant_index,
15446                    peer_id: collaborator.peer_id,
15447                    user_name,
15448                })
15449            })
15450    }
15451
15452    pub fn hunks_for_ranges(
15453        &self,
15454        ranges: impl Iterator<Item = Range<Point>>,
15455    ) -> Vec<MultiBufferDiffHunk> {
15456        let mut hunks = Vec::new();
15457        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15458            HashMap::default();
15459        for query_range in ranges {
15460            let query_rows =
15461                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15462            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15463                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15464            ) {
15465                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15466                // when the caret is just above or just below the deleted hunk.
15467                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15468                let related_to_selection = if allow_adjacent {
15469                    hunk.row_range.overlaps(&query_rows)
15470                        || hunk.row_range.start == query_rows.end
15471                        || hunk.row_range.end == query_rows.start
15472                } else {
15473                    hunk.row_range.overlaps(&query_rows)
15474                };
15475                if related_to_selection {
15476                    if !processed_buffer_rows
15477                        .entry(hunk.buffer_id)
15478                        .or_default()
15479                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15480                    {
15481                        continue;
15482                    }
15483                    hunks.push(hunk);
15484                }
15485            }
15486        }
15487
15488        hunks
15489    }
15490
15491    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15492        self.display_snapshot.buffer_snapshot.language_at(position)
15493    }
15494
15495    pub fn is_focused(&self) -> bool {
15496        self.is_focused
15497    }
15498
15499    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15500        self.placeholder_text.as_ref()
15501    }
15502
15503    pub fn scroll_position(&self) -> gpui::Point<f32> {
15504        self.scroll_anchor.scroll_position(&self.display_snapshot)
15505    }
15506
15507    fn gutter_dimensions(
15508        &self,
15509        font_id: FontId,
15510        font_size: Pixels,
15511        max_line_number_width: Pixels,
15512        cx: &App,
15513    ) -> Option<GutterDimensions> {
15514        if !self.show_gutter {
15515            return None;
15516        }
15517
15518        let descent = cx.text_system().descent(font_id, font_size);
15519        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15520        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15521
15522        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15523            matches!(
15524                ProjectSettings::get_global(cx).git.git_gutter,
15525                Some(GitGutterSetting::TrackedFiles)
15526            )
15527        });
15528        let gutter_settings = EditorSettings::get_global(cx).gutter;
15529        let show_line_numbers = self
15530            .show_line_numbers
15531            .unwrap_or(gutter_settings.line_numbers);
15532        let line_gutter_width = if show_line_numbers {
15533            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15534            let min_width_for_number_on_gutter = em_advance * 4.0;
15535            max_line_number_width.max(min_width_for_number_on_gutter)
15536        } else {
15537            0.0.into()
15538        };
15539
15540        let show_code_actions = self
15541            .show_code_actions
15542            .unwrap_or(gutter_settings.code_actions);
15543
15544        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15545
15546        let git_blame_entries_width =
15547            self.git_blame_gutter_max_author_length
15548                .map(|max_author_length| {
15549                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15550
15551                    /// The number of characters to dedicate to gaps and margins.
15552                    const SPACING_WIDTH: usize = 4;
15553
15554                    let max_char_count = max_author_length
15555                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15556                        + ::git::SHORT_SHA_LENGTH
15557                        + MAX_RELATIVE_TIMESTAMP.len()
15558                        + SPACING_WIDTH;
15559
15560                    em_advance * max_char_count
15561                });
15562
15563        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15564        left_padding += if show_code_actions || show_runnables {
15565            em_width * 3.0
15566        } else if show_git_gutter && show_line_numbers {
15567            em_width * 2.0
15568        } else if show_git_gutter || show_line_numbers {
15569            em_width
15570        } else {
15571            px(0.)
15572        };
15573
15574        let right_padding = if gutter_settings.folds && show_line_numbers {
15575            em_width * 4.0
15576        } else if gutter_settings.folds {
15577            em_width * 3.0
15578        } else if show_line_numbers {
15579            em_width
15580        } else {
15581            px(0.)
15582        };
15583
15584        Some(GutterDimensions {
15585            left_padding,
15586            right_padding,
15587            width: line_gutter_width + left_padding + right_padding,
15588            margin: -descent,
15589            git_blame_entries_width,
15590        })
15591    }
15592
15593    pub fn render_crease_toggle(
15594        &self,
15595        buffer_row: MultiBufferRow,
15596        row_contains_cursor: bool,
15597        editor: Entity<Editor>,
15598        window: &mut Window,
15599        cx: &mut App,
15600    ) -> Option<AnyElement> {
15601        let folded = self.is_line_folded(buffer_row);
15602        let mut is_foldable = false;
15603
15604        if let Some(crease) = self
15605            .crease_snapshot
15606            .query_row(buffer_row, &self.buffer_snapshot)
15607        {
15608            is_foldable = true;
15609            match crease {
15610                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15611                    if let Some(render_toggle) = render_toggle {
15612                        let toggle_callback =
15613                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15614                                if folded {
15615                                    editor.update(cx, |editor, cx| {
15616                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15617                                    });
15618                                } else {
15619                                    editor.update(cx, |editor, cx| {
15620                                        editor.unfold_at(
15621                                            &crate::UnfoldAt { buffer_row },
15622                                            window,
15623                                            cx,
15624                                        )
15625                                    });
15626                                }
15627                            });
15628                        return Some((render_toggle)(
15629                            buffer_row,
15630                            folded,
15631                            toggle_callback,
15632                            window,
15633                            cx,
15634                        ));
15635                    }
15636                }
15637            }
15638        }
15639
15640        is_foldable |= self.starts_indent(buffer_row);
15641
15642        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15643            Some(
15644                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15645                    .toggle_state(folded)
15646                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15647                        if folded {
15648                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15649                        } else {
15650                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15651                        }
15652                    }))
15653                    .into_any_element(),
15654            )
15655        } else {
15656            None
15657        }
15658    }
15659
15660    pub fn render_crease_trailer(
15661        &self,
15662        buffer_row: MultiBufferRow,
15663        window: &mut Window,
15664        cx: &mut App,
15665    ) -> Option<AnyElement> {
15666        let folded = self.is_line_folded(buffer_row);
15667        if let Crease::Inline { render_trailer, .. } = self
15668            .crease_snapshot
15669            .query_row(buffer_row, &self.buffer_snapshot)?
15670        {
15671            let render_trailer = render_trailer.as_ref()?;
15672            Some(render_trailer(buffer_row, folded, window, cx))
15673        } else {
15674            None
15675        }
15676    }
15677}
15678
15679impl Deref for EditorSnapshot {
15680    type Target = DisplaySnapshot;
15681
15682    fn deref(&self) -> &Self::Target {
15683        &self.display_snapshot
15684    }
15685}
15686
15687#[derive(Clone, Debug, PartialEq, Eq)]
15688pub enum EditorEvent {
15689    InputIgnored {
15690        text: Arc<str>,
15691    },
15692    InputHandled {
15693        utf16_range_to_replace: Option<Range<isize>>,
15694        text: Arc<str>,
15695    },
15696    ExcerptsAdded {
15697        buffer: Entity<Buffer>,
15698        predecessor: ExcerptId,
15699        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15700    },
15701    ExcerptsRemoved {
15702        ids: Vec<ExcerptId>,
15703    },
15704    BufferFoldToggled {
15705        ids: Vec<ExcerptId>,
15706        folded: bool,
15707    },
15708    ExcerptsEdited {
15709        ids: Vec<ExcerptId>,
15710    },
15711    ExcerptsExpanded {
15712        ids: Vec<ExcerptId>,
15713    },
15714    BufferEdited,
15715    Edited {
15716        transaction_id: clock::Lamport,
15717    },
15718    Reparsed(BufferId),
15719    Focused,
15720    FocusedIn,
15721    Blurred,
15722    DirtyChanged,
15723    Saved,
15724    TitleChanged,
15725    DiffBaseChanged,
15726    SelectionsChanged {
15727        local: bool,
15728    },
15729    ScrollPositionChanged {
15730        local: bool,
15731        autoscroll: bool,
15732    },
15733    Closed,
15734    TransactionUndone {
15735        transaction_id: clock::Lamport,
15736    },
15737    TransactionBegun {
15738        transaction_id: clock::Lamport,
15739    },
15740    Reloaded,
15741    CursorShapeChanged,
15742}
15743
15744impl EventEmitter<EditorEvent> for Editor {}
15745
15746impl Focusable for Editor {
15747    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15748        self.focus_handle.clone()
15749    }
15750}
15751
15752impl Render for Editor {
15753    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15754        let settings = ThemeSettings::get_global(cx);
15755
15756        let mut text_style = match self.mode {
15757            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15758                color: cx.theme().colors().editor_foreground,
15759                font_family: settings.ui_font.family.clone(),
15760                font_features: settings.ui_font.features.clone(),
15761                font_fallbacks: settings.ui_font.fallbacks.clone(),
15762                font_size: rems(0.875).into(),
15763                font_weight: settings.ui_font.weight,
15764                line_height: relative(settings.buffer_line_height.value()),
15765                ..Default::default()
15766            },
15767            EditorMode::Full => TextStyle {
15768                color: cx.theme().colors().editor_foreground,
15769                font_family: settings.buffer_font.family.clone(),
15770                font_features: settings.buffer_font.features.clone(),
15771                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15772                font_size: settings.buffer_font_size().into(),
15773                font_weight: settings.buffer_font.weight,
15774                line_height: relative(settings.buffer_line_height.value()),
15775                ..Default::default()
15776            },
15777        };
15778        if let Some(text_style_refinement) = &self.text_style_refinement {
15779            text_style.refine(text_style_refinement)
15780        }
15781
15782        let background = match self.mode {
15783            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15784            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15785            EditorMode::Full => cx.theme().colors().editor_background,
15786        };
15787
15788        EditorElement::new(
15789            &cx.entity(),
15790            EditorStyle {
15791                background,
15792                local_player: cx.theme().players().local(),
15793                text: text_style,
15794                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15795                syntax: cx.theme().syntax().clone(),
15796                status: cx.theme().status().clone(),
15797                inlay_hints_style: make_inlay_hints_style(cx),
15798                inline_completion_styles: make_suggestion_styles(cx),
15799                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15800            },
15801        )
15802    }
15803}
15804
15805impl EntityInputHandler for Editor {
15806    fn text_for_range(
15807        &mut self,
15808        range_utf16: Range<usize>,
15809        adjusted_range: &mut Option<Range<usize>>,
15810        _: &mut Window,
15811        cx: &mut Context<Self>,
15812    ) -> Option<String> {
15813        let snapshot = self.buffer.read(cx).read(cx);
15814        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15815        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15816        if (start.0..end.0) != range_utf16 {
15817            adjusted_range.replace(start.0..end.0);
15818        }
15819        Some(snapshot.text_for_range(start..end).collect())
15820    }
15821
15822    fn selected_text_range(
15823        &mut self,
15824        ignore_disabled_input: bool,
15825        _: &mut Window,
15826        cx: &mut Context<Self>,
15827    ) -> Option<UTF16Selection> {
15828        // Prevent the IME menu from appearing when holding down an alphabetic key
15829        // while input is disabled.
15830        if !ignore_disabled_input && !self.input_enabled {
15831            return None;
15832        }
15833
15834        let selection = self.selections.newest::<OffsetUtf16>(cx);
15835        let range = selection.range();
15836
15837        Some(UTF16Selection {
15838            range: range.start.0..range.end.0,
15839            reversed: selection.reversed,
15840        })
15841    }
15842
15843    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15844        let snapshot = self.buffer.read(cx).read(cx);
15845        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15846        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15847    }
15848
15849    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15850        self.clear_highlights::<InputComposition>(cx);
15851        self.ime_transaction.take();
15852    }
15853
15854    fn replace_text_in_range(
15855        &mut self,
15856        range_utf16: Option<Range<usize>>,
15857        text: &str,
15858        window: &mut Window,
15859        cx: &mut Context<Self>,
15860    ) {
15861        if !self.input_enabled {
15862            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15863            return;
15864        }
15865
15866        self.transact(window, cx, |this, window, cx| {
15867            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15868                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15869                Some(this.selection_replacement_ranges(range_utf16, cx))
15870            } else {
15871                this.marked_text_ranges(cx)
15872            };
15873
15874            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15875                let newest_selection_id = this.selections.newest_anchor().id;
15876                this.selections
15877                    .all::<OffsetUtf16>(cx)
15878                    .iter()
15879                    .zip(ranges_to_replace.iter())
15880                    .find_map(|(selection, range)| {
15881                        if selection.id == newest_selection_id {
15882                            Some(
15883                                (range.start.0 as isize - selection.head().0 as isize)
15884                                    ..(range.end.0 as isize - selection.head().0 as isize),
15885                            )
15886                        } else {
15887                            None
15888                        }
15889                    })
15890            });
15891
15892            cx.emit(EditorEvent::InputHandled {
15893                utf16_range_to_replace: range_to_replace,
15894                text: text.into(),
15895            });
15896
15897            if let Some(new_selected_ranges) = new_selected_ranges {
15898                this.change_selections(None, window, cx, |selections| {
15899                    selections.select_ranges(new_selected_ranges)
15900                });
15901                this.backspace(&Default::default(), window, cx);
15902            }
15903
15904            this.handle_input(text, window, cx);
15905        });
15906
15907        if let Some(transaction) = self.ime_transaction {
15908            self.buffer.update(cx, |buffer, cx| {
15909                buffer.group_until_transaction(transaction, cx);
15910            });
15911        }
15912
15913        self.unmark_text(window, cx);
15914    }
15915
15916    fn replace_and_mark_text_in_range(
15917        &mut self,
15918        range_utf16: Option<Range<usize>>,
15919        text: &str,
15920        new_selected_range_utf16: Option<Range<usize>>,
15921        window: &mut Window,
15922        cx: &mut Context<Self>,
15923    ) {
15924        if !self.input_enabled {
15925            return;
15926        }
15927
15928        let transaction = self.transact(window, cx, |this, window, cx| {
15929            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15930                let snapshot = this.buffer.read(cx).read(cx);
15931                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15932                    for marked_range in &mut marked_ranges {
15933                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15934                        marked_range.start.0 += relative_range_utf16.start;
15935                        marked_range.start =
15936                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15937                        marked_range.end =
15938                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15939                    }
15940                }
15941                Some(marked_ranges)
15942            } else if let Some(range_utf16) = range_utf16 {
15943                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15944                Some(this.selection_replacement_ranges(range_utf16, cx))
15945            } else {
15946                None
15947            };
15948
15949            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15950                let newest_selection_id = this.selections.newest_anchor().id;
15951                this.selections
15952                    .all::<OffsetUtf16>(cx)
15953                    .iter()
15954                    .zip(ranges_to_replace.iter())
15955                    .find_map(|(selection, range)| {
15956                        if selection.id == newest_selection_id {
15957                            Some(
15958                                (range.start.0 as isize - selection.head().0 as isize)
15959                                    ..(range.end.0 as isize - selection.head().0 as isize),
15960                            )
15961                        } else {
15962                            None
15963                        }
15964                    })
15965            });
15966
15967            cx.emit(EditorEvent::InputHandled {
15968                utf16_range_to_replace: range_to_replace,
15969                text: text.into(),
15970            });
15971
15972            if let Some(ranges) = ranges_to_replace {
15973                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15974            }
15975
15976            let marked_ranges = {
15977                let snapshot = this.buffer.read(cx).read(cx);
15978                this.selections
15979                    .disjoint_anchors()
15980                    .iter()
15981                    .map(|selection| {
15982                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15983                    })
15984                    .collect::<Vec<_>>()
15985            };
15986
15987            if text.is_empty() {
15988                this.unmark_text(window, cx);
15989            } else {
15990                this.highlight_text::<InputComposition>(
15991                    marked_ranges.clone(),
15992                    HighlightStyle {
15993                        underline: Some(UnderlineStyle {
15994                            thickness: px(1.),
15995                            color: None,
15996                            wavy: false,
15997                        }),
15998                        ..Default::default()
15999                    },
16000                    cx,
16001                );
16002            }
16003
16004            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16005            let use_autoclose = this.use_autoclose;
16006            let use_auto_surround = this.use_auto_surround;
16007            this.set_use_autoclose(false);
16008            this.set_use_auto_surround(false);
16009            this.handle_input(text, window, cx);
16010            this.set_use_autoclose(use_autoclose);
16011            this.set_use_auto_surround(use_auto_surround);
16012
16013            if let Some(new_selected_range) = new_selected_range_utf16 {
16014                let snapshot = this.buffer.read(cx).read(cx);
16015                let new_selected_ranges = marked_ranges
16016                    .into_iter()
16017                    .map(|marked_range| {
16018                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16019                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16020                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16021                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16022                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16023                    })
16024                    .collect::<Vec<_>>();
16025
16026                drop(snapshot);
16027                this.change_selections(None, window, cx, |selections| {
16028                    selections.select_ranges(new_selected_ranges)
16029                });
16030            }
16031        });
16032
16033        self.ime_transaction = self.ime_transaction.or(transaction);
16034        if let Some(transaction) = self.ime_transaction {
16035            self.buffer.update(cx, |buffer, cx| {
16036                buffer.group_until_transaction(transaction, cx);
16037            });
16038        }
16039
16040        if self.text_highlights::<InputComposition>(cx).is_none() {
16041            self.ime_transaction.take();
16042        }
16043    }
16044
16045    fn bounds_for_range(
16046        &mut self,
16047        range_utf16: Range<usize>,
16048        element_bounds: gpui::Bounds<Pixels>,
16049        window: &mut Window,
16050        cx: &mut Context<Self>,
16051    ) -> Option<gpui::Bounds<Pixels>> {
16052        let text_layout_details = self.text_layout_details(window);
16053        let gpui::Size {
16054            width: em_width,
16055            height: line_height,
16056        } = self.character_size(window);
16057
16058        let snapshot = self.snapshot(window, cx);
16059        let scroll_position = snapshot.scroll_position();
16060        let scroll_left = scroll_position.x * em_width;
16061
16062        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16063        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16064            + self.gutter_dimensions.width
16065            + self.gutter_dimensions.margin;
16066        let y = line_height * (start.row().as_f32() - scroll_position.y);
16067
16068        Some(Bounds {
16069            origin: element_bounds.origin + point(x, y),
16070            size: size(em_width, line_height),
16071        })
16072    }
16073
16074    fn character_index_for_point(
16075        &mut self,
16076        point: gpui::Point<Pixels>,
16077        _window: &mut Window,
16078        _cx: &mut Context<Self>,
16079    ) -> Option<usize> {
16080        let position_map = self.last_position_map.as_ref()?;
16081        if !position_map.text_hitbox.contains(&point) {
16082            return None;
16083        }
16084        let display_point = position_map.point_for_position(point).previous_valid;
16085        let anchor = position_map
16086            .snapshot
16087            .display_point_to_anchor(display_point, Bias::Left);
16088        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16089        Some(utf16_offset.0)
16090    }
16091}
16092
16093trait SelectionExt {
16094    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16095    fn spanned_rows(
16096        &self,
16097        include_end_if_at_line_start: bool,
16098        map: &DisplaySnapshot,
16099    ) -> Range<MultiBufferRow>;
16100}
16101
16102impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16103    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16104        let start = self
16105            .start
16106            .to_point(&map.buffer_snapshot)
16107            .to_display_point(map);
16108        let end = self
16109            .end
16110            .to_point(&map.buffer_snapshot)
16111            .to_display_point(map);
16112        if self.reversed {
16113            end..start
16114        } else {
16115            start..end
16116        }
16117    }
16118
16119    fn spanned_rows(
16120        &self,
16121        include_end_if_at_line_start: bool,
16122        map: &DisplaySnapshot,
16123    ) -> Range<MultiBufferRow> {
16124        let start = self.start.to_point(&map.buffer_snapshot);
16125        let mut end = self.end.to_point(&map.buffer_snapshot);
16126        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16127            end.row -= 1;
16128        }
16129
16130        let buffer_start = map.prev_line_boundary(start).0;
16131        let buffer_end = map.next_line_boundary(end).0;
16132        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16133    }
16134}
16135
16136impl<T: InvalidationRegion> InvalidationStack<T> {
16137    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16138    where
16139        S: Clone + ToOffset,
16140    {
16141        while let Some(region) = self.last() {
16142            let all_selections_inside_invalidation_ranges =
16143                if selections.len() == region.ranges().len() {
16144                    selections
16145                        .iter()
16146                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16147                        .all(|(selection, invalidation_range)| {
16148                            let head = selection.head().to_offset(buffer);
16149                            invalidation_range.start <= head && invalidation_range.end >= head
16150                        })
16151                } else {
16152                    false
16153                };
16154
16155            if all_selections_inside_invalidation_ranges {
16156                break;
16157            } else {
16158                self.pop();
16159            }
16160        }
16161    }
16162}
16163
16164impl<T> Default for InvalidationStack<T> {
16165    fn default() -> Self {
16166        Self(Default::default())
16167    }
16168}
16169
16170impl<T> Deref for InvalidationStack<T> {
16171    type Target = Vec<T>;
16172
16173    fn deref(&self) -> &Self::Target {
16174        &self.0
16175    }
16176}
16177
16178impl<T> DerefMut for InvalidationStack<T> {
16179    fn deref_mut(&mut self) -> &mut Self::Target {
16180        &mut self.0
16181    }
16182}
16183
16184impl InvalidationRegion for SnippetState {
16185    fn ranges(&self) -> &[Range<Anchor>] {
16186        &self.ranges[self.active_index]
16187    }
16188}
16189
16190pub fn diagnostic_block_renderer(
16191    diagnostic: Diagnostic,
16192    max_message_rows: Option<u8>,
16193    allow_closing: bool,
16194    _is_valid: bool,
16195) -> RenderBlock {
16196    let (text_without_backticks, code_ranges) =
16197        highlight_diagnostic_message(&diagnostic, max_message_rows);
16198
16199    Arc::new(move |cx: &mut BlockContext| {
16200        let group_id: SharedString = cx.block_id.to_string().into();
16201
16202        let mut text_style = cx.window.text_style().clone();
16203        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16204        let theme_settings = ThemeSettings::get_global(cx);
16205        text_style.font_family = theme_settings.buffer_font.family.clone();
16206        text_style.font_style = theme_settings.buffer_font.style;
16207        text_style.font_features = theme_settings.buffer_font.features.clone();
16208        text_style.font_weight = theme_settings.buffer_font.weight;
16209
16210        let multi_line_diagnostic = diagnostic.message.contains('\n');
16211
16212        let buttons = |diagnostic: &Diagnostic| {
16213            if multi_line_diagnostic {
16214                v_flex()
16215            } else {
16216                h_flex()
16217            }
16218            .when(allow_closing, |div| {
16219                div.children(diagnostic.is_primary.then(|| {
16220                    IconButton::new("close-block", IconName::XCircle)
16221                        .icon_color(Color::Muted)
16222                        .size(ButtonSize::Compact)
16223                        .style(ButtonStyle::Transparent)
16224                        .visible_on_hover(group_id.clone())
16225                        .on_click(move |_click, window, cx| {
16226                            window.dispatch_action(Box::new(Cancel), cx)
16227                        })
16228                        .tooltip(|window, cx| {
16229                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16230                        })
16231                }))
16232            })
16233            .child(
16234                IconButton::new("copy-block", IconName::Copy)
16235                    .icon_color(Color::Muted)
16236                    .size(ButtonSize::Compact)
16237                    .style(ButtonStyle::Transparent)
16238                    .visible_on_hover(group_id.clone())
16239                    .on_click({
16240                        let message = diagnostic.message.clone();
16241                        move |_click, _, cx| {
16242                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16243                        }
16244                    })
16245                    .tooltip(Tooltip::text("Copy diagnostic message")),
16246            )
16247        };
16248
16249        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16250            AvailableSpace::min_size(),
16251            cx.window,
16252            cx.app,
16253        );
16254
16255        h_flex()
16256            .id(cx.block_id)
16257            .group(group_id.clone())
16258            .relative()
16259            .size_full()
16260            .block_mouse_down()
16261            .pl(cx.gutter_dimensions.width)
16262            .w(cx.max_width - cx.gutter_dimensions.full_width())
16263            .child(
16264                div()
16265                    .flex()
16266                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16267                    .flex_shrink(),
16268            )
16269            .child(buttons(&diagnostic))
16270            .child(div().flex().flex_shrink_0().child(
16271                StyledText::new(text_without_backticks.clone()).with_highlights(
16272                    &text_style,
16273                    code_ranges.iter().map(|range| {
16274                        (
16275                            range.clone(),
16276                            HighlightStyle {
16277                                font_weight: Some(FontWeight::BOLD),
16278                                ..Default::default()
16279                            },
16280                        )
16281                    }),
16282                ),
16283            ))
16284            .into_any_element()
16285    })
16286}
16287
16288fn inline_completion_edit_text(
16289    current_snapshot: &BufferSnapshot,
16290    edits: &[(Range<Anchor>, String)],
16291    edit_preview: &EditPreview,
16292    include_deletions: bool,
16293    cx: &App,
16294) -> HighlightedText {
16295    let edits = edits
16296        .iter()
16297        .map(|(anchor, text)| {
16298            (
16299                anchor.start.text_anchor..anchor.end.text_anchor,
16300                text.clone(),
16301            )
16302        })
16303        .collect::<Vec<_>>();
16304
16305    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16306}
16307
16308pub fn highlight_diagnostic_message(
16309    diagnostic: &Diagnostic,
16310    mut max_message_rows: Option<u8>,
16311) -> (SharedString, Vec<Range<usize>>) {
16312    let mut text_without_backticks = String::new();
16313    let mut code_ranges = Vec::new();
16314
16315    if let Some(source) = &diagnostic.source {
16316        text_without_backticks.push_str(source);
16317        code_ranges.push(0..source.len());
16318        text_without_backticks.push_str(": ");
16319    }
16320
16321    let mut prev_offset = 0;
16322    let mut in_code_block = false;
16323    let has_row_limit = max_message_rows.is_some();
16324    let mut newline_indices = diagnostic
16325        .message
16326        .match_indices('\n')
16327        .filter(|_| has_row_limit)
16328        .map(|(ix, _)| ix)
16329        .fuse()
16330        .peekable();
16331
16332    for (quote_ix, _) in diagnostic
16333        .message
16334        .match_indices('`')
16335        .chain([(diagnostic.message.len(), "")])
16336    {
16337        let mut first_newline_ix = None;
16338        let mut last_newline_ix = None;
16339        while let Some(newline_ix) = newline_indices.peek() {
16340            if *newline_ix < quote_ix {
16341                if first_newline_ix.is_none() {
16342                    first_newline_ix = Some(*newline_ix);
16343                }
16344                last_newline_ix = Some(*newline_ix);
16345
16346                if let Some(rows_left) = &mut max_message_rows {
16347                    if *rows_left == 0 {
16348                        break;
16349                    } else {
16350                        *rows_left -= 1;
16351                    }
16352                }
16353                let _ = newline_indices.next();
16354            } else {
16355                break;
16356            }
16357        }
16358        let prev_len = text_without_backticks.len();
16359        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16360        text_without_backticks.push_str(new_text);
16361        if in_code_block {
16362            code_ranges.push(prev_len..text_without_backticks.len());
16363        }
16364        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16365        in_code_block = !in_code_block;
16366        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16367            text_without_backticks.push_str("...");
16368            break;
16369        }
16370    }
16371
16372    (text_without_backticks.into(), code_ranges)
16373}
16374
16375fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16376    match severity {
16377        DiagnosticSeverity::ERROR => colors.error,
16378        DiagnosticSeverity::WARNING => colors.warning,
16379        DiagnosticSeverity::INFORMATION => colors.info,
16380        DiagnosticSeverity::HINT => colors.info,
16381        _ => colors.ignored,
16382    }
16383}
16384
16385pub fn styled_runs_for_code_label<'a>(
16386    label: &'a CodeLabel,
16387    syntax_theme: &'a theme::SyntaxTheme,
16388) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16389    let fade_out = HighlightStyle {
16390        fade_out: Some(0.35),
16391        ..Default::default()
16392    };
16393
16394    let mut prev_end = label.filter_range.end;
16395    label
16396        .runs
16397        .iter()
16398        .enumerate()
16399        .flat_map(move |(ix, (range, highlight_id))| {
16400            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16401                style
16402            } else {
16403                return Default::default();
16404            };
16405            let mut muted_style = style;
16406            muted_style.highlight(fade_out);
16407
16408            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16409            if range.start >= label.filter_range.end {
16410                if range.start > prev_end {
16411                    runs.push((prev_end..range.start, fade_out));
16412                }
16413                runs.push((range.clone(), muted_style));
16414            } else if range.end <= label.filter_range.end {
16415                runs.push((range.clone(), style));
16416            } else {
16417                runs.push((range.start..label.filter_range.end, style));
16418                runs.push((label.filter_range.end..range.end, muted_style));
16419            }
16420            prev_end = cmp::max(prev_end, range.end);
16421
16422            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16423                runs.push((prev_end..label.text.len(), fade_out));
16424            }
16425
16426            runs
16427        })
16428}
16429
16430pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16431    let mut prev_index = 0;
16432    let mut prev_codepoint: Option<char> = None;
16433    text.char_indices()
16434        .chain([(text.len(), '\0')])
16435        .filter_map(move |(index, codepoint)| {
16436            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16437            let is_boundary = index == text.len()
16438                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16439                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16440            if is_boundary {
16441                let chunk = &text[prev_index..index];
16442                prev_index = index;
16443                Some(chunk)
16444            } else {
16445                None
16446            }
16447        })
16448}
16449
16450pub trait RangeToAnchorExt: Sized {
16451    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16452
16453    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16454        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16455        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16456    }
16457}
16458
16459impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16460    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16461        let start_offset = self.start.to_offset(snapshot);
16462        let end_offset = self.end.to_offset(snapshot);
16463        if start_offset == end_offset {
16464            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16465        } else {
16466            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16467        }
16468    }
16469}
16470
16471pub trait RowExt {
16472    fn as_f32(&self) -> f32;
16473
16474    fn next_row(&self) -> Self;
16475
16476    fn previous_row(&self) -> Self;
16477
16478    fn minus(&self, other: Self) -> u32;
16479}
16480
16481impl RowExt for DisplayRow {
16482    fn as_f32(&self) -> f32 {
16483        self.0 as f32
16484    }
16485
16486    fn next_row(&self) -> Self {
16487        Self(self.0 + 1)
16488    }
16489
16490    fn previous_row(&self) -> Self {
16491        Self(self.0.saturating_sub(1))
16492    }
16493
16494    fn minus(&self, other: Self) -> u32 {
16495        self.0 - other.0
16496    }
16497}
16498
16499impl RowExt for MultiBufferRow {
16500    fn as_f32(&self) -> f32 {
16501        self.0 as f32
16502    }
16503
16504    fn next_row(&self) -> Self {
16505        Self(self.0 + 1)
16506    }
16507
16508    fn previous_row(&self) -> Self {
16509        Self(self.0.saturating_sub(1))
16510    }
16511
16512    fn minus(&self, other: Self) -> u32 {
16513        self.0 - other.0
16514    }
16515}
16516
16517trait RowRangeExt {
16518    type Row;
16519
16520    fn len(&self) -> usize;
16521
16522    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16523}
16524
16525impl RowRangeExt for Range<MultiBufferRow> {
16526    type Row = MultiBufferRow;
16527
16528    fn len(&self) -> usize {
16529        (self.end.0 - self.start.0) as usize
16530    }
16531
16532    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16533        (self.start.0..self.end.0).map(MultiBufferRow)
16534    }
16535}
16536
16537impl RowRangeExt for Range<DisplayRow> {
16538    type Row = DisplayRow;
16539
16540    fn len(&self) -> usize {
16541        (self.end.0 - self.start.0) as usize
16542    }
16543
16544    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16545        (self.start.0..self.end.0).map(DisplayRow)
16546    }
16547}
16548
16549/// If select range has more than one line, we
16550/// just point the cursor to range.start.
16551fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16552    if range.start.row == range.end.row {
16553        range
16554    } else {
16555        range.start..range.start
16556    }
16557}
16558pub struct KillRing(ClipboardItem);
16559impl Global for KillRing {}
16560
16561const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16562
16563fn all_edits_insertions_or_deletions(
16564    edits: &Vec<(Range<Anchor>, String)>,
16565    snapshot: &MultiBufferSnapshot,
16566) -> bool {
16567    let mut all_insertions = true;
16568    let mut all_deletions = true;
16569
16570    for (range, new_text) in edits.iter() {
16571        let range_is_empty = range.to_offset(&snapshot).is_empty();
16572        let text_is_empty = new_text.is_empty();
16573
16574        if range_is_empty != text_is_empty {
16575            if range_is_empty {
16576                all_deletions = false;
16577            } else {
16578                all_insertions = false;
16579            }
16580        } else {
16581            return false;
16582        }
16583
16584        if !all_insertions && !all_deletions {
16585            return false;
16586        }
16587    }
16588    all_insertions || all_deletions
16589}