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
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66pub use element::{
   67    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   68};
   69use element::{LineWithInvisibles, PositionMap};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72
   73use code_context_menus::{
   74    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   75    CompletionsMenu, ContextMenuOrigin,
   76};
   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, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    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::{InlineCompletionProvider, 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(bool),
  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    invalidation_range: Range<Anchor>,
  494}
  495
  496impl InlineCompletionState {
  497    pub fn is_move(&self) -> bool {
  498        match &self.completion {
  499            InlineCompletion::Move { .. } => true,
  500            _ => false,
  501        }
  502    }
  503}
  504
  505enum InlineCompletionHighlight {}
  506
  507pub enum MenuInlineCompletionsPolicy {
  508    Never,
  509    ByProvider,
  510}
  511
  512#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  513struct EditorActionId(usize);
  514
  515impl EditorActionId {
  516    pub fn post_inc(&mut self) -> Self {
  517        let answer = self.0;
  518
  519        *self = Self(answer + 1);
  520
  521        Self(answer)
  522    }
  523}
  524
  525// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  526// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  527
  528type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  529type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  530
  531#[derive(Default)]
  532struct ScrollbarMarkerState {
  533    scrollbar_size: Size<Pixels>,
  534    dirty: bool,
  535    markers: Arc<[PaintQuad]>,
  536    pending_refresh: Option<Task<Result<()>>>,
  537}
  538
  539impl ScrollbarMarkerState {
  540    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  541        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  542    }
  543}
  544
  545#[derive(Clone, Debug)]
  546struct RunnableTasks {
  547    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  548    offset: MultiBufferOffset,
  549    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  550    column: u32,
  551    // Values of all named captures, including those starting with '_'
  552    extra_variables: HashMap<String, String>,
  553    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  554    context_range: Range<BufferOffset>,
  555}
  556
  557impl RunnableTasks {
  558    fn resolve<'a>(
  559        &'a self,
  560        cx: &'a task::TaskContext,
  561    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  562        self.templates.iter().filter_map(|(kind, template)| {
  563            template
  564                .resolve_task(&kind.to_id_base(), cx)
  565                .map(|task| (kind.clone(), task))
  566        })
  567    }
  568}
  569
  570#[derive(Clone)]
  571struct ResolvedTasks {
  572    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  573    position: Anchor,
  574}
  575#[derive(Copy, Clone, Debug)]
  576struct MultiBufferOffset(usize);
  577#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  578struct BufferOffset(usize);
  579
  580// Addons allow storing per-editor state in other crates (e.g. Vim)
  581pub trait Addon: 'static {
  582    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  583
  584    fn render_buffer_header_controls(
  585        &self,
  586        _: &ExcerptInfo,
  587        _: &Window,
  588        _: &App,
  589    ) -> Option<AnyElement> {
  590        None
  591    }
  592
  593    fn to_any(&self) -> &dyn std::any::Any;
  594}
  595
  596#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  597pub enum IsVimMode {
  598    Yes,
  599    No,
  600}
  601
  602/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  603///
  604/// See the [module level documentation](self) for more information.
  605pub struct Editor {
  606    focus_handle: FocusHandle,
  607    last_focused_descendant: Option<WeakFocusHandle>,
  608    /// The text buffer being edited
  609    buffer: Entity<MultiBuffer>,
  610    /// Map of how text in the buffer should be displayed.
  611    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  612    pub display_map: Entity<DisplayMap>,
  613    pub selections: SelectionsCollection,
  614    pub scroll_manager: ScrollManager,
  615    /// When inline assist editors are linked, they all render cursors because
  616    /// typing enters text into each of them, even the ones that aren't focused.
  617    pub(crate) show_cursor_when_unfocused: bool,
  618    columnar_selection_tail: Option<Anchor>,
  619    add_selections_state: Option<AddSelectionsState>,
  620    select_next_state: Option<SelectNextState>,
  621    select_prev_state: Option<SelectNextState>,
  622    selection_history: SelectionHistory,
  623    autoclose_regions: Vec<AutocloseRegion>,
  624    snippet_stack: InvalidationStack<SnippetState>,
  625    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  626    ime_transaction: Option<TransactionId>,
  627    active_diagnostics: Option<ActiveDiagnosticGroup>,
  628    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  629
  630    // TODO: make this a access method
  631    pub project: Option<Entity<Project>>,
  632    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  633    completion_provider: Option<Box<dyn CompletionProvider>>,
  634    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  635    blink_manager: Entity<BlinkManager>,
  636    show_cursor_names: bool,
  637    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  638    pub show_local_selections: bool,
  639    mode: EditorMode,
  640    show_breadcrumbs: bool,
  641    show_gutter: bool,
  642    show_scrollbars: bool,
  643    show_line_numbers: Option<bool>,
  644    use_relative_line_numbers: Option<bool>,
  645    show_git_diff_gutter: Option<bool>,
  646    show_code_actions: Option<bool>,
  647    show_runnables: Option<bool>,
  648    show_wrap_guides: Option<bool>,
  649    show_indent_guides: Option<bool>,
  650    placeholder_text: Option<Arc<str>>,
  651    highlight_order: usize,
  652    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  653    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  654    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  655    scrollbar_marker_state: ScrollbarMarkerState,
  656    active_indent_guides_state: ActiveIndentGuidesState,
  657    nav_history: Option<ItemNavHistory>,
  658    context_menu: RefCell<Option<CodeContextMenu>>,
  659    mouse_context_menu: Option<MouseContextMenu>,
  660    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  661    signature_help_state: SignatureHelpState,
  662    auto_signature_help: Option<bool>,
  663    find_all_references_task_sources: Vec<Anchor>,
  664    next_completion_id: CompletionId,
  665    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  666    code_actions_task: Option<Task<Result<()>>>,
  667    document_highlights_task: Option<Task<()>>,
  668    linked_editing_range_task: Option<Task<Option<()>>>,
  669    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  670    pending_rename: Option<RenameState>,
  671    searchable: bool,
  672    cursor_shape: CursorShape,
  673    current_line_highlight: Option<CurrentLineHighlight>,
  674    collapse_matches: bool,
  675    autoindent_mode: Option<AutoindentMode>,
  676    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  677    input_enabled: bool,
  678    use_modal_editing: bool,
  679    read_only: bool,
  680    leader_peer_id: Option<PeerId>,
  681    remote_id: Option<ViewId>,
  682    hover_state: HoverState,
  683    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  684    gutter_hovered: bool,
  685    hovered_link_state: Option<HoveredLinkState>,
  686    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  687    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  688    active_inline_completion: Option<InlineCompletionState>,
  689    /// Used to prevent flickering as the user types while the menu is open
  690    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  691    // enable_inline_completions is a switch that Vim can use to disable
  692    // edit predictions based on its mode.
  693    show_inline_completions: bool,
  694    show_inline_completions_override: Option<bool>,
  695    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  696    previewing_inline_completion: bool,
  697    inlay_hint_cache: InlayHintCache,
  698    next_inlay_id: usize,
  699    _subscriptions: Vec<Subscription>,
  700    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  701    gutter_dimensions: GutterDimensions,
  702    style: Option<EditorStyle>,
  703    text_style_refinement: Option<TextStyleRefinement>,
  704    next_editor_action_id: EditorActionId,
  705    editor_actions:
  706        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  707    use_autoclose: bool,
  708    use_auto_surround: bool,
  709    auto_replace_emoji_shortcode: bool,
  710    show_git_blame_gutter: bool,
  711    show_git_blame_inline: bool,
  712    show_git_blame_inline_delay_task: Option<Task<()>>,
  713    git_blame_inline_enabled: bool,
  714    serialize_dirty_buffers: bool,
  715    show_selection_menu: Option<bool>,
  716    blame: Option<Entity<GitBlame>>,
  717    blame_subscription: Option<Subscription>,
  718    custom_context_menu: Option<
  719        Box<
  720            dyn 'static
  721                + Fn(
  722                    &mut Self,
  723                    DisplayPoint,
  724                    &mut Window,
  725                    &mut Context<Self>,
  726                ) -> Option<Entity<ui::ContextMenu>>,
  727        >,
  728    >,
  729    last_bounds: Option<Bounds<Pixels>>,
  730    last_position_map: Option<Rc<PositionMap>>,
  731    expect_bounds_change: Option<Bounds<Pixels>>,
  732    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  733    tasks_update_task: Option<Task<()>>,
  734    in_project_search: bool,
  735    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  736    breadcrumb_header: Option<String>,
  737    focused_block: Option<FocusedBlock>,
  738    next_scroll_position: NextScrollCursorCenterTopBottom,
  739    addons: HashMap<TypeId, Box<dyn Addon>>,
  740    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  741    selection_mark_mode: bool,
  742    toggle_fold_multiple_buffers: Task<()>,
  743    _scroll_cursor_center_top_bottom_task: Task<()>,
  744}
  745
  746#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  747enum NextScrollCursorCenterTopBottom {
  748    #[default]
  749    Center,
  750    Top,
  751    Bottom,
  752}
  753
  754impl NextScrollCursorCenterTopBottom {
  755    fn next(&self) -> Self {
  756        match self {
  757            Self::Center => Self::Top,
  758            Self::Top => Self::Bottom,
  759            Self::Bottom => Self::Center,
  760        }
  761    }
  762}
  763
  764#[derive(Clone)]
  765pub struct EditorSnapshot {
  766    pub mode: EditorMode,
  767    show_gutter: bool,
  768    show_line_numbers: Option<bool>,
  769    show_git_diff_gutter: Option<bool>,
  770    show_code_actions: Option<bool>,
  771    show_runnables: Option<bool>,
  772    git_blame_gutter_max_author_length: Option<usize>,
  773    pub display_snapshot: DisplaySnapshot,
  774    pub placeholder_text: Option<Arc<str>>,
  775    is_focused: bool,
  776    scroll_anchor: ScrollAnchor,
  777    ongoing_scroll: OngoingScroll,
  778    current_line_highlight: CurrentLineHighlight,
  779    gutter_hovered: bool,
  780}
  781
  782const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  783
  784#[derive(Default, Debug, Clone, Copy)]
  785pub struct GutterDimensions {
  786    pub left_padding: Pixels,
  787    pub right_padding: Pixels,
  788    pub width: Pixels,
  789    pub margin: Pixels,
  790    pub git_blame_entries_width: Option<Pixels>,
  791}
  792
  793impl GutterDimensions {
  794    /// The full width of the space taken up by the gutter.
  795    pub fn full_width(&self) -> Pixels {
  796        self.margin + self.width
  797    }
  798
  799    /// The width of the space reserved for the fold indicators,
  800    /// use alongside 'justify_end' and `gutter_width` to
  801    /// right align content with the line numbers
  802    pub fn fold_area_width(&self) -> Pixels {
  803        self.margin + self.right_padding
  804    }
  805}
  806
  807#[derive(Debug)]
  808pub struct RemoteSelection {
  809    pub replica_id: ReplicaId,
  810    pub selection: Selection<Anchor>,
  811    pub cursor_shape: CursorShape,
  812    pub peer_id: PeerId,
  813    pub line_mode: bool,
  814    pub participant_index: Option<ParticipantIndex>,
  815    pub user_name: Option<SharedString>,
  816}
  817
  818#[derive(Clone, Debug)]
  819struct SelectionHistoryEntry {
  820    selections: Arc<[Selection<Anchor>]>,
  821    select_next_state: Option<SelectNextState>,
  822    select_prev_state: Option<SelectNextState>,
  823    add_selections_state: Option<AddSelectionsState>,
  824}
  825
  826enum SelectionHistoryMode {
  827    Normal,
  828    Undoing,
  829    Redoing,
  830}
  831
  832#[derive(Clone, PartialEq, Eq, Hash)]
  833struct HoveredCursor {
  834    replica_id: u16,
  835    selection_id: usize,
  836}
  837
  838impl Default for SelectionHistoryMode {
  839    fn default() -> Self {
  840        Self::Normal
  841    }
  842}
  843
  844#[derive(Default)]
  845struct SelectionHistory {
  846    #[allow(clippy::type_complexity)]
  847    selections_by_transaction:
  848        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  849    mode: SelectionHistoryMode,
  850    undo_stack: VecDeque<SelectionHistoryEntry>,
  851    redo_stack: VecDeque<SelectionHistoryEntry>,
  852}
  853
  854impl SelectionHistory {
  855    fn insert_transaction(
  856        &mut self,
  857        transaction_id: TransactionId,
  858        selections: Arc<[Selection<Anchor>]>,
  859    ) {
  860        self.selections_by_transaction
  861            .insert(transaction_id, (selections, None));
  862    }
  863
  864    #[allow(clippy::type_complexity)]
  865    fn transaction(
  866        &self,
  867        transaction_id: TransactionId,
  868    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  869        self.selections_by_transaction.get(&transaction_id)
  870    }
  871
  872    #[allow(clippy::type_complexity)]
  873    fn transaction_mut(
  874        &mut self,
  875        transaction_id: TransactionId,
  876    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  877        self.selections_by_transaction.get_mut(&transaction_id)
  878    }
  879
  880    fn push(&mut self, entry: SelectionHistoryEntry) {
  881        if !entry.selections.is_empty() {
  882            match self.mode {
  883                SelectionHistoryMode::Normal => {
  884                    self.push_undo(entry);
  885                    self.redo_stack.clear();
  886                }
  887                SelectionHistoryMode::Undoing => self.push_redo(entry),
  888                SelectionHistoryMode::Redoing => self.push_undo(entry),
  889            }
  890        }
  891    }
  892
  893    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  894        if self
  895            .undo_stack
  896            .back()
  897            .map_or(true, |e| e.selections != entry.selections)
  898        {
  899            self.undo_stack.push_back(entry);
  900            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  901                self.undo_stack.pop_front();
  902            }
  903        }
  904    }
  905
  906    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  907        if self
  908            .redo_stack
  909            .back()
  910            .map_or(true, |e| e.selections != entry.selections)
  911        {
  912            self.redo_stack.push_back(entry);
  913            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  914                self.redo_stack.pop_front();
  915            }
  916        }
  917    }
  918}
  919
  920struct RowHighlight {
  921    index: usize,
  922    range: Range<Anchor>,
  923    color: Hsla,
  924    should_autoscroll: bool,
  925}
  926
  927#[derive(Clone, Debug)]
  928struct AddSelectionsState {
  929    above: bool,
  930    stack: Vec<usize>,
  931}
  932
  933#[derive(Clone)]
  934struct SelectNextState {
  935    query: AhoCorasick,
  936    wordwise: bool,
  937    done: bool,
  938}
  939
  940impl std::fmt::Debug for SelectNextState {
  941    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  942        f.debug_struct(std::any::type_name::<Self>())
  943            .field("wordwise", &self.wordwise)
  944            .field("done", &self.done)
  945            .finish()
  946    }
  947}
  948
  949#[derive(Debug)]
  950struct AutocloseRegion {
  951    selection_id: usize,
  952    range: Range<Anchor>,
  953    pair: BracketPair,
  954}
  955
  956#[derive(Debug)]
  957struct SnippetState {
  958    ranges: Vec<Vec<Range<Anchor>>>,
  959    active_index: usize,
  960    choices: Vec<Option<Vec<String>>>,
  961}
  962
  963#[doc(hidden)]
  964pub struct RenameState {
  965    pub range: Range<Anchor>,
  966    pub old_name: Arc<str>,
  967    pub editor: Entity<Editor>,
  968    block_id: CustomBlockId,
  969}
  970
  971struct InvalidationStack<T>(Vec<T>);
  972
  973struct RegisteredInlineCompletionProvider {
  974    provider: Arc<dyn InlineCompletionProviderHandle>,
  975    _subscription: Subscription,
  976}
  977
  978#[derive(Debug)]
  979struct ActiveDiagnosticGroup {
  980    primary_range: Range<Anchor>,
  981    primary_message: String,
  982    group_id: usize,
  983    blocks: HashMap<CustomBlockId, Diagnostic>,
  984    is_valid: bool,
  985}
  986
  987#[derive(Serialize, Deserialize, Clone, Debug)]
  988pub struct ClipboardSelection {
  989    pub len: usize,
  990    pub is_entire_line: bool,
  991    pub first_line_indent: u32,
  992}
  993
  994#[derive(Debug)]
  995pub(crate) struct NavigationData {
  996    cursor_anchor: Anchor,
  997    cursor_position: Point,
  998    scroll_anchor: ScrollAnchor,
  999    scroll_top_row: u32,
 1000}
 1001
 1002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1003pub enum GotoDefinitionKind {
 1004    Symbol,
 1005    Declaration,
 1006    Type,
 1007    Implementation,
 1008}
 1009
 1010#[derive(Debug, Clone)]
 1011enum InlayHintRefreshReason {
 1012    Toggle(bool),
 1013    SettingsChange(InlayHintSettings),
 1014    NewLinesShown,
 1015    BufferEdited(HashSet<Arc<Language>>),
 1016    RefreshRequested,
 1017    ExcerptsRemoved(Vec<ExcerptId>),
 1018}
 1019
 1020impl InlayHintRefreshReason {
 1021    fn description(&self) -> &'static str {
 1022        match self {
 1023            Self::Toggle(_) => "toggle",
 1024            Self::SettingsChange(_) => "settings change",
 1025            Self::NewLinesShown => "new lines shown",
 1026            Self::BufferEdited(_) => "buffer edited",
 1027            Self::RefreshRequested => "refresh requested",
 1028            Self::ExcerptsRemoved(_) => "excerpts removed",
 1029        }
 1030    }
 1031}
 1032
 1033pub enum FormatTarget {
 1034    Buffers,
 1035    Ranges(Vec<Range<MultiBufferPoint>>),
 1036}
 1037
 1038pub(crate) struct FocusedBlock {
 1039    id: BlockId,
 1040    focus_handle: WeakFocusHandle,
 1041}
 1042
 1043#[derive(Clone)]
 1044enum JumpData {
 1045    MultiBufferRow {
 1046        row: MultiBufferRow,
 1047        line_offset_from_top: u32,
 1048    },
 1049    MultiBufferPoint {
 1050        excerpt_id: ExcerptId,
 1051        position: Point,
 1052        anchor: text::Anchor,
 1053        line_offset_from_top: u32,
 1054    },
 1055}
 1056
 1057pub enum MultibufferSelectionMode {
 1058    First,
 1059    All,
 1060}
 1061
 1062impl Editor {
 1063    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1064        let buffer = cx.new(|cx| Buffer::local("", cx));
 1065        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1066        Self::new(
 1067            EditorMode::SingleLine { auto_width: false },
 1068            buffer,
 1069            None,
 1070            false,
 1071            window,
 1072            cx,
 1073        )
 1074    }
 1075
 1076    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1077        let buffer = cx.new(|cx| Buffer::local("", cx));
 1078        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1079        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1080    }
 1081
 1082    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1083        let buffer = cx.new(|cx| Buffer::local("", cx));
 1084        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1085        Self::new(
 1086            EditorMode::SingleLine { auto_width: true },
 1087            buffer,
 1088            None,
 1089            false,
 1090            window,
 1091            cx,
 1092        )
 1093    }
 1094
 1095    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1096        let buffer = cx.new(|cx| Buffer::local("", cx));
 1097        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1098        Self::new(
 1099            EditorMode::AutoHeight { max_lines },
 1100            buffer,
 1101            None,
 1102            false,
 1103            window,
 1104            cx,
 1105        )
 1106    }
 1107
 1108    pub fn for_buffer(
 1109        buffer: Entity<Buffer>,
 1110        project: Option<Entity<Project>>,
 1111        window: &mut Window,
 1112        cx: &mut Context<Self>,
 1113    ) -> Self {
 1114        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1115        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1116    }
 1117
 1118    pub fn for_multibuffer(
 1119        buffer: Entity<MultiBuffer>,
 1120        project: Option<Entity<Project>>,
 1121        show_excerpt_controls: bool,
 1122        window: &mut Window,
 1123        cx: &mut Context<Self>,
 1124    ) -> Self {
 1125        Self::new(
 1126            EditorMode::Full,
 1127            buffer,
 1128            project,
 1129            show_excerpt_controls,
 1130            window,
 1131            cx,
 1132        )
 1133    }
 1134
 1135    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1136        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1137        let mut clone = Self::new(
 1138            self.mode,
 1139            self.buffer.clone(),
 1140            self.project.clone(),
 1141            show_excerpt_controls,
 1142            window,
 1143            cx,
 1144        );
 1145        self.display_map.update(cx, |display_map, cx| {
 1146            let snapshot = display_map.snapshot(cx);
 1147            clone.display_map.update(cx, |display_map, cx| {
 1148                display_map.set_state(&snapshot, cx);
 1149            });
 1150        });
 1151        clone.selections.clone_state(&self.selections);
 1152        clone.scroll_manager.clone_state(&self.scroll_manager);
 1153        clone.searchable = self.searchable;
 1154        clone
 1155    }
 1156
 1157    pub fn new(
 1158        mode: EditorMode,
 1159        buffer: Entity<MultiBuffer>,
 1160        project: Option<Entity<Project>>,
 1161        show_excerpt_controls: bool,
 1162        window: &mut Window,
 1163        cx: &mut Context<Self>,
 1164    ) -> Self {
 1165        let style = window.text_style();
 1166        let font_size = style.font_size.to_pixels(window.rem_size());
 1167        let editor = cx.entity().downgrade();
 1168        let fold_placeholder = FoldPlaceholder {
 1169            constrain_width: true,
 1170            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1171                let editor = editor.clone();
 1172                div()
 1173                    .id(fold_id)
 1174                    .bg(cx.theme().colors().ghost_element_background)
 1175                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1176                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1177                    .rounded_sm()
 1178                    .size_full()
 1179                    .cursor_pointer()
 1180                    .child("")
 1181                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1182                    .on_click(move |_, _window, cx| {
 1183                        editor
 1184                            .update(cx, |editor, cx| {
 1185                                editor.unfold_ranges(
 1186                                    &[fold_range.start..fold_range.end],
 1187                                    true,
 1188                                    false,
 1189                                    cx,
 1190                                );
 1191                                cx.stop_propagation();
 1192                            })
 1193                            .ok();
 1194                    })
 1195                    .into_any()
 1196            }),
 1197            merge_adjacent: true,
 1198            ..Default::default()
 1199        };
 1200        let display_map = cx.new(|cx| {
 1201            DisplayMap::new(
 1202                buffer.clone(),
 1203                style.font(),
 1204                font_size,
 1205                None,
 1206                show_excerpt_controls,
 1207                FILE_HEADER_HEIGHT,
 1208                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1209                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1210                fold_placeholder,
 1211                cx,
 1212            )
 1213        });
 1214
 1215        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1216
 1217        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1218
 1219        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1220            .then(|| language_settings::SoftWrap::None);
 1221
 1222        let mut project_subscriptions = Vec::new();
 1223        if mode == EditorMode::Full {
 1224            if let Some(project) = project.as_ref() {
 1225                if buffer.read(cx).is_singleton() {
 1226                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1227                        cx.emit(EditorEvent::TitleChanged);
 1228                    }));
 1229                }
 1230                project_subscriptions.push(cx.subscribe_in(
 1231                    project,
 1232                    window,
 1233                    |editor, _, event, window, cx| {
 1234                        if let project::Event::RefreshInlayHints = event {
 1235                            editor
 1236                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1237                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1238                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1239                                let focus_handle = editor.focus_handle(cx);
 1240                                if focus_handle.is_focused(window) {
 1241                                    let snapshot = buffer.read(cx).snapshot();
 1242                                    for (range, snippet) in snippet_edits {
 1243                                        let editor_range =
 1244                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1245                                        editor
 1246                                            .insert_snippet(
 1247                                                &[editor_range],
 1248                                                snippet.clone(),
 1249                                                window,
 1250                                                cx,
 1251                                            )
 1252                                            .ok();
 1253                                    }
 1254                                }
 1255                            }
 1256                        }
 1257                    },
 1258                ));
 1259                if let Some(task_inventory) = project
 1260                    .read(cx)
 1261                    .task_store()
 1262                    .read(cx)
 1263                    .task_inventory()
 1264                    .cloned()
 1265                {
 1266                    project_subscriptions.push(cx.observe_in(
 1267                        &task_inventory,
 1268                        window,
 1269                        |editor, _, window, cx| {
 1270                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1271                        },
 1272                    ));
 1273                }
 1274            }
 1275        }
 1276
 1277        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1278
 1279        let inlay_hint_settings =
 1280            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1281        let focus_handle = cx.focus_handle();
 1282        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1283            .detach();
 1284        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1285            .detach();
 1286        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1287            .detach();
 1288        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1289            .detach();
 1290
 1291        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1292            Some(false)
 1293        } else {
 1294            None
 1295        };
 1296
 1297        let mut code_action_providers = Vec::new();
 1298        if let Some(project) = project.clone() {
 1299            get_uncommitted_changes_for_buffer(
 1300                &project,
 1301                buffer.read(cx).all_buffers(),
 1302                buffer.clone(),
 1303                cx,
 1304            );
 1305            code_action_providers.push(Rc::new(project) as Rc<_>);
 1306        }
 1307
 1308        let mut this = Self {
 1309            focus_handle,
 1310            show_cursor_when_unfocused: false,
 1311            last_focused_descendant: None,
 1312            buffer: buffer.clone(),
 1313            display_map: display_map.clone(),
 1314            selections,
 1315            scroll_manager: ScrollManager::new(cx),
 1316            columnar_selection_tail: None,
 1317            add_selections_state: None,
 1318            select_next_state: None,
 1319            select_prev_state: None,
 1320            selection_history: Default::default(),
 1321            autoclose_regions: Default::default(),
 1322            snippet_stack: Default::default(),
 1323            select_larger_syntax_node_stack: Vec::new(),
 1324            ime_transaction: Default::default(),
 1325            active_diagnostics: None,
 1326            soft_wrap_mode_override,
 1327            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1328            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1329            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1330            project,
 1331            blink_manager: blink_manager.clone(),
 1332            show_local_selections: true,
 1333            show_scrollbars: true,
 1334            mode,
 1335            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1336            show_gutter: mode == EditorMode::Full,
 1337            show_line_numbers: None,
 1338            use_relative_line_numbers: None,
 1339            show_git_diff_gutter: None,
 1340            show_code_actions: None,
 1341            show_runnables: None,
 1342            show_wrap_guides: None,
 1343            show_indent_guides,
 1344            placeholder_text: None,
 1345            highlight_order: 0,
 1346            highlighted_rows: HashMap::default(),
 1347            background_highlights: Default::default(),
 1348            gutter_highlights: TreeMap::default(),
 1349            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1350            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1351            nav_history: None,
 1352            context_menu: RefCell::new(None),
 1353            mouse_context_menu: None,
 1354            completion_tasks: Default::default(),
 1355            signature_help_state: SignatureHelpState::default(),
 1356            auto_signature_help: None,
 1357            find_all_references_task_sources: Vec::new(),
 1358            next_completion_id: 0,
 1359            next_inlay_id: 0,
 1360            code_action_providers,
 1361            available_code_actions: Default::default(),
 1362            code_actions_task: Default::default(),
 1363            document_highlights_task: Default::default(),
 1364            linked_editing_range_task: Default::default(),
 1365            pending_rename: Default::default(),
 1366            searchable: true,
 1367            cursor_shape: EditorSettings::get_global(cx)
 1368                .cursor_shape
 1369                .unwrap_or_default(),
 1370            current_line_highlight: None,
 1371            autoindent_mode: Some(AutoindentMode::EachLine),
 1372            collapse_matches: false,
 1373            workspace: None,
 1374            input_enabled: true,
 1375            use_modal_editing: mode == EditorMode::Full,
 1376            read_only: false,
 1377            use_autoclose: true,
 1378            use_auto_surround: true,
 1379            auto_replace_emoji_shortcode: false,
 1380            leader_peer_id: None,
 1381            remote_id: None,
 1382            hover_state: Default::default(),
 1383            pending_mouse_down: None,
 1384            hovered_link_state: Default::default(),
 1385            inline_completion_provider: None,
 1386            active_inline_completion: None,
 1387            stale_inline_completion_in_menu: None,
 1388            previewing_inline_completion: false,
 1389            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1390
 1391            gutter_hovered: false,
 1392            pixel_position_of_newest_cursor: None,
 1393            last_bounds: None,
 1394            last_position_map: None,
 1395            expect_bounds_change: None,
 1396            gutter_dimensions: GutterDimensions::default(),
 1397            style: None,
 1398            show_cursor_names: false,
 1399            hovered_cursors: Default::default(),
 1400            next_editor_action_id: EditorActionId::default(),
 1401            editor_actions: Rc::default(),
 1402            show_inline_completions_override: None,
 1403            show_inline_completions: true,
 1404            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1405            custom_context_menu: None,
 1406            show_git_blame_gutter: false,
 1407            show_git_blame_inline: false,
 1408            show_selection_menu: None,
 1409            show_git_blame_inline_delay_task: None,
 1410            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1411            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1412                .session
 1413                .restore_unsaved_buffers,
 1414            blame: None,
 1415            blame_subscription: None,
 1416            tasks: Default::default(),
 1417            _subscriptions: vec![
 1418                cx.observe(&buffer, Self::on_buffer_changed),
 1419                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1420                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1421                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1422                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1423                cx.observe_window_activation(window, |editor, window, cx| {
 1424                    let active = window.is_window_active();
 1425                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1426                        if active {
 1427                            blink_manager.enable(cx);
 1428                        } else {
 1429                            blink_manager.disable(cx);
 1430                        }
 1431                    });
 1432                }),
 1433            ],
 1434            tasks_update_task: None,
 1435            linked_edit_ranges: Default::default(),
 1436            in_project_search: false,
 1437            previous_search_ranges: None,
 1438            breadcrumb_header: None,
 1439            focused_block: None,
 1440            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1441            addons: HashMap::default(),
 1442            registered_buffers: HashMap::default(),
 1443            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1444            selection_mark_mode: false,
 1445            toggle_fold_multiple_buffers: Task::ready(()),
 1446            text_style_refinement: None,
 1447        };
 1448        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1449        this._subscriptions.extend(project_subscriptions);
 1450
 1451        this.end_selection(window, cx);
 1452        this.scroll_manager.show_scrollbar(window, cx);
 1453
 1454        if mode == EditorMode::Full {
 1455            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1456            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1457
 1458            if this.git_blame_inline_enabled {
 1459                this.git_blame_inline_enabled = true;
 1460                this.start_git_blame_inline(false, window, cx);
 1461            }
 1462
 1463            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1464                if let Some(project) = this.project.as_ref() {
 1465                    let lsp_store = project.read(cx).lsp_store();
 1466                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1467                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1468                    });
 1469                    this.registered_buffers
 1470                        .insert(buffer.read(cx).remote_id(), handle);
 1471                }
 1472            }
 1473        }
 1474
 1475        this.report_editor_event("Editor Opened", None, cx);
 1476        this
 1477    }
 1478
 1479    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1480        self.mouse_context_menu
 1481            .as_ref()
 1482            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1483    }
 1484
 1485    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1486        let mut key_context = KeyContext::new_with_defaults();
 1487        key_context.add("Editor");
 1488        let mode = match self.mode {
 1489            EditorMode::SingleLine { .. } => "single_line",
 1490            EditorMode::AutoHeight { .. } => "auto_height",
 1491            EditorMode::Full => "full",
 1492        };
 1493
 1494        if EditorSettings::jupyter_enabled(cx) {
 1495            key_context.add("jupyter");
 1496        }
 1497
 1498        key_context.set("mode", mode);
 1499        if self.pending_rename.is_some() {
 1500            key_context.add("renaming");
 1501        }
 1502        match self.context_menu.borrow().as_ref() {
 1503            Some(CodeContextMenu::Completions(_)) => {
 1504                key_context.add("menu");
 1505                key_context.add("showing_completions");
 1506            }
 1507            Some(CodeContextMenu::CodeActions(_)) => {
 1508                key_context.add("menu");
 1509                key_context.add("showing_code_actions")
 1510            }
 1511            None => {}
 1512        }
 1513
 1514        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1515        if !self.focus_handle(cx).contains_focused(window, cx)
 1516            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1517        {
 1518            for addon in self.addons.values() {
 1519                addon.extend_key_context(&mut key_context, cx)
 1520            }
 1521        }
 1522
 1523        if let Some(extension) = self
 1524            .buffer
 1525            .read(cx)
 1526            .as_singleton()
 1527            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1528        {
 1529            key_context.set("extension", extension.to_string());
 1530        }
 1531
 1532        if self.has_active_inline_completion() {
 1533            key_context.add("copilot_suggestion");
 1534            key_context.add("inline_completion");
 1535        }
 1536
 1537        if self.selection_mark_mode {
 1538            key_context.add("selection_mode");
 1539        }
 1540
 1541        key_context
 1542    }
 1543
 1544    pub fn new_file(
 1545        workspace: &mut Workspace,
 1546        _: &workspace::NewFile,
 1547        window: &mut Window,
 1548        cx: &mut Context<Workspace>,
 1549    ) {
 1550        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1551            "Failed to create buffer",
 1552            window,
 1553            cx,
 1554            |e, _, _| match e.error_code() {
 1555                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1556                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1557                e.error_tag("required").unwrap_or("the latest version")
 1558            )),
 1559                _ => None,
 1560            },
 1561        );
 1562    }
 1563
 1564    pub fn new_in_workspace(
 1565        workspace: &mut Workspace,
 1566        window: &mut Window,
 1567        cx: &mut Context<Workspace>,
 1568    ) -> Task<Result<Entity<Editor>>> {
 1569        let project = workspace.project().clone();
 1570        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1571
 1572        cx.spawn_in(window, |workspace, mut cx| async move {
 1573            let buffer = create.await?;
 1574            workspace.update_in(&mut cx, |workspace, window, cx| {
 1575                let editor =
 1576                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1577                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1578                editor
 1579            })
 1580        })
 1581    }
 1582
 1583    fn new_file_vertical(
 1584        workspace: &mut Workspace,
 1585        _: &workspace::NewFileSplitVertical,
 1586        window: &mut Window,
 1587        cx: &mut Context<Workspace>,
 1588    ) {
 1589        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1590    }
 1591
 1592    fn new_file_horizontal(
 1593        workspace: &mut Workspace,
 1594        _: &workspace::NewFileSplitHorizontal,
 1595        window: &mut Window,
 1596        cx: &mut Context<Workspace>,
 1597    ) {
 1598        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1599    }
 1600
 1601    fn new_file_in_direction(
 1602        workspace: &mut Workspace,
 1603        direction: SplitDirection,
 1604        window: &mut Window,
 1605        cx: &mut Context<Workspace>,
 1606    ) {
 1607        let project = workspace.project().clone();
 1608        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1609
 1610        cx.spawn_in(window, |workspace, mut cx| async move {
 1611            let buffer = create.await?;
 1612            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1613                workspace.split_item(
 1614                    direction,
 1615                    Box::new(
 1616                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1617                    ),
 1618                    window,
 1619                    cx,
 1620                )
 1621            })?;
 1622            anyhow::Ok(())
 1623        })
 1624        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1625            match e.error_code() {
 1626                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1627                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1628                e.error_tag("required").unwrap_or("the latest version")
 1629            )),
 1630                _ => None,
 1631            }
 1632        });
 1633    }
 1634
 1635    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1636        self.leader_peer_id
 1637    }
 1638
 1639    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1640        &self.buffer
 1641    }
 1642
 1643    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1644        self.workspace.as_ref()?.0.upgrade()
 1645    }
 1646
 1647    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1648        self.buffer().read(cx).title(cx)
 1649    }
 1650
 1651    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1652        let git_blame_gutter_max_author_length = self
 1653            .render_git_blame_gutter(cx)
 1654            .then(|| {
 1655                if let Some(blame) = self.blame.as_ref() {
 1656                    let max_author_length =
 1657                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1658                    Some(max_author_length)
 1659                } else {
 1660                    None
 1661                }
 1662            })
 1663            .flatten();
 1664
 1665        EditorSnapshot {
 1666            mode: self.mode,
 1667            show_gutter: self.show_gutter,
 1668            show_line_numbers: self.show_line_numbers,
 1669            show_git_diff_gutter: self.show_git_diff_gutter,
 1670            show_code_actions: self.show_code_actions,
 1671            show_runnables: self.show_runnables,
 1672            git_blame_gutter_max_author_length,
 1673            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1674            scroll_anchor: self.scroll_manager.anchor(),
 1675            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1676            placeholder_text: self.placeholder_text.clone(),
 1677            is_focused: self.focus_handle.is_focused(window),
 1678            current_line_highlight: self
 1679                .current_line_highlight
 1680                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1681            gutter_hovered: self.gutter_hovered,
 1682        }
 1683    }
 1684
 1685    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1686        self.buffer.read(cx).language_at(point, cx)
 1687    }
 1688
 1689    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1690        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1691    }
 1692
 1693    pub fn active_excerpt(
 1694        &self,
 1695        cx: &App,
 1696    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1697        self.buffer
 1698            .read(cx)
 1699            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1700    }
 1701
 1702    pub fn mode(&self) -> EditorMode {
 1703        self.mode
 1704    }
 1705
 1706    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1707        self.collaboration_hub.as_deref()
 1708    }
 1709
 1710    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1711        self.collaboration_hub = Some(hub);
 1712    }
 1713
 1714    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1715        self.in_project_search = in_project_search;
 1716    }
 1717
 1718    pub fn set_custom_context_menu(
 1719        &mut self,
 1720        f: impl 'static
 1721            + Fn(
 1722                &mut Self,
 1723                DisplayPoint,
 1724                &mut Window,
 1725                &mut Context<Self>,
 1726            ) -> Option<Entity<ui::ContextMenu>>,
 1727    ) {
 1728        self.custom_context_menu = Some(Box::new(f))
 1729    }
 1730
 1731    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1732        self.completion_provider = provider;
 1733    }
 1734
 1735    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1736        self.semantics_provider.clone()
 1737    }
 1738
 1739    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1740        self.semantics_provider = provider;
 1741    }
 1742
 1743    pub fn set_inline_completion_provider<T>(
 1744        &mut self,
 1745        provider: Option<Entity<T>>,
 1746        window: &mut Window,
 1747        cx: &mut Context<Self>,
 1748    ) where
 1749        T: InlineCompletionProvider,
 1750    {
 1751        self.inline_completion_provider =
 1752            provider.map(|provider| RegisteredInlineCompletionProvider {
 1753                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1754                    if this.focus_handle.is_focused(window) {
 1755                        this.update_visible_inline_completion(window, cx);
 1756                    }
 1757                }),
 1758                provider: Arc::new(provider),
 1759            });
 1760        self.refresh_inline_completion(false, false, window, cx);
 1761    }
 1762
 1763    pub fn placeholder_text(&self) -> Option<&str> {
 1764        self.placeholder_text.as_deref()
 1765    }
 1766
 1767    pub fn set_placeholder_text(
 1768        &mut self,
 1769        placeholder_text: impl Into<Arc<str>>,
 1770        cx: &mut Context<Self>,
 1771    ) {
 1772        let placeholder_text = Some(placeholder_text.into());
 1773        if self.placeholder_text != placeholder_text {
 1774            self.placeholder_text = placeholder_text;
 1775            cx.notify();
 1776        }
 1777    }
 1778
 1779    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1780        self.cursor_shape = cursor_shape;
 1781
 1782        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1783        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1784
 1785        cx.notify();
 1786    }
 1787
 1788    pub fn set_current_line_highlight(
 1789        &mut self,
 1790        current_line_highlight: Option<CurrentLineHighlight>,
 1791    ) {
 1792        self.current_line_highlight = current_line_highlight;
 1793    }
 1794
 1795    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1796        self.collapse_matches = collapse_matches;
 1797    }
 1798
 1799    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1800        let buffers = self.buffer.read(cx).all_buffers();
 1801        let Some(lsp_store) = self.lsp_store(cx) else {
 1802            return;
 1803        };
 1804        lsp_store.update(cx, |lsp_store, cx| {
 1805            for buffer in buffers {
 1806                self.registered_buffers
 1807                    .entry(buffer.read(cx).remote_id())
 1808                    .or_insert_with(|| {
 1809                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1810                    });
 1811            }
 1812        })
 1813    }
 1814
 1815    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1816        if self.collapse_matches {
 1817            return range.start..range.start;
 1818        }
 1819        range.clone()
 1820    }
 1821
 1822    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1823        if self.display_map.read(cx).clip_at_line_ends != clip {
 1824            self.display_map
 1825                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1826        }
 1827    }
 1828
 1829    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1830        self.input_enabled = input_enabled;
 1831    }
 1832
 1833    pub fn set_show_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1834        self.show_inline_completions = enabled;
 1835        if !self.show_inline_completions {
 1836            self.take_active_inline_completion(cx);
 1837            cx.notify();
 1838        }
 1839    }
 1840
 1841    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1842        self.menu_inline_completions_policy = value;
 1843    }
 1844
 1845    pub fn set_autoindent(&mut self, autoindent: bool) {
 1846        if autoindent {
 1847            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1848        } else {
 1849            self.autoindent_mode = None;
 1850        }
 1851    }
 1852
 1853    pub fn read_only(&self, cx: &App) -> bool {
 1854        self.read_only || self.buffer.read(cx).read_only()
 1855    }
 1856
 1857    pub fn set_read_only(&mut self, read_only: bool) {
 1858        self.read_only = read_only;
 1859    }
 1860
 1861    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1862        self.use_autoclose = autoclose;
 1863    }
 1864
 1865    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1866        self.use_auto_surround = auto_surround;
 1867    }
 1868
 1869    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1870        self.auto_replace_emoji_shortcode = auto_replace;
 1871    }
 1872
 1873    pub fn toggle_inline_completions(
 1874        &mut self,
 1875        _: &ToggleInlineCompletions,
 1876        window: &mut Window,
 1877        cx: &mut Context<Self>,
 1878    ) {
 1879        if self.show_inline_completions_override.is_some() {
 1880            self.set_show_inline_completions(None, window, cx);
 1881        } else {
 1882            let cursor = self.selections.newest_anchor().head();
 1883            if let Some((buffer, cursor_buffer_position)) =
 1884                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1885            {
 1886                let show_inline_completions = !self.should_show_inline_completions_in_buffer(
 1887                    &buffer,
 1888                    cursor_buffer_position,
 1889                    cx,
 1890                );
 1891                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1892            }
 1893        }
 1894    }
 1895
 1896    pub fn set_show_inline_completions(
 1897        &mut self,
 1898        show_inline_completions: Option<bool>,
 1899        window: &mut Window,
 1900        cx: &mut Context<Self>,
 1901    ) {
 1902        self.show_inline_completions_override = show_inline_completions;
 1903        self.refresh_inline_completion(false, true, window, cx);
 1904    }
 1905
 1906    fn inline_completions_disabled_in_scope(
 1907        &self,
 1908        buffer: &Entity<Buffer>,
 1909        buffer_position: language::Anchor,
 1910        cx: &App,
 1911    ) -> bool {
 1912        let snapshot = buffer.read(cx).snapshot();
 1913        let settings = snapshot.settings_at(buffer_position, cx);
 1914
 1915        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1916            return false;
 1917        };
 1918
 1919        scope.override_name().map_or(false, |scope_name| {
 1920            settings
 1921                .inline_completions_disabled_in
 1922                .iter()
 1923                .any(|s| s == scope_name)
 1924        })
 1925    }
 1926
 1927    pub fn set_use_modal_editing(&mut self, to: bool) {
 1928        self.use_modal_editing = to;
 1929    }
 1930
 1931    pub fn use_modal_editing(&self) -> bool {
 1932        self.use_modal_editing
 1933    }
 1934
 1935    fn selections_did_change(
 1936        &mut self,
 1937        local: bool,
 1938        old_cursor_position: &Anchor,
 1939        show_completions: bool,
 1940        window: &mut Window,
 1941        cx: &mut Context<Self>,
 1942    ) {
 1943        window.invalidate_character_coordinates();
 1944
 1945        // Copy selections to primary selection buffer
 1946        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1947        if local {
 1948            let selections = self.selections.all::<usize>(cx);
 1949            let buffer_handle = self.buffer.read(cx).read(cx);
 1950
 1951            let mut text = String::new();
 1952            for (index, selection) in selections.iter().enumerate() {
 1953                let text_for_selection = buffer_handle
 1954                    .text_for_range(selection.start..selection.end)
 1955                    .collect::<String>();
 1956
 1957                text.push_str(&text_for_selection);
 1958                if index != selections.len() - 1 {
 1959                    text.push('\n');
 1960                }
 1961            }
 1962
 1963            if !text.is_empty() {
 1964                cx.write_to_primary(ClipboardItem::new_string(text));
 1965            }
 1966        }
 1967
 1968        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1969            self.buffer.update(cx, |buffer, cx| {
 1970                buffer.set_active_selections(
 1971                    &self.selections.disjoint_anchors(),
 1972                    self.selections.line_mode,
 1973                    self.cursor_shape,
 1974                    cx,
 1975                )
 1976            });
 1977        }
 1978        let display_map = self
 1979            .display_map
 1980            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1981        let buffer = &display_map.buffer_snapshot;
 1982        self.add_selections_state = None;
 1983        self.select_next_state = None;
 1984        self.select_prev_state = None;
 1985        self.select_larger_syntax_node_stack.clear();
 1986        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1987        self.snippet_stack
 1988            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1989        self.take_rename(false, window, cx);
 1990
 1991        let new_cursor_position = self.selections.newest_anchor().head();
 1992
 1993        self.push_to_nav_history(
 1994            *old_cursor_position,
 1995            Some(new_cursor_position.to_point(buffer)),
 1996            cx,
 1997        );
 1998
 1999        if local {
 2000            let new_cursor_position = self.selections.newest_anchor().head();
 2001            let mut context_menu = self.context_menu.borrow_mut();
 2002            let completion_menu = match context_menu.as_ref() {
 2003                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2004                _ => {
 2005                    *context_menu = None;
 2006                    None
 2007                }
 2008            };
 2009
 2010            if let Some(completion_menu) = completion_menu {
 2011                let cursor_position = new_cursor_position.to_offset(buffer);
 2012                let (word_range, kind) =
 2013                    buffer.surrounding_word(completion_menu.initial_position, true);
 2014                if kind == Some(CharKind::Word)
 2015                    && word_range.to_inclusive().contains(&cursor_position)
 2016                {
 2017                    let mut completion_menu = completion_menu.clone();
 2018                    drop(context_menu);
 2019
 2020                    let query = Self::completion_query(buffer, cursor_position);
 2021                    cx.spawn(move |this, mut cx| async move {
 2022                        completion_menu
 2023                            .filter(query.as_deref(), cx.background_executor().clone())
 2024                            .await;
 2025
 2026                        this.update(&mut cx, |this, cx| {
 2027                            let mut context_menu = this.context_menu.borrow_mut();
 2028                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2029                            else {
 2030                                return;
 2031                            };
 2032
 2033                            if menu.id > completion_menu.id {
 2034                                return;
 2035                            }
 2036
 2037                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2038                            drop(context_menu);
 2039                            cx.notify();
 2040                        })
 2041                    })
 2042                    .detach();
 2043
 2044                    if show_completions {
 2045                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2046                    }
 2047                } else {
 2048                    drop(context_menu);
 2049                    self.hide_context_menu(window, cx);
 2050                }
 2051            } else {
 2052                drop(context_menu);
 2053            }
 2054
 2055            hide_hover(self, cx);
 2056
 2057            if old_cursor_position.to_display_point(&display_map).row()
 2058                != new_cursor_position.to_display_point(&display_map).row()
 2059            {
 2060                self.available_code_actions.take();
 2061            }
 2062            self.refresh_code_actions(window, cx);
 2063            self.refresh_document_highlights(cx);
 2064            refresh_matching_bracket_highlights(self, window, cx);
 2065            self.update_visible_inline_completion(window, cx);
 2066            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2067            if self.git_blame_inline_enabled {
 2068                self.start_inline_blame_timer(window, cx);
 2069            }
 2070        }
 2071
 2072        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2073        cx.emit(EditorEvent::SelectionsChanged { local });
 2074
 2075        if self.selections.disjoint_anchors().len() == 1 {
 2076            cx.emit(SearchEvent::ActiveMatchChanged)
 2077        }
 2078        cx.notify();
 2079    }
 2080
 2081    pub fn change_selections<R>(
 2082        &mut self,
 2083        autoscroll: Option<Autoscroll>,
 2084        window: &mut Window,
 2085        cx: &mut Context<Self>,
 2086        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2087    ) -> R {
 2088        self.change_selections_inner(autoscroll, true, window, cx, change)
 2089    }
 2090
 2091    pub fn change_selections_inner<R>(
 2092        &mut self,
 2093        autoscroll: Option<Autoscroll>,
 2094        request_completions: bool,
 2095        window: &mut Window,
 2096        cx: &mut Context<Self>,
 2097        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2098    ) -> R {
 2099        let old_cursor_position = self.selections.newest_anchor().head();
 2100        self.push_to_selection_history();
 2101
 2102        let (changed, result) = self.selections.change_with(cx, change);
 2103
 2104        if changed {
 2105            if let Some(autoscroll) = autoscroll {
 2106                self.request_autoscroll(autoscroll, cx);
 2107            }
 2108            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2109
 2110            if self.should_open_signature_help_automatically(
 2111                &old_cursor_position,
 2112                self.signature_help_state.backspace_pressed(),
 2113                cx,
 2114            ) {
 2115                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2116            }
 2117            self.signature_help_state.set_backspace_pressed(false);
 2118        }
 2119
 2120        result
 2121    }
 2122
 2123    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2124    where
 2125        I: IntoIterator<Item = (Range<S>, T)>,
 2126        S: ToOffset,
 2127        T: Into<Arc<str>>,
 2128    {
 2129        if self.read_only(cx) {
 2130            return;
 2131        }
 2132
 2133        self.buffer
 2134            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2135    }
 2136
 2137    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2138    where
 2139        I: IntoIterator<Item = (Range<S>, T)>,
 2140        S: ToOffset,
 2141        T: Into<Arc<str>>,
 2142    {
 2143        if self.read_only(cx) {
 2144            return;
 2145        }
 2146
 2147        self.buffer.update(cx, |buffer, cx| {
 2148            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2149        });
 2150    }
 2151
 2152    pub fn edit_with_block_indent<I, S, T>(
 2153        &mut self,
 2154        edits: I,
 2155        original_indent_columns: Vec<u32>,
 2156        cx: &mut Context<Self>,
 2157    ) where
 2158        I: IntoIterator<Item = (Range<S>, T)>,
 2159        S: ToOffset,
 2160        T: Into<Arc<str>>,
 2161    {
 2162        if self.read_only(cx) {
 2163            return;
 2164        }
 2165
 2166        self.buffer.update(cx, |buffer, cx| {
 2167            buffer.edit(
 2168                edits,
 2169                Some(AutoindentMode::Block {
 2170                    original_indent_columns,
 2171                }),
 2172                cx,
 2173            )
 2174        });
 2175    }
 2176
 2177    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2178        self.hide_context_menu(window, cx);
 2179
 2180        match phase {
 2181            SelectPhase::Begin {
 2182                position,
 2183                add,
 2184                click_count,
 2185            } => self.begin_selection(position, add, click_count, window, cx),
 2186            SelectPhase::BeginColumnar {
 2187                position,
 2188                goal_column,
 2189                reset,
 2190            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2191            SelectPhase::Extend {
 2192                position,
 2193                click_count,
 2194            } => self.extend_selection(position, click_count, window, cx),
 2195            SelectPhase::Update {
 2196                position,
 2197                goal_column,
 2198                scroll_delta,
 2199            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2200            SelectPhase::End => self.end_selection(window, cx),
 2201        }
 2202    }
 2203
 2204    fn extend_selection(
 2205        &mut self,
 2206        position: DisplayPoint,
 2207        click_count: usize,
 2208        window: &mut Window,
 2209        cx: &mut Context<Self>,
 2210    ) {
 2211        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2212        let tail = self.selections.newest::<usize>(cx).tail();
 2213        self.begin_selection(position, false, click_count, window, cx);
 2214
 2215        let position = position.to_offset(&display_map, Bias::Left);
 2216        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2217
 2218        let mut pending_selection = self
 2219            .selections
 2220            .pending_anchor()
 2221            .expect("extend_selection not called with pending selection");
 2222        if position >= tail {
 2223            pending_selection.start = tail_anchor;
 2224        } else {
 2225            pending_selection.end = tail_anchor;
 2226            pending_selection.reversed = true;
 2227        }
 2228
 2229        let mut pending_mode = self.selections.pending_mode().unwrap();
 2230        match &mut pending_mode {
 2231            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2232            _ => {}
 2233        }
 2234
 2235        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2236            s.set_pending(pending_selection, pending_mode)
 2237        });
 2238    }
 2239
 2240    fn begin_selection(
 2241        &mut self,
 2242        position: DisplayPoint,
 2243        add: bool,
 2244        click_count: usize,
 2245        window: &mut Window,
 2246        cx: &mut Context<Self>,
 2247    ) {
 2248        if !self.focus_handle.is_focused(window) {
 2249            self.last_focused_descendant = None;
 2250            window.focus(&self.focus_handle);
 2251        }
 2252
 2253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2254        let buffer = &display_map.buffer_snapshot;
 2255        let newest_selection = self.selections.newest_anchor().clone();
 2256        let position = display_map.clip_point(position, Bias::Left);
 2257
 2258        let start;
 2259        let end;
 2260        let mode;
 2261        let mut auto_scroll;
 2262        match click_count {
 2263            1 => {
 2264                start = buffer.anchor_before(position.to_point(&display_map));
 2265                end = start;
 2266                mode = SelectMode::Character;
 2267                auto_scroll = true;
 2268            }
 2269            2 => {
 2270                let range = movement::surrounding_word(&display_map, position);
 2271                start = buffer.anchor_before(range.start.to_point(&display_map));
 2272                end = buffer.anchor_before(range.end.to_point(&display_map));
 2273                mode = SelectMode::Word(start..end);
 2274                auto_scroll = true;
 2275            }
 2276            3 => {
 2277                let position = display_map
 2278                    .clip_point(position, Bias::Left)
 2279                    .to_point(&display_map);
 2280                let line_start = display_map.prev_line_boundary(position).0;
 2281                let next_line_start = buffer.clip_point(
 2282                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2283                    Bias::Left,
 2284                );
 2285                start = buffer.anchor_before(line_start);
 2286                end = buffer.anchor_before(next_line_start);
 2287                mode = SelectMode::Line(start..end);
 2288                auto_scroll = true;
 2289            }
 2290            _ => {
 2291                start = buffer.anchor_before(0);
 2292                end = buffer.anchor_before(buffer.len());
 2293                mode = SelectMode::All;
 2294                auto_scroll = false;
 2295            }
 2296        }
 2297        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2298
 2299        let point_to_delete: Option<usize> = {
 2300            let selected_points: Vec<Selection<Point>> =
 2301                self.selections.disjoint_in_range(start..end, cx);
 2302
 2303            if !add || click_count > 1 {
 2304                None
 2305            } else if !selected_points.is_empty() {
 2306                Some(selected_points[0].id)
 2307            } else {
 2308                let clicked_point_already_selected =
 2309                    self.selections.disjoint.iter().find(|selection| {
 2310                        selection.start.to_point(buffer) == start.to_point(buffer)
 2311                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2312                    });
 2313
 2314                clicked_point_already_selected.map(|selection| selection.id)
 2315            }
 2316        };
 2317
 2318        let selections_count = self.selections.count();
 2319
 2320        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2321            if let Some(point_to_delete) = point_to_delete {
 2322                s.delete(point_to_delete);
 2323
 2324                if selections_count == 1 {
 2325                    s.set_pending_anchor_range(start..end, mode);
 2326                }
 2327            } else {
 2328                if !add {
 2329                    s.clear_disjoint();
 2330                } else if click_count > 1 {
 2331                    s.delete(newest_selection.id)
 2332                }
 2333
 2334                s.set_pending_anchor_range(start..end, mode);
 2335            }
 2336        });
 2337    }
 2338
 2339    fn begin_columnar_selection(
 2340        &mut self,
 2341        position: DisplayPoint,
 2342        goal_column: u32,
 2343        reset: bool,
 2344        window: &mut Window,
 2345        cx: &mut Context<Self>,
 2346    ) {
 2347        if !self.focus_handle.is_focused(window) {
 2348            self.last_focused_descendant = None;
 2349            window.focus(&self.focus_handle);
 2350        }
 2351
 2352        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2353
 2354        if reset {
 2355            let pointer_position = display_map
 2356                .buffer_snapshot
 2357                .anchor_before(position.to_point(&display_map));
 2358
 2359            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2360                s.clear_disjoint();
 2361                s.set_pending_anchor_range(
 2362                    pointer_position..pointer_position,
 2363                    SelectMode::Character,
 2364                );
 2365            });
 2366        }
 2367
 2368        let tail = self.selections.newest::<Point>(cx).tail();
 2369        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2370
 2371        if !reset {
 2372            self.select_columns(
 2373                tail.to_display_point(&display_map),
 2374                position,
 2375                goal_column,
 2376                &display_map,
 2377                window,
 2378                cx,
 2379            );
 2380        }
 2381    }
 2382
 2383    fn update_selection(
 2384        &mut self,
 2385        position: DisplayPoint,
 2386        goal_column: u32,
 2387        scroll_delta: gpui::Point<f32>,
 2388        window: &mut Window,
 2389        cx: &mut Context<Self>,
 2390    ) {
 2391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2392
 2393        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2394            let tail = tail.to_display_point(&display_map);
 2395            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2396        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2397            let buffer = self.buffer.read(cx).snapshot(cx);
 2398            let head;
 2399            let tail;
 2400            let mode = self.selections.pending_mode().unwrap();
 2401            match &mode {
 2402                SelectMode::Character => {
 2403                    head = position.to_point(&display_map);
 2404                    tail = pending.tail().to_point(&buffer);
 2405                }
 2406                SelectMode::Word(original_range) => {
 2407                    let original_display_range = original_range.start.to_display_point(&display_map)
 2408                        ..original_range.end.to_display_point(&display_map);
 2409                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2410                        ..original_display_range.end.to_point(&display_map);
 2411                    if movement::is_inside_word(&display_map, position)
 2412                        || original_display_range.contains(&position)
 2413                    {
 2414                        let word_range = movement::surrounding_word(&display_map, position);
 2415                        if word_range.start < original_display_range.start {
 2416                            head = word_range.start.to_point(&display_map);
 2417                        } else {
 2418                            head = word_range.end.to_point(&display_map);
 2419                        }
 2420                    } else {
 2421                        head = position.to_point(&display_map);
 2422                    }
 2423
 2424                    if head <= original_buffer_range.start {
 2425                        tail = original_buffer_range.end;
 2426                    } else {
 2427                        tail = original_buffer_range.start;
 2428                    }
 2429                }
 2430                SelectMode::Line(original_range) => {
 2431                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2432
 2433                    let position = display_map
 2434                        .clip_point(position, Bias::Left)
 2435                        .to_point(&display_map);
 2436                    let line_start = display_map.prev_line_boundary(position).0;
 2437                    let next_line_start = buffer.clip_point(
 2438                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2439                        Bias::Left,
 2440                    );
 2441
 2442                    if line_start < original_range.start {
 2443                        head = line_start
 2444                    } else {
 2445                        head = next_line_start
 2446                    }
 2447
 2448                    if head <= original_range.start {
 2449                        tail = original_range.end;
 2450                    } else {
 2451                        tail = original_range.start;
 2452                    }
 2453                }
 2454                SelectMode::All => {
 2455                    return;
 2456                }
 2457            };
 2458
 2459            if head < tail {
 2460                pending.start = buffer.anchor_before(head);
 2461                pending.end = buffer.anchor_before(tail);
 2462                pending.reversed = true;
 2463            } else {
 2464                pending.start = buffer.anchor_before(tail);
 2465                pending.end = buffer.anchor_before(head);
 2466                pending.reversed = false;
 2467            }
 2468
 2469            self.change_selections(None, window, cx, |s| {
 2470                s.set_pending(pending, mode);
 2471            });
 2472        } else {
 2473            log::error!("update_selection dispatched with no pending selection");
 2474            return;
 2475        }
 2476
 2477        self.apply_scroll_delta(scroll_delta, window, cx);
 2478        cx.notify();
 2479    }
 2480
 2481    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2482        self.columnar_selection_tail.take();
 2483        if self.selections.pending_anchor().is_some() {
 2484            let selections = self.selections.all::<usize>(cx);
 2485            self.change_selections(None, window, cx, |s| {
 2486                s.select(selections);
 2487                s.clear_pending();
 2488            });
 2489        }
 2490    }
 2491
 2492    fn select_columns(
 2493        &mut self,
 2494        tail: DisplayPoint,
 2495        head: DisplayPoint,
 2496        goal_column: u32,
 2497        display_map: &DisplaySnapshot,
 2498        window: &mut Window,
 2499        cx: &mut Context<Self>,
 2500    ) {
 2501        let start_row = cmp::min(tail.row(), head.row());
 2502        let end_row = cmp::max(tail.row(), head.row());
 2503        let start_column = cmp::min(tail.column(), goal_column);
 2504        let end_column = cmp::max(tail.column(), goal_column);
 2505        let reversed = start_column < tail.column();
 2506
 2507        let selection_ranges = (start_row.0..=end_row.0)
 2508            .map(DisplayRow)
 2509            .filter_map(|row| {
 2510                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2511                    let start = display_map
 2512                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2513                        .to_point(display_map);
 2514                    let end = display_map
 2515                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2516                        .to_point(display_map);
 2517                    if reversed {
 2518                        Some(end..start)
 2519                    } else {
 2520                        Some(start..end)
 2521                    }
 2522                } else {
 2523                    None
 2524                }
 2525            })
 2526            .collect::<Vec<_>>();
 2527
 2528        self.change_selections(None, window, cx, |s| {
 2529            s.select_ranges(selection_ranges);
 2530        });
 2531        cx.notify();
 2532    }
 2533
 2534    pub fn has_pending_nonempty_selection(&self) -> bool {
 2535        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2536            Some(Selection { start, end, .. }) => start != end,
 2537            None => false,
 2538        };
 2539
 2540        pending_nonempty_selection
 2541            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2542    }
 2543
 2544    pub fn has_pending_selection(&self) -> bool {
 2545        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2546    }
 2547
 2548    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2549        self.selection_mark_mode = false;
 2550
 2551        if self.clear_expanded_diff_hunks(cx) {
 2552            cx.notify();
 2553            return;
 2554        }
 2555        if self.dismiss_menus_and_popups(true, window, cx) {
 2556            return;
 2557        }
 2558
 2559        if self.mode == EditorMode::Full
 2560            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2561        {
 2562            return;
 2563        }
 2564
 2565        cx.propagate();
 2566    }
 2567
 2568    pub fn dismiss_menus_and_popups(
 2569        &mut self,
 2570        should_report_inline_completion_event: bool,
 2571        window: &mut Window,
 2572        cx: &mut Context<Self>,
 2573    ) -> bool {
 2574        if self.take_rename(false, window, cx).is_some() {
 2575            return true;
 2576        }
 2577
 2578        if hide_hover(self, cx) {
 2579            return true;
 2580        }
 2581
 2582        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2583            return true;
 2584        }
 2585
 2586        if self.hide_context_menu(window, cx).is_some() {
 2587            return true;
 2588        }
 2589
 2590        if self.mouse_context_menu.take().is_some() {
 2591            return true;
 2592        }
 2593
 2594        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2595            return true;
 2596        }
 2597
 2598        if self.snippet_stack.pop().is_some() {
 2599            return true;
 2600        }
 2601
 2602        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2603            self.dismiss_diagnostics(cx);
 2604            return true;
 2605        }
 2606
 2607        false
 2608    }
 2609
 2610    fn linked_editing_ranges_for(
 2611        &self,
 2612        selection: Range<text::Anchor>,
 2613        cx: &App,
 2614    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2615        if self.linked_edit_ranges.is_empty() {
 2616            return None;
 2617        }
 2618        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2619            selection.end.buffer_id.and_then(|end_buffer_id| {
 2620                if selection.start.buffer_id != Some(end_buffer_id) {
 2621                    return None;
 2622                }
 2623                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2624                let snapshot = buffer.read(cx).snapshot();
 2625                self.linked_edit_ranges
 2626                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2627                    .map(|ranges| (ranges, snapshot, buffer))
 2628            })?;
 2629        use text::ToOffset as TO;
 2630        // find offset from the start of current range to current cursor position
 2631        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2632
 2633        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2634        let start_difference = start_offset - start_byte_offset;
 2635        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2636        let end_difference = end_offset - start_byte_offset;
 2637        // Current range has associated linked ranges.
 2638        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2639        for range in linked_ranges.iter() {
 2640            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2641            let end_offset = start_offset + end_difference;
 2642            let start_offset = start_offset + start_difference;
 2643            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2644                continue;
 2645            }
 2646            if self.selections.disjoint_anchor_ranges().any(|s| {
 2647                if s.start.buffer_id != selection.start.buffer_id
 2648                    || s.end.buffer_id != selection.end.buffer_id
 2649                {
 2650                    return false;
 2651                }
 2652                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2653                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2654            }) {
 2655                continue;
 2656            }
 2657            let start = buffer_snapshot.anchor_after(start_offset);
 2658            let end = buffer_snapshot.anchor_after(end_offset);
 2659            linked_edits
 2660                .entry(buffer.clone())
 2661                .or_default()
 2662                .push(start..end);
 2663        }
 2664        Some(linked_edits)
 2665    }
 2666
 2667    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2668        let text: Arc<str> = text.into();
 2669
 2670        if self.read_only(cx) {
 2671            return;
 2672        }
 2673
 2674        let selections = self.selections.all_adjusted(cx);
 2675        let mut bracket_inserted = false;
 2676        let mut edits = Vec::new();
 2677        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2678        let mut new_selections = Vec::with_capacity(selections.len());
 2679        let mut new_autoclose_regions = Vec::new();
 2680        let snapshot = self.buffer.read(cx).read(cx);
 2681
 2682        for (selection, autoclose_region) in
 2683            self.selections_with_autoclose_regions(selections, &snapshot)
 2684        {
 2685            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2686                // Determine if the inserted text matches the opening or closing
 2687                // bracket of any of this language's bracket pairs.
 2688                let mut bracket_pair = None;
 2689                let mut is_bracket_pair_start = false;
 2690                let mut is_bracket_pair_end = false;
 2691                if !text.is_empty() {
 2692                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2693                    //  and they are removing the character that triggered IME popup.
 2694                    for (pair, enabled) in scope.brackets() {
 2695                        if !pair.close && !pair.surround {
 2696                            continue;
 2697                        }
 2698
 2699                        if enabled && pair.start.ends_with(text.as_ref()) {
 2700                            let prefix_len = pair.start.len() - text.len();
 2701                            let preceding_text_matches_prefix = prefix_len == 0
 2702                                || (selection.start.column >= (prefix_len as u32)
 2703                                    && snapshot.contains_str_at(
 2704                                        Point::new(
 2705                                            selection.start.row,
 2706                                            selection.start.column - (prefix_len as u32),
 2707                                        ),
 2708                                        &pair.start[..prefix_len],
 2709                                    ));
 2710                            if preceding_text_matches_prefix {
 2711                                bracket_pair = Some(pair.clone());
 2712                                is_bracket_pair_start = true;
 2713                                break;
 2714                            }
 2715                        }
 2716                        if pair.end.as_str() == text.as_ref() {
 2717                            bracket_pair = Some(pair.clone());
 2718                            is_bracket_pair_end = true;
 2719                            break;
 2720                        }
 2721                    }
 2722                }
 2723
 2724                if let Some(bracket_pair) = bracket_pair {
 2725                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2726                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2727                    let auto_surround =
 2728                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2729                    if selection.is_empty() {
 2730                        if is_bracket_pair_start {
 2731                            // If the inserted text is a suffix of an opening bracket and the
 2732                            // selection is preceded by the rest of the opening bracket, then
 2733                            // insert the closing bracket.
 2734                            let following_text_allows_autoclose = snapshot
 2735                                .chars_at(selection.start)
 2736                                .next()
 2737                                .map_or(true, |c| scope.should_autoclose_before(c));
 2738
 2739                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2740                                && bracket_pair.start.len() == 1
 2741                            {
 2742                                let target = bracket_pair.start.chars().next().unwrap();
 2743                                let current_line_count = snapshot
 2744                                    .reversed_chars_at(selection.start)
 2745                                    .take_while(|&c| c != '\n')
 2746                                    .filter(|&c| c == target)
 2747                                    .count();
 2748                                current_line_count % 2 == 1
 2749                            } else {
 2750                                false
 2751                            };
 2752
 2753                            if autoclose
 2754                                && bracket_pair.close
 2755                                && following_text_allows_autoclose
 2756                                && !is_closing_quote
 2757                            {
 2758                                let anchor = snapshot.anchor_before(selection.end);
 2759                                new_selections.push((selection.map(|_| anchor), text.len()));
 2760                                new_autoclose_regions.push((
 2761                                    anchor,
 2762                                    text.len(),
 2763                                    selection.id,
 2764                                    bracket_pair.clone(),
 2765                                ));
 2766                                edits.push((
 2767                                    selection.range(),
 2768                                    format!("{}{}", text, bracket_pair.end).into(),
 2769                                ));
 2770                                bracket_inserted = true;
 2771                                continue;
 2772                            }
 2773                        }
 2774
 2775                        if let Some(region) = autoclose_region {
 2776                            // If the selection is followed by an auto-inserted closing bracket,
 2777                            // then don't insert that closing bracket again; just move the selection
 2778                            // past the closing bracket.
 2779                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2780                                && text.as_ref() == region.pair.end.as_str();
 2781                            if should_skip {
 2782                                let anchor = snapshot.anchor_after(selection.end);
 2783                                new_selections
 2784                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2785                                continue;
 2786                            }
 2787                        }
 2788
 2789                        let always_treat_brackets_as_autoclosed = snapshot
 2790                            .settings_at(selection.start, cx)
 2791                            .always_treat_brackets_as_autoclosed;
 2792                        if always_treat_brackets_as_autoclosed
 2793                            && is_bracket_pair_end
 2794                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2795                        {
 2796                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2797                            // and the inserted text is a closing bracket and the selection is followed
 2798                            // by the closing bracket then move the selection past the closing bracket.
 2799                            let anchor = snapshot.anchor_after(selection.end);
 2800                            new_selections.push((selection.map(|_| anchor), text.len()));
 2801                            continue;
 2802                        }
 2803                    }
 2804                    // If an opening bracket is 1 character long and is typed while
 2805                    // text is selected, then surround that text with the bracket pair.
 2806                    else if auto_surround
 2807                        && bracket_pair.surround
 2808                        && is_bracket_pair_start
 2809                        && bracket_pair.start.chars().count() == 1
 2810                    {
 2811                        edits.push((selection.start..selection.start, text.clone()));
 2812                        edits.push((
 2813                            selection.end..selection.end,
 2814                            bracket_pair.end.as_str().into(),
 2815                        ));
 2816                        bracket_inserted = true;
 2817                        new_selections.push((
 2818                            Selection {
 2819                                id: selection.id,
 2820                                start: snapshot.anchor_after(selection.start),
 2821                                end: snapshot.anchor_before(selection.end),
 2822                                reversed: selection.reversed,
 2823                                goal: selection.goal,
 2824                            },
 2825                            0,
 2826                        ));
 2827                        continue;
 2828                    }
 2829                }
 2830            }
 2831
 2832            if self.auto_replace_emoji_shortcode
 2833                && selection.is_empty()
 2834                && text.as_ref().ends_with(':')
 2835            {
 2836                if let Some(possible_emoji_short_code) =
 2837                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2838                {
 2839                    if !possible_emoji_short_code.is_empty() {
 2840                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2841                            let emoji_shortcode_start = Point::new(
 2842                                selection.start.row,
 2843                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2844                            );
 2845
 2846                            // Remove shortcode from buffer
 2847                            edits.push((
 2848                                emoji_shortcode_start..selection.start,
 2849                                "".to_string().into(),
 2850                            ));
 2851                            new_selections.push((
 2852                                Selection {
 2853                                    id: selection.id,
 2854                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2855                                    end: snapshot.anchor_before(selection.start),
 2856                                    reversed: selection.reversed,
 2857                                    goal: selection.goal,
 2858                                },
 2859                                0,
 2860                            ));
 2861
 2862                            // Insert emoji
 2863                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2864                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2865                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2866
 2867                            continue;
 2868                        }
 2869                    }
 2870                }
 2871            }
 2872
 2873            // If not handling any auto-close operation, then just replace the selected
 2874            // text with the given input and move the selection to the end of the
 2875            // newly inserted text.
 2876            let anchor = snapshot.anchor_after(selection.end);
 2877            if !self.linked_edit_ranges.is_empty() {
 2878                let start_anchor = snapshot.anchor_before(selection.start);
 2879
 2880                let is_word_char = text.chars().next().map_or(true, |char| {
 2881                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2882                    classifier.is_word(char)
 2883                });
 2884
 2885                if is_word_char {
 2886                    if let Some(ranges) = self
 2887                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2888                    {
 2889                        for (buffer, edits) in ranges {
 2890                            linked_edits
 2891                                .entry(buffer.clone())
 2892                                .or_default()
 2893                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2894                        }
 2895                    }
 2896                }
 2897            }
 2898
 2899            new_selections.push((selection.map(|_| anchor), 0));
 2900            edits.push((selection.start..selection.end, text.clone()));
 2901        }
 2902
 2903        drop(snapshot);
 2904
 2905        self.transact(window, cx, |this, window, cx| {
 2906            this.buffer.update(cx, |buffer, cx| {
 2907                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2908            });
 2909            for (buffer, edits) in linked_edits {
 2910                buffer.update(cx, |buffer, cx| {
 2911                    let snapshot = buffer.snapshot();
 2912                    let edits = edits
 2913                        .into_iter()
 2914                        .map(|(range, text)| {
 2915                            use text::ToPoint as TP;
 2916                            let end_point = TP::to_point(&range.end, &snapshot);
 2917                            let start_point = TP::to_point(&range.start, &snapshot);
 2918                            (start_point..end_point, text)
 2919                        })
 2920                        .sorted_by_key(|(range, _)| range.start)
 2921                        .collect::<Vec<_>>();
 2922                    buffer.edit(edits, None, cx);
 2923                })
 2924            }
 2925            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2926            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2927            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2928            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2929                .zip(new_selection_deltas)
 2930                .map(|(selection, delta)| Selection {
 2931                    id: selection.id,
 2932                    start: selection.start + delta,
 2933                    end: selection.end + delta,
 2934                    reversed: selection.reversed,
 2935                    goal: SelectionGoal::None,
 2936                })
 2937                .collect::<Vec<_>>();
 2938
 2939            let mut i = 0;
 2940            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2941                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2942                let start = map.buffer_snapshot.anchor_before(position);
 2943                let end = map.buffer_snapshot.anchor_after(position);
 2944                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2945                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2946                        Ordering::Less => i += 1,
 2947                        Ordering::Greater => break,
 2948                        Ordering::Equal => {
 2949                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2950                                Ordering::Less => i += 1,
 2951                                Ordering::Equal => break,
 2952                                Ordering::Greater => break,
 2953                            }
 2954                        }
 2955                    }
 2956                }
 2957                this.autoclose_regions.insert(
 2958                    i,
 2959                    AutocloseRegion {
 2960                        selection_id,
 2961                        range: start..end,
 2962                        pair,
 2963                    },
 2964                );
 2965            }
 2966
 2967            let had_active_inline_completion = this.has_active_inline_completion();
 2968            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2969                s.select(new_selections)
 2970            });
 2971
 2972            if !bracket_inserted {
 2973                if let Some(on_type_format_task) =
 2974                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2975                {
 2976                    on_type_format_task.detach_and_log_err(cx);
 2977                }
 2978            }
 2979
 2980            let editor_settings = EditorSettings::get_global(cx);
 2981            if bracket_inserted
 2982                && (editor_settings.auto_signature_help
 2983                    || editor_settings.show_signature_help_after_edits)
 2984            {
 2985                this.show_signature_help(&ShowSignatureHelp, window, cx);
 2986            }
 2987
 2988            let trigger_in_words =
 2989                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2990            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 2991            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 2992            this.refresh_inline_completion(true, false, window, cx);
 2993        });
 2994    }
 2995
 2996    fn find_possible_emoji_shortcode_at_position(
 2997        snapshot: &MultiBufferSnapshot,
 2998        position: Point,
 2999    ) -> Option<String> {
 3000        let mut chars = Vec::new();
 3001        let mut found_colon = false;
 3002        for char in snapshot.reversed_chars_at(position).take(100) {
 3003            // Found a possible emoji shortcode in the middle of the buffer
 3004            if found_colon {
 3005                if char.is_whitespace() {
 3006                    chars.reverse();
 3007                    return Some(chars.iter().collect());
 3008                }
 3009                // If the previous character is not a whitespace, we are in the middle of a word
 3010                // and we only want to complete the shortcode if the word is made up of other emojis
 3011                let mut containing_word = String::new();
 3012                for ch in snapshot
 3013                    .reversed_chars_at(position)
 3014                    .skip(chars.len() + 1)
 3015                    .take(100)
 3016                {
 3017                    if ch.is_whitespace() {
 3018                        break;
 3019                    }
 3020                    containing_word.push(ch);
 3021                }
 3022                let containing_word = containing_word.chars().rev().collect::<String>();
 3023                if util::word_consists_of_emojis(containing_word.as_str()) {
 3024                    chars.reverse();
 3025                    return Some(chars.iter().collect());
 3026                }
 3027            }
 3028
 3029            if char.is_whitespace() || !char.is_ascii() {
 3030                return None;
 3031            }
 3032            if char == ':' {
 3033                found_colon = true;
 3034            } else {
 3035                chars.push(char);
 3036            }
 3037        }
 3038        // Found a possible emoji shortcode at the beginning of the buffer
 3039        chars.reverse();
 3040        Some(chars.iter().collect())
 3041    }
 3042
 3043    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3044        self.transact(window, cx, |this, window, cx| {
 3045            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3046                let selections = this.selections.all::<usize>(cx);
 3047                let multi_buffer = this.buffer.read(cx);
 3048                let buffer = multi_buffer.snapshot(cx);
 3049                selections
 3050                    .iter()
 3051                    .map(|selection| {
 3052                        let start_point = selection.start.to_point(&buffer);
 3053                        let mut indent =
 3054                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3055                        indent.len = cmp::min(indent.len, start_point.column);
 3056                        let start = selection.start;
 3057                        let end = selection.end;
 3058                        let selection_is_empty = start == end;
 3059                        let language_scope = buffer.language_scope_at(start);
 3060                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3061                            &language_scope
 3062                        {
 3063                            let leading_whitespace_len = buffer
 3064                                .reversed_chars_at(start)
 3065                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3066                                .map(|c| c.len_utf8())
 3067                                .sum::<usize>();
 3068
 3069                            let trailing_whitespace_len = buffer
 3070                                .chars_at(end)
 3071                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3072                                .map(|c| c.len_utf8())
 3073                                .sum::<usize>();
 3074
 3075                            let insert_extra_newline =
 3076                                language.brackets().any(|(pair, enabled)| {
 3077                                    let pair_start = pair.start.trim_end();
 3078                                    let pair_end = pair.end.trim_start();
 3079
 3080                                    enabled
 3081                                        && pair.newline
 3082                                        && buffer.contains_str_at(
 3083                                            end + trailing_whitespace_len,
 3084                                            pair_end,
 3085                                        )
 3086                                        && buffer.contains_str_at(
 3087                                            (start - leading_whitespace_len)
 3088                                                .saturating_sub(pair_start.len()),
 3089                                            pair_start,
 3090                                        )
 3091                                });
 3092
 3093                            // Comment extension on newline is allowed only for cursor selections
 3094                            let comment_delimiter = maybe!({
 3095                                if !selection_is_empty {
 3096                                    return None;
 3097                                }
 3098
 3099                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3100                                    return None;
 3101                                }
 3102
 3103                                let delimiters = language.line_comment_prefixes();
 3104                                let max_len_of_delimiter =
 3105                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3106                                let (snapshot, range) =
 3107                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3108
 3109                                let mut index_of_first_non_whitespace = 0;
 3110                                let comment_candidate = snapshot
 3111                                    .chars_for_range(range)
 3112                                    .skip_while(|c| {
 3113                                        let should_skip = c.is_whitespace();
 3114                                        if should_skip {
 3115                                            index_of_first_non_whitespace += 1;
 3116                                        }
 3117                                        should_skip
 3118                                    })
 3119                                    .take(max_len_of_delimiter)
 3120                                    .collect::<String>();
 3121                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3122                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3123                                })?;
 3124                                let cursor_is_placed_after_comment_marker =
 3125                                    index_of_first_non_whitespace + comment_prefix.len()
 3126                                        <= start_point.column as usize;
 3127                                if cursor_is_placed_after_comment_marker {
 3128                                    Some(comment_prefix.clone())
 3129                                } else {
 3130                                    None
 3131                                }
 3132                            });
 3133                            (comment_delimiter, insert_extra_newline)
 3134                        } else {
 3135                            (None, false)
 3136                        };
 3137
 3138                        let capacity_for_delimiter = comment_delimiter
 3139                            .as_deref()
 3140                            .map(str::len)
 3141                            .unwrap_or_default();
 3142                        let mut new_text =
 3143                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3144                        new_text.push('\n');
 3145                        new_text.extend(indent.chars());
 3146                        if let Some(delimiter) = &comment_delimiter {
 3147                            new_text.push_str(delimiter);
 3148                        }
 3149                        if insert_extra_newline {
 3150                            new_text = new_text.repeat(2);
 3151                        }
 3152
 3153                        let anchor = buffer.anchor_after(end);
 3154                        let new_selection = selection.map(|_| anchor);
 3155                        (
 3156                            (start..end, new_text),
 3157                            (insert_extra_newline, new_selection),
 3158                        )
 3159                    })
 3160                    .unzip()
 3161            };
 3162
 3163            this.edit_with_autoindent(edits, cx);
 3164            let buffer = this.buffer.read(cx).snapshot(cx);
 3165            let new_selections = selection_fixup_info
 3166                .into_iter()
 3167                .map(|(extra_newline_inserted, new_selection)| {
 3168                    let mut cursor = new_selection.end.to_point(&buffer);
 3169                    if extra_newline_inserted {
 3170                        cursor.row -= 1;
 3171                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3172                    }
 3173                    new_selection.map(|_| cursor)
 3174                })
 3175                .collect();
 3176
 3177            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3178                s.select(new_selections)
 3179            });
 3180            this.refresh_inline_completion(true, false, window, cx);
 3181        });
 3182    }
 3183
 3184    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3185        let buffer = self.buffer.read(cx);
 3186        let snapshot = buffer.snapshot(cx);
 3187
 3188        let mut edits = Vec::new();
 3189        let mut rows = Vec::new();
 3190
 3191        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3192            let cursor = selection.head();
 3193            let row = cursor.row;
 3194
 3195            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3196
 3197            let newline = "\n".to_string();
 3198            edits.push((start_of_line..start_of_line, newline));
 3199
 3200            rows.push(row + rows_inserted as u32);
 3201        }
 3202
 3203        self.transact(window, cx, |editor, window, cx| {
 3204            editor.edit(edits, cx);
 3205
 3206            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3207                let mut index = 0;
 3208                s.move_cursors_with(|map, _, _| {
 3209                    let row = rows[index];
 3210                    index += 1;
 3211
 3212                    let point = Point::new(row, 0);
 3213                    let boundary = map.next_line_boundary(point).1;
 3214                    let clipped = map.clip_point(boundary, Bias::Left);
 3215
 3216                    (clipped, SelectionGoal::None)
 3217                });
 3218            });
 3219
 3220            let mut indent_edits = Vec::new();
 3221            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3222            for row in rows {
 3223                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3224                for (row, indent) in indents {
 3225                    if indent.len == 0 {
 3226                        continue;
 3227                    }
 3228
 3229                    let text = match indent.kind {
 3230                        IndentKind::Space => " ".repeat(indent.len as usize),
 3231                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3232                    };
 3233                    let point = Point::new(row.0, 0);
 3234                    indent_edits.push((point..point, text));
 3235                }
 3236            }
 3237            editor.edit(indent_edits, cx);
 3238        });
 3239    }
 3240
 3241    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3242        let buffer = self.buffer.read(cx);
 3243        let snapshot = buffer.snapshot(cx);
 3244
 3245        let mut edits = Vec::new();
 3246        let mut rows = Vec::new();
 3247        let mut rows_inserted = 0;
 3248
 3249        for selection in self.selections.all_adjusted(cx) {
 3250            let cursor = selection.head();
 3251            let row = cursor.row;
 3252
 3253            let point = Point::new(row + 1, 0);
 3254            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3255
 3256            let newline = "\n".to_string();
 3257            edits.push((start_of_line..start_of_line, newline));
 3258
 3259            rows_inserted += 1;
 3260            rows.push(row + rows_inserted);
 3261        }
 3262
 3263        self.transact(window, cx, |editor, window, cx| {
 3264            editor.edit(edits, cx);
 3265
 3266            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3267                let mut index = 0;
 3268                s.move_cursors_with(|map, _, _| {
 3269                    let row = rows[index];
 3270                    index += 1;
 3271
 3272                    let point = Point::new(row, 0);
 3273                    let boundary = map.next_line_boundary(point).1;
 3274                    let clipped = map.clip_point(boundary, Bias::Left);
 3275
 3276                    (clipped, SelectionGoal::None)
 3277                });
 3278            });
 3279
 3280            let mut indent_edits = Vec::new();
 3281            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3282            for row in rows {
 3283                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3284                for (row, indent) in indents {
 3285                    if indent.len == 0 {
 3286                        continue;
 3287                    }
 3288
 3289                    let text = match indent.kind {
 3290                        IndentKind::Space => " ".repeat(indent.len as usize),
 3291                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3292                    };
 3293                    let point = Point::new(row.0, 0);
 3294                    indent_edits.push((point..point, text));
 3295                }
 3296            }
 3297            editor.edit(indent_edits, cx);
 3298        });
 3299    }
 3300
 3301    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3302        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3303            original_indent_columns: Vec::new(),
 3304        });
 3305        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3306    }
 3307
 3308    fn insert_with_autoindent_mode(
 3309        &mut self,
 3310        text: &str,
 3311        autoindent_mode: Option<AutoindentMode>,
 3312        window: &mut Window,
 3313        cx: &mut Context<Self>,
 3314    ) {
 3315        if self.read_only(cx) {
 3316            return;
 3317        }
 3318
 3319        let text: Arc<str> = text.into();
 3320        self.transact(window, cx, |this, window, cx| {
 3321            let old_selections = this.selections.all_adjusted(cx);
 3322            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3323                let anchors = {
 3324                    let snapshot = buffer.read(cx);
 3325                    old_selections
 3326                        .iter()
 3327                        .map(|s| {
 3328                            let anchor = snapshot.anchor_after(s.head());
 3329                            s.map(|_| anchor)
 3330                        })
 3331                        .collect::<Vec<_>>()
 3332                };
 3333                buffer.edit(
 3334                    old_selections
 3335                        .iter()
 3336                        .map(|s| (s.start..s.end, text.clone())),
 3337                    autoindent_mode,
 3338                    cx,
 3339                );
 3340                anchors
 3341            });
 3342
 3343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3344                s.select_anchors(selection_anchors);
 3345            });
 3346
 3347            cx.notify();
 3348        });
 3349    }
 3350
 3351    fn trigger_completion_on_input(
 3352        &mut self,
 3353        text: &str,
 3354        trigger_in_words: bool,
 3355        window: &mut Window,
 3356        cx: &mut Context<Self>,
 3357    ) {
 3358        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3359            self.show_completions(
 3360                &ShowCompletions {
 3361                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3362                },
 3363                window,
 3364                cx,
 3365            );
 3366        } else {
 3367            self.hide_context_menu(window, cx);
 3368        }
 3369    }
 3370
 3371    fn is_completion_trigger(
 3372        &self,
 3373        text: &str,
 3374        trigger_in_words: bool,
 3375        cx: &mut Context<Self>,
 3376    ) -> bool {
 3377        let position = self.selections.newest_anchor().head();
 3378        let multibuffer = self.buffer.read(cx);
 3379        let Some(buffer) = position
 3380            .buffer_id
 3381            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3382        else {
 3383            return false;
 3384        };
 3385
 3386        if let Some(completion_provider) = &self.completion_provider {
 3387            completion_provider.is_completion_trigger(
 3388                &buffer,
 3389                position.text_anchor,
 3390                text,
 3391                trigger_in_words,
 3392                cx,
 3393            )
 3394        } else {
 3395            false
 3396        }
 3397    }
 3398
 3399    /// If any empty selections is touching the start of its innermost containing autoclose
 3400    /// region, expand it to select the brackets.
 3401    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3402        let selections = self.selections.all::<usize>(cx);
 3403        let buffer = self.buffer.read(cx).read(cx);
 3404        let new_selections = self
 3405            .selections_with_autoclose_regions(selections, &buffer)
 3406            .map(|(mut selection, region)| {
 3407                if !selection.is_empty() {
 3408                    return selection;
 3409                }
 3410
 3411                if let Some(region) = region {
 3412                    let mut range = region.range.to_offset(&buffer);
 3413                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3414                        range.start -= region.pair.start.len();
 3415                        if buffer.contains_str_at(range.start, &region.pair.start)
 3416                            && buffer.contains_str_at(range.end, &region.pair.end)
 3417                        {
 3418                            range.end += region.pair.end.len();
 3419                            selection.start = range.start;
 3420                            selection.end = range.end;
 3421
 3422                            return selection;
 3423                        }
 3424                    }
 3425                }
 3426
 3427                let always_treat_brackets_as_autoclosed = buffer
 3428                    .settings_at(selection.start, cx)
 3429                    .always_treat_brackets_as_autoclosed;
 3430
 3431                if !always_treat_brackets_as_autoclosed {
 3432                    return selection;
 3433                }
 3434
 3435                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3436                    for (pair, enabled) in scope.brackets() {
 3437                        if !enabled || !pair.close {
 3438                            continue;
 3439                        }
 3440
 3441                        if buffer.contains_str_at(selection.start, &pair.end) {
 3442                            let pair_start_len = pair.start.len();
 3443                            if buffer.contains_str_at(
 3444                                selection.start.saturating_sub(pair_start_len),
 3445                                &pair.start,
 3446                            ) {
 3447                                selection.start -= pair_start_len;
 3448                                selection.end += pair.end.len();
 3449
 3450                                return selection;
 3451                            }
 3452                        }
 3453                    }
 3454                }
 3455
 3456                selection
 3457            })
 3458            .collect();
 3459
 3460        drop(buffer);
 3461        self.change_selections(None, window, cx, |selections| {
 3462            selections.select(new_selections)
 3463        });
 3464    }
 3465
 3466    /// Iterate the given selections, and for each one, find the smallest surrounding
 3467    /// autoclose region. This uses the ordering of the selections and the autoclose
 3468    /// regions to avoid repeated comparisons.
 3469    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3470        &'a self,
 3471        selections: impl IntoIterator<Item = Selection<D>>,
 3472        buffer: &'a MultiBufferSnapshot,
 3473    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3474        let mut i = 0;
 3475        let mut regions = self.autoclose_regions.as_slice();
 3476        selections.into_iter().map(move |selection| {
 3477            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3478
 3479            let mut enclosing = None;
 3480            while let Some(pair_state) = regions.get(i) {
 3481                if pair_state.range.end.to_offset(buffer) < range.start {
 3482                    regions = &regions[i + 1..];
 3483                    i = 0;
 3484                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3485                    break;
 3486                } else {
 3487                    if pair_state.selection_id == selection.id {
 3488                        enclosing = Some(pair_state);
 3489                    }
 3490                    i += 1;
 3491                }
 3492            }
 3493
 3494            (selection, enclosing)
 3495        })
 3496    }
 3497
 3498    /// Remove any autoclose regions that no longer contain their selection.
 3499    fn invalidate_autoclose_regions(
 3500        &mut self,
 3501        mut selections: &[Selection<Anchor>],
 3502        buffer: &MultiBufferSnapshot,
 3503    ) {
 3504        self.autoclose_regions.retain(|state| {
 3505            let mut i = 0;
 3506            while let Some(selection) = selections.get(i) {
 3507                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3508                    selections = &selections[1..];
 3509                    continue;
 3510                }
 3511                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3512                    break;
 3513                }
 3514                if selection.id == state.selection_id {
 3515                    return true;
 3516                } else {
 3517                    i += 1;
 3518                }
 3519            }
 3520            false
 3521        });
 3522    }
 3523
 3524    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3525        let offset = position.to_offset(buffer);
 3526        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3527        if offset > word_range.start && kind == Some(CharKind::Word) {
 3528            Some(
 3529                buffer
 3530                    .text_for_range(word_range.start..offset)
 3531                    .collect::<String>(),
 3532            )
 3533        } else {
 3534            None
 3535        }
 3536    }
 3537
 3538    pub fn toggle_inlay_hints(
 3539        &mut self,
 3540        _: &ToggleInlayHints,
 3541        _: &mut Window,
 3542        cx: &mut Context<Self>,
 3543    ) {
 3544        self.refresh_inlay_hints(
 3545            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3546            cx,
 3547        );
 3548    }
 3549
 3550    pub fn inlay_hints_enabled(&self) -> bool {
 3551        self.inlay_hint_cache.enabled
 3552    }
 3553
 3554    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3555        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3556            return;
 3557        }
 3558
 3559        let reason_description = reason.description();
 3560        let ignore_debounce = matches!(
 3561            reason,
 3562            InlayHintRefreshReason::SettingsChange(_)
 3563                | InlayHintRefreshReason::Toggle(_)
 3564                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3565        );
 3566        let (invalidate_cache, required_languages) = match reason {
 3567            InlayHintRefreshReason::Toggle(enabled) => {
 3568                self.inlay_hint_cache.enabled = enabled;
 3569                if enabled {
 3570                    (InvalidationStrategy::RefreshRequested, None)
 3571                } else {
 3572                    self.inlay_hint_cache.clear();
 3573                    self.splice_inlays(
 3574                        &self
 3575                            .visible_inlay_hints(cx)
 3576                            .iter()
 3577                            .map(|inlay| inlay.id)
 3578                            .collect::<Vec<InlayId>>(),
 3579                        Vec::new(),
 3580                        cx,
 3581                    );
 3582                    return;
 3583                }
 3584            }
 3585            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3586                match self.inlay_hint_cache.update_settings(
 3587                    &self.buffer,
 3588                    new_settings,
 3589                    self.visible_inlay_hints(cx),
 3590                    cx,
 3591                ) {
 3592                    ControlFlow::Break(Some(InlaySplice {
 3593                        to_remove,
 3594                        to_insert,
 3595                    })) => {
 3596                        self.splice_inlays(&to_remove, to_insert, cx);
 3597                        return;
 3598                    }
 3599                    ControlFlow::Break(None) => return,
 3600                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3601                }
 3602            }
 3603            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3604                if let Some(InlaySplice {
 3605                    to_remove,
 3606                    to_insert,
 3607                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3608                {
 3609                    self.splice_inlays(&to_remove, to_insert, cx);
 3610                }
 3611                return;
 3612            }
 3613            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3614            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3615                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3616            }
 3617            InlayHintRefreshReason::RefreshRequested => {
 3618                (InvalidationStrategy::RefreshRequested, None)
 3619            }
 3620        };
 3621
 3622        if let Some(InlaySplice {
 3623            to_remove,
 3624            to_insert,
 3625        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3626            reason_description,
 3627            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3628            invalidate_cache,
 3629            ignore_debounce,
 3630            cx,
 3631        ) {
 3632            self.splice_inlays(&to_remove, to_insert, cx);
 3633        }
 3634    }
 3635
 3636    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3637        self.display_map
 3638            .read(cx)
 3639            .current_inlays()
 3640            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3641            .cloned()
 3642            .collect()
 3643    }
 3644
 3645    pub fn excerpts_for_inlay_hints_query(
 3646        &self,
 3647        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3648        cx: &mut Context<Editor>,
 3649    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3650        let Some(project) = self.project.as_ref() else {
 3651            return HashMap::default();
 3652        };
 3653        let project = project.read(cx);
 3654        let multi_buffer = self.buffer().read(cx);
 3655        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3656        let multi_buffer_visible_start = self
 3657            .scroll_manager
 3658            .anchor()
 3659            .anchor
 3660            .to_point(&multi_buffer_snapshot);
 3661        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3662            multi_buffer_visible_start
 3663                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3664            Bias::Left,
 3665        );
 3666        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3667        multi_buffer_snapshot
 3668            .range_to_buffer_ranges(multi_buffer_visible_range)
 3669            .into_iter()
 3670            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3671            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3672                let buffer_file = project::File::from_dyn(buffer.file())?;
 3673                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3674                let worktree_entry = buffer_worktree
 3675                    .read(cx)
 3676                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3677                if worktree_entry.is_ignored {
 3678                    return None;
 3679                }
 3680
 3681                let language = buffer.language()?;
 3682                if let Some(restrict_to_languages) = restrict_to_languages {
 3683                    if !restrict_to_languages.contains(language) {
 3684                        return None;
 3685                    }
 3686                }
 3687                Some((
 3688                    excerpt_id,
 3689                    (
 3690                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3691                        buffer.version().clone(),
 3692                        excerpt_visible_range,
 3693                    ),
 3694                ))
 3695            })
 3696            .collect()
 3697    }
 3698
 3699    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3700        TextLayoutDetails {
 3701            text_system: window.text_system().clone(),
 3702            editor_style: self.style.clone().unwrap(),
 3703            rem_size: window.rem_size(),
 3704            scroll_anchor: self.scroll_manager.anchor(),
 3705            visible_rows: self.visible_line_count(),
 3706            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3707        }
 3708    }
 3709
 3710    pub fn splice_inlays(
 3711        &self,
 3712        to_remove: &[InlayId],
 3713        to_insert: Vec<Inlay>,
 3714        cx: &mut Context<Self>,
 3715    ) {
 3716        self.display_map.update(cx, |display_map, cx| {
 3717            display_map.splice_inlays(to_remove, to_insert, cx)
 3718        });
 3719        cx.notify();
 3720    }
 3721
 3722    fn trigger_on_type_formatting(
 3723        &self,
 3724        input: String,
 3725        window: &mut Window,
 3726        cx: &mut Context<Self>,
 3727    ) -> Option<Task<Result<()>>> {
 3728        if input.len() != 1 {
 3729            return None;
 3730        }
 3731
 3732        let project = self.project.as_ref()?;
 3733        let position = self.selections.newest_anchor().head();
 3734        let (buffer, buffer_position) = self
 3735            .buffer
 3736            .read(cx)
 3737            .text_anchor_for_position(position, cx)?;
 3738
 3739        let settings = language_settings::language_settings(
 3740            buffer
 3741                .read(cx)
 3742                .language_at(buffer_position)
 3743                .map(|l| l.name()),
 3744            buffer.read(cx).file(),
 3745            cx,
 3746        );
 3747        if !settings.use_on_type_format {
 3748            return None;
 3749        }
 3750
 3751        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3752        // hence we do LSP request & edit on host side only — add formats to host's history.
 3753        let push_to_lsp_host_history = true;
 3754        // If this is not the host, append its history with new edits.
 3755        let push_to_client_history = project.read(cx).is_via_collab();
 3756
 3757        let on_type_formatting = project.update(cx, |project, cx| {
 3758            project.on_type_format(
 3759                buffer.clone(),
 3760                buffer_position,
 3761                input,
 3762                push_to_lsp_host_history,
 3763                cx,
 3764            )
 3765        });
 3766        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3767            if let Some(transaction) = on_type_formatting.await? {
 3768                if push_to_client_history {
 3769                    buffer
 3770                        .update(&mut cx, |buffer, _| {
 3771                            buffer.push_transaction(transaction, Instant::now());
 3772                        })
 3773                        .ok();
 3774                }
 3775                editor.update(&mut cx, |editor, cx| {
 3776                    editor.refresh_document_highlights(cx);
 3777                })?;
 3778            }
 3779            Ok(())
 3780        }))
 3781    }
 3782
 3783    pub fn show_completions(
 3784        &mut self,
 3785        options: &ShowCompletions,
 3786        window: &mut Window,
 3787        cx: &mut Context<Self>,
 3788    ) {
 3789        if self.pending_rename.is_some() {
 3790            return;
 3791        }
 3792
 3793        let Some(provider) = self.completion_provider.as_ref() else {
 3794            return;
 3795        };
 3796
 3797        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3798            return;
 3799        }
 3800
 3801        let position = self.selections.newest_anchor().head();
 3802        if position.diff_base_anchor.is_some() {
 3803            return;
 3804        }
 3805        let (buffer, buffer_position) =
 3806            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3807                output
 3808            } else {
 3809                return;
 3810            };
 3811        let show_completion_documentation = buffer
 3812            .read(cx)
 3813            .snapshot()
 3814            .settings_at(buffer_position, cx)
 3815            .show_completion_documentation;
 3816
 3817        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3818
 3819        let trigger_kind = match &options.trigger {
 3820            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3821                CompletionTriggerKind::TRIGGER_CHARACTER
 3822            }
 3823            _ => CompletionTriggerKind::INVOKED,
 3824        };
 3825        let completion_context = CompletionContext {
 3826            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3827                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3828                    Some(String::from(trigger))
 3829                } else {
 3830                    None
 3831                }
 3832            }),
 3833            trigger_kind,
 3834        };
 3835        let completions =
 3836            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3837        let sort_completions = provider.sort_completions();
 3838
 3839        let id = post_inc(&mut self.next_completion_id);
 3840        let task = cx.spawn_in(window, |editor, mut cx| {
 3841            async move {
 3842                editor.update(&mut cx, |this, _| {
 3843                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3844                })?;
 3845                let completions = completions.await.log_err();
 3846                let menu = if let Some(completions) = completions {
 3847                    let mut menu = CompletionsMenu::new(
 3848                        id,
 3849                        sort_completions,
 3850                        show_completion_documentation,
 3851                        position,
 3852                        buffer.clone(),
 3853                        completions.into(),
 3854                    );
 3855
 3856                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3857                        .await;
 3858
 3859                    menu.visible().then_some(menu)
 3860                } else {
 3861                    None
 3862                };
 3863
 3864                editor.update_in(&mut cx, |editor, window, cx| {
 3865                    match editor.context_menu.borrow().as_ref() {
 3866                        None => {}
 3867                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3868                            if prev_menu.id > id {
 3869                                return;
 3870                            }
 3871                        }
 3872                        _ => return,
 3873                    }
 3874
 3875                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3876                        let mut menu = menu.unwrap();
 3877                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3878
 3879                        *editor.context_menu.borrow_mut() =
 3880                            Some(CodeContextMenu::Completions(menu));
 3881
 3882                        if editor.show_inline_completions_in_menu(cx) {
 3883                            editor.update_visible_inline_completion(window, cx);
 3884                        } else {
 3885                            editor.discard_inline_completion(false, cx);
 3886                        }
 3887
 3888                        cx.notify();
 3889                    } else if editor.completion_tasks.len() <= 1 {
 3890                        // If there are no more completion tasks and the last menu was
 3891                        // empty, we should hide it.
 3892                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3893                        // If it was already hidden and we don't show inline
 3894                        // completions in the menu, we should also show the
 3895                        // inline-completion when available.
 3896                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3897                            editor.update_visible_inline_completion(window, cx);
 3898                        }
 3899                    }
 3900                })?;
 3901
 3902                Ok::<_, anyhow::Error>(())
 3903            }
 3904            .log_err()
 3905        });
 3906
 3907        self.completion_tasks.push((id, task));
 3908    }
 3909
 3910    pub fn confirm_completion(
 3911        &mut self,
 3912        action: &ConfirmCompletion,
 3913        window: &mut Window,
 3914        cx: &mut Context<Self>,
 3915    ) -> Option<Task<Result<()>>> {
 3916        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3917    }
 3918
 3919    pub fn compose_completion(
 3920        &mut self,
 3921        action: &ComposeCompletion,
 3922        window: &mut Window,
 3923        cx: &mut Context<Self>,
 3924    ) -> Option<Task<Result<()>>> {
 3925        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3926    }
 3927
 3928    fn do_completion(
 3929        &mut self,
 3930        item_ix: Option<usize>,
 3931        intent: CompletionIntent,
 3932        window: &mut Window,
 3933        cx: &mut Context<Editor>,
 3934    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3935        use language::ToOffset as _;
 3936
 3937        let completions_menu =
 3938            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3939                menu
 3940            } else {
 3941                return None;
 3942            };
 3943
 3944        let entries = completions_menu.entries.borrow();
 3945        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3946        if self.show_inline_completions_in_menu(cx) {
 3947            self.discard_inline_completion(true, cx);
 3948        }
 3949        let candidate_id = mat.candidate_id;
 3950        drop(entries);
 3951
 3952        let buffer_handle = completions_menu.buffer;
 3953        let completion = completions_menu
 3954            .completions
 3955            .borrow()
 3956            .get(candidate_id)?
 3957            .clone();
 3958        cx.stop_propagation();
 3959
 3960        let snippet;
 3961        let text;
 3962
 3963        if completion.is_snippet() {
 3964            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3965            text = snippet.as_ref().unwrap().text.clone();
 3966        } else {
 3967            snippet = None;
 3968            text = completion.new_text.clone();
 3969        };
 3970        let selections = self.selections.all::<usize>(cx);
 3971        let buffer = buffer_handle.read(cx);
 3972        let old_range = completion.old_range.to_offset(buffer);
 3973        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3974
 3975        let newest_selection = self.selections.newest_anchor();
 3976        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3977            return None;
 3978        }
 3979
 3980        let lookbehind = newest_selection
 3981            .start
 3982            .text_anchor
 3983            .to_offset(buffer)
 3984            .saturating_sub(old_range.start);
 3985        let lookahead = old_range
 3986            .end
 3987            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3988        let mut common_prefix_len = old_text
 3989            .bytes()
 3990            .zip(text.bytes())
 3991            .take_while(|(a, b)| a == b)
 3992            .count();
 3993
 3994        let snapshot = self.buffer.read(cx).snapshot(cx);
 3995        let mut range_to_replace: Option<Range<isize>> = None;
 3996        let mut ranges = Vec::new();
 3997        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3998        for selection in &selections {
 3999            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4000                let start = selection.start.saturating_sub(lookbehind);
 4001                let end = selection.end + lookahead;
 4002                if selection.id == newest_selection.id {
 4003                    range_to_replace = Some(
 4004                        ((start + common_prefix_len) as isize - selection.start as isize)
 4005                            ..(end as isize - selection.start as isize),
 4006                    );
 4007                }
 4008                ranges.push(start + common_prefix_len..end);
 4009            } else {
 4010                common_prefix_len = 0;
 4011                ranges.clear();
 4012                ranges.extend(selections.iter().map(|s| {
 4013                    if s.id == newest_selection.id {
 4014                        range_to_replace = Some(
 4015                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4016                                - selection.start as isize
 4017                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4018                                    - selection.start as isize,
 4019                        );
 4020                        old_range.clone()
 4021                    } else {
 4022                        s.start..s.end
 4023                    }
 4024                }));
 4025                break;
 4026            }
 4027            if !self.linked_edit_ranges.is_empty() {
 4028                let start_anchor = snapshot.anchor_before(selection.head());
 4029                let end_anchor = snapshot.anchor_after(selection.tail());
 4030                if let Some(ranges) = self
 4031                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4032                {
 4033                    for (buffer, edits) in ranges {
 4034                        linked_edits.entry(buffer.clone()).or_default().extend(
 4035                            edits
 4036                                .into_iter()
 4037                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4038                        );
 4039                    }
 4040                }
 4041            }
 4042        }
 4043        let text = &text[common_prefix_len..];
 4044
 4045        cx.emit(EditorEvent::InputHandled {
 4046            utf16_range_to_replace: range_to_replace,
 4047            text: text.into(),
 4048        });
 4049
 4050        self.transact(window, cx, |this, window, cx| {
 4051            if let Some(mut snippet) = snippet {
 4052                snippet.text = text.to_string();
 4053                for tabstop in snippet
 4054                    .tabstops
 4055                    .iter_mut()
 4056                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4057                {
 4058                    tabstop.start -= common_prefix_len as isize;
 4059                    tabstop.end -= common_prefix_len as isize;
 4060                }
 4061
 4062                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4063            } else {
 4064                this.buffer.update(cx, |buffer, cx| {
 4065                    buffer.edit(
 4066                        ranges.iter().map(|range| (range.clone(), text)),
 4067                        this.autoindent_mode.clone(),
 4068                        cx,
 4069                    );
 4070                });
 4071            }
 4072            for (buffer, edits) in linked_edits {
 4073                buffer.update(cx, |buffer, cx| {
 4074                    let snapshot = buffer.snapshot();
 4075                    let edits = edits
 4076                        .into_iter()
 4077                        .map(|(range, text)| {
 4078                            use text::ToPoint as TP;
 4079                            let end_point = TP::to_point(&range.end, &snapshot);
 4080                            let start_point = TP::to_point(&range.start, &snapshot);
 4081                            (start_point..end_point, text)
 4082                        })
 4083                        .sorted_by_key(|(range, _)| range.start)
 4084                        .collect::<Vec<_>>();
 4085                    buffer.edit(edits, None, cx);
 4086                })
 4087            }
 4088
 4089            this.refresh_inline_completion(true, false, window, cx);
 4090        });
 4091
 4092        let show_new_completions_on_confirm = completion
 4093            .confirm
 4094            .as_ref()
 4095            .map_or(false, |confirm| confirm(intent, window, cx));
 4096        if show_new_completions_on_confirm {
 4097            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4098        }
 4099
 4100        let provider = self.completion_provider.as_ref()?;
 4101        drop(completion);
 4102        let apply_edits = provider.apply_additional_edits_for_completion(
 4103            buffer_handle,
 4104            completions_menu.completions.clone(),
 4105            candidate_id,
 4106            true,
 4107            cx,
 4108        );
 4109
 4110        let editor_settings = EditorSettings::get_global(cx);
 4111        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4112            // After the code completion is finished, users often want to know what signatures are needed.
 4113            // so we should automatically call signature_help
 4114            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4115        }
 4116
 4117        Some(cx.foreground_executor().spawn(async move {
 4118            apply_edits.await?;
 4119            Ok(())
 4120        }))
 4121    }
 4122
 4123    pub fn toggle_code_actions(
 4124        &mut self,
 4125        action: &ToggleCodeActions,
 4126        window: &mut Window,
 4127        cx: &mut Context<Self>,
 4128    ) {
 4129        let mut context_menu = self.context_menu.borrow_mut();
 4130        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4131            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4132                // Toggle if we're selecting the same one
 4133                *context_menu = None;
 4134                cx.notify();
 4135                return;
 4136            } else {
 4137                // Otherwise, clear it and start a new one
 4138                *context_menu = None;
 4139                cx.notify();
 4140            }
 4141        }
 4142        drop(context_menu);
 4143        let snapshot = self.snapshot(window, cx);
 4144        let deployed_from_indicator = action.deployed_from_indicator;
 4145        let mut task = self.code_actions_task.take();
 4146        let action = action.clone();
 4147        cx.spawn_in(window, |editor, mut cx| async move {
 4148            while let Some(prev_task) = task {
 4149                prev_task.await.log_err();
 4150                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4151            }
 4152
 4153            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4154                if editor.focus_handle.is_focused(window) {
 4155                    let multibuffer_point = action
 4156                        .deployed_from_indicator
 4157                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4158                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4159                    let (buffer, buffer_row) = snapshot
 4160                        .buffer_snapshot
 4161                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4162                        .and_then(|(buffer_snapshot, range)| {
 4163                            editor
 4164                                .buffer
 4165                                .read(cx)
 4166                                .buffer(buffer_snapshot.remote_id())
 4167                                .map(|buffer| (buffer, range.start.row))
 4168                        })?;
 4169                    let (_, code_actions) = editor
 4170                        .available_code_actions
 4171                        .clone()
 4172                        .and_then(|(location, code_actions)| {
 4173                            let snapshot = location.buffer.read(cx).snapshot();
 4174                            let point_range = location.range.to_point(&snapshot);
 4175                            let point_range = point_range.start.row..=point_range.end.row;
 4176                            if point_range.contains(&buffer_row) {
 4177                                Some((location, code_actions))
 4178                            } else {
 4179                                None
 4180                            }
 4181                        })
 4182                        .unzip();
 4183                    let buffer_id = buffer.read(cx).remote_id();
 4184                    let tasks = editor
 4185                        .tasks
 4186                        .get(&(buffer_id, buffer_row))
 4187                        .map(|t| Arc::new(t.to_owned()));
 4188                    if tasks.is_none() && code_actions.is_none() {
 4189                        return None;
 4190                    }
 4191
 4192                    editor.completion_tasks.clear();
 4193                    editor.discard_inline_completion(false, cx);
 4194                    let task_context =
 4195                        tasks
 4196                            .as_ref()
 4197                            .zip(editor.project.clone())
 4198                            .map(|(tasks, project)| {
 4199                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4200                            });
 4201
 4202                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4203                        let task_context = match task_context {
 4204                            Some(task_context) => task_context.await,
 4205                            None => None,
 4206                        };
 4207                        let resolved_tasks =
 4208                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4209                                Rc::new(ResolvedTasks {
 4210                                    templates: tasks.resolve(&task_context).collect(),
 4211                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4212                                        multibuffer_point.row,
 4213                                        tasks.column,
 4214                                    )),
 4215                                })
 4216                            });
 4217                        let spawn_straight_away = resolved_tasks
 4218                            .as_ref()
 4219                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4220                            && code_actions
 4221                                .as_ref()
 4222                                .map_or(true, |actions| actions.is_empty());
 4223                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4224                            *editor.context_menu.borrow_mut() =
 4225                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4226                                    buffer,
 4227                                    actions: CodeActionContents {
 4228                                        tasks: resolved_tasks,
 4229                                        actions: code_actions,
 4230                                    },
 4231                                    selected_item: Default::default(),
 4232                                    scroll_handle: UniformListScrollHandle::default(),
 4233                                    deployed_from_indicator,
 4234                                }));
 4235                            if spawn_straight_away {
 4236                                if let Some(task) = editor.confirm_code_action(
 4237                                    &ConfirmCodeAction { item_ix: Some(0) },
 4238                                    window,
 4239                                    cx,
 4240                                ) {
 4241                                    cx.notify();
 4242                                    return task;
 4243                                }
 4244                            }
 4245                            cx.notify();
 4246                            Task::ready(Ok(()))
 4247                        }) {
 4248                            task.await
 4249                        } else {
 4250                            Ok(())
 4251                        }
 4252                    }))
 4253                } else {
 4254                    Some(Task::ready(Ok(())))
 4255                }
 4256            })?;
 4257            if let Some(task) = spawned_test_task {
 4258                task.await?;
 4259            }
 4260
 4261            Ok::<_, anyhow::Error>(())
 4262        })
 4263        .detach_and_log_err(cx);
 4264    }
 4265
 4266    pub fn confirm_code_action(
 4267        &mut self,
 4268        action: &ConfirmCodeAction,
 4269        window: &mut Window,
 4270        cx: &mut Context<Self>,
 4271    ) -> Option<Task<Result<()>>> {
 4272        let actions_menu =
 4273            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4274                menu
 4275            } else {
 4276                return None;
 4277            };
 4278        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4279        let action = actions_menu.actions.get(action_ix)?;
 4280        let title = action.label();
 4281        let buffer = actions_menu.buffer;
 4282        let workspace = self.workspace()?;
 4283
 4284        match action {
 4285            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4286                workspace.update(cx, |workspace, cx| {
 4287                    workspace::tasks::schedule_resolved_task(
 4288                        workspace,
 4289                        task_source_kind,
 4290                        resolved_task,
 4291                        false,
 4292                        cx,
 4293                    );
 4294
 4295                    Some(Task::ready(Ok(())))
 4296                })
 4297            }
 4298            CodeActionsItem::CodeAction {
 4299                excerpt_id,
 4300                action,
 4301                provider,
 4302            } => {
 4303                let apply_code_action =
 4304                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4305                let workspace = workspace.downgrade();
 4306                Some(cx.spawn_in(window, |editor, cx| async move {
 4307                    let project_transaction = apply_code_action.await?;
 4308                    Self::open_project_transaction(
 4309                        &editor,
 4310                        workspace,
 4311                        project_transaction,
 4312                        title,
 4313                        cx,
 4314                    )
 4315                    .await
 4316                }))
 4317            }
 4318        }
 4319    }
 4320
 4321    pub async fn open_project_transaction(
 4322        this: &WeakEntity<Editor>,
 4323        workspace: WeakEntity<Workspace>,
 4324        transaction: ProjectTransaction,
 4325        title: String,
 4326        mut cx: AsyncWindowContext,
 4327    ) -> Result<()> {
 4328        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4329        cx.update(|_, cx| {
 4330            entries.sort_unstable_by_key(|(buffer, _)| {
 4331                buffer.read(cx).file().map(|f| f.path().clone())
 4332            });
 4333        })?;
 4334
 4335        // If the project transaction's edits are all contained within this editor, then
 4336        // avoid opening a new editor to display them.
 4337
 4338        if let Some((buffer, transaction)) = entries.first() {
 4339            if entries.len() == 1 {
 4340                let excerpt = this.update(&mut cx, |editor, cx| {
 4341                    editor
 4342                        .buffer()
 4343                        .read(cx)
 4344                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4345                })?;
 4346                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4347                    if excerpted_buffer == *buffer {
 4348                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4349                            let excerpt_range = excerpt_range.to_offset(buffer);
 4350                            buffer
 4351                                .edited_ranges_for_transaction::<usize>(transaction)
 4352                                .all(|range| {
 4353                                    excerpt_range.start <= range.start
 4354                                        && excerpt_range.end >= range.end
 4355                                })
 4356                        })?;
 4357
 4358                        if all_edits_within_excerpt {
 4359                            return Ok(());
 4360                        }
 4361                    }
 4362                }
 4363            }
 4364        } else {
 4365            return Ok(());
 4366        }
 4367
 4368        let mut ranges_to_highlight = Vec::new();
 4369        let excerpt_buffer = cx.new(|cx| {
 4370            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4371            for (buffer_handle, transaction) in &entries {
 4372                let buffer = buffer_handle.read(cx);
 4373                ranges_to_highlight.extend(
 4374                    multibuffer.push_excerpts_with_context_lines(
 4375                        buffer_handle.clone(),
 4376                        buffer
 4377                            .edited_ranges_for_transaction::<usize>(transaction)
 4378                            .collect(),
 4379                        DEFAULT_MULTIBUFFER_CONTEXT,
 4380                        cx,
 4381                    ),
 4382                );
 4383            }
 4384            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4385            multibuffer
 4386        })?;
 4387
 4388        workspace.update_in(&mut cx, |workspace, window, cx| {
 4389            let project = workspace.project().clone();
 4390            let editor = cx
 4391                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4392            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4393            editor.update(cx, |editor, cx| {
 4394                editor.highlight_background::<Self>(
 4395                    &ranges_to_highlight,
 4396                    |theme| theme.editor_highlighted_line_background,
 4397                    cx,
 4398                );
 4399            });
 4400        })?;
 4401
 4402        Ok(())
 4403    }
 4404
 4405    pub fn clear_code_action_providers(&mut self) {
 4406        self.code_action_providers.clear();
 4407        self.available_code_actions.take();
 4408    }
 4409
 4410    pub fn add_code_action_provider(
 4411        &mut self,
 4412        provider: Rc<dyn CodeActionProvider>,
 4413        window: &mut Window,
 4414        cx: &mut Context<Self>,
 4415    ) {
 4416        if self
 4417            .code_action_providers
 4418            .iter()
 4419            .any(|existing_provider| existing_provider.id() == provider.id())
 4420        {
 4421            return;
 4422        }
 4423
 4424        self.code_action_providers.push(provider);
 4425        self.refresh_code_actions(window, cx);
 4426    }
 4427
 4428    pub fn remove_code_action_provider(
 4429        &mut self,
 4430        id: Arc<str>,
 4431        window: &mut Window,
 4432        cx: &mut Context<Self>,
 4433    ) {
 4434        self.code_action_providers
 4435            .retain(|provider| provider.id() != id);
 4436        self.refresh_code_actions(window, cx);
 4437    }
 4438
 4439    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4440        let buffer = self.buffer.read(cx);
 4441        let newest_selection = self.selections.newest_anchor().clone();
 4442        if newest_selection.head().diff_base_anchor.is_some() {
 4443            return None;
 4444        }
 4445        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4446        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4447        if start_buffer != end_buffer {
 4448            return None;
 4449        }
 4450
 4451        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4452            cx.background_executor()
 4453                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4454                .await;
 4455
 4456            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4457                let providers = this.code_action_providers.clone();
 4458                let tasks = this
 4459                    .code_action_providers
 4460                    .iter()
 4461                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4462                    .collect::<Vec<_>>();
 4463                (providers, tasks)
 4464            })?;
 4465
 4466            let mut actions = Vec::new();
 4467            for (provider, provider_actions) in
 4468                providers.into_iter().zip(future::join_all(tasks).await)
 4469            {
 4470                if let Some(provider_actions) = provider_actions.log_err() {
 4471                    actions.extend(provider_actions.into_iter().map(|action| {
 4472                        AvailableCodeAction {
 4473                            excerpt_id: newest_selection.start.excerpt_id,
 4474                            action,
 4475                            provider: provider.clone(),
 4476                        }
 4477                    }));
 4478                }
 4479            }
 4480
 4481            this.update(&mut cx, |this, cx| {
 4482                this.available_code_actions = if actions.is_empty() {
 4483                    None
 4484                } else {
 4485                    Some((
 4486                        Location {
 4487                            buffer: start_buffer,
 4488                            range: start..end,
 4489                        },
 4490                        actions.into(),
 4491                    ))
 4492                };
 4493                cx.notify();
 4494            })
 4495        }));
 4496        None
 4497    }
 4498
 4499    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4500        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4501            self.show_git_blame_inline = false;
 4502
 4503            self.show_git_blame_inline_delay_task =
 4504                Some(cx.spawn_in(window, |this, mut cx| async move {
 4505                    cx.background_executor().timer(delay).await;
 4506
 4507                    this.update(&mut cx, |this, cx| {
 4508                        this.show_git_blame_inline = true;
 4509                        cx.notify();
 4510                    })
 4511                    .log_err();
 4512                }));
 4513        }
 4514    }
 4515
 4516    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4517        if self.pending_rename.is_some() {
 4518            return None;
 4519        }
 4520
 4521        let provider = self.semantics_provider.clone()?;
 4522        let buffer = self.buffer.read(cx);
 4523        let newest_selection = self.selections.newest_anchor().clone();
 4524        let cursor_position = newest_selection.head();
 4525        let (cursor_buffer, cursor_buffer_position) =
 4526            buffer.text_anchor_for_position(cursor_position, cx)?;
 4527        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4528        if cursor_buffer != tail_buffer {
 4529            return None;
 4530        }
 4531        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4532        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4533            cx.background_executor()
 4534                .timer(Duration::from_millis(debounce))
 4535                .await;
 4536
 4537            let highlights = if let Some(highlights) = cx
 4538                .update(|cx| {
 4539                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4540                })
 4541                .ok()
 4542                .flatten()
 4543            {
 4544                highlights.await.log_err()
 4545            } else {
 4546                None
 4547            };
 4548
 4549            if let Some(highlights) = highlights {
 4550                this.update(&mut cx, |this, cx| {
 4551                    if this.pending_rename.is_some() {
 4552                        return;
 4553                    }
 4554
 4555                    let buffer_id = cursor_position.buffer_id;
 4556                    let buffer = this.buffer.read(cx);
 4557                    if !buffer
 4558                        .text_anchor_for_position(cursor_position, cx)
 4559                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4560                    {
 4561                        return;
 4562                    }
 4563
 4564                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4565                    let mut write_ranges = Vec::new();
 4566                    let mut read_ranges = Vec::new();
 4567                    for highlight in highlights {
 4568                        for (excerpt_id, excerpt_range) in
 4569                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4570                        {
 4571                            let start = highlight
 4572                                .range
 4573                                .start
 4574                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4575                            let end = highlight
 4576                                .range
 4577                                .end
 4578                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4579                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4580                                continue;
 4581                            }
 4582
 4583                            let range = Anchor {
 4584                                buffer_id,
 4585                                excerpt_id,
 4586                                text_anchor: start,
 4587                                diff_base_anchor: None,
 4588                            }..Anchor {
 4589                                buffer_id,
 4590                                excerpt_id,
 4591                                text_anchor: end,
 4592                                diff_base_anchor: None,
 4593                            };
 4594                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4595                                write_ranges.push(range);
 4596                            } else {
 4597                                read_ranges.push(range);
 4598                            }
 4599                        }
 4600                    }
 4601
 4602                    this.highlight_background::<DocumentHighlightRead>(
 4603                        &read_ranges,
 4604                        |theme| theme.editor_document_highlight_read_background,
 4605                        cx,
 4606                    );
 4607                    this.highlight_background::<DocumentHighlightWrite>(
 4608                        &write_ranges,
 4609                        |theme| theme.editor_document_highlight_write_background,
 4610                        cx,
 4611                    );
 4612                    cx.notify();
 4613                })
 4614                .log_err();
 4615            }
 4616        }));
 4617        None
 4618    }
 4619
 4620    pub fn refresh_inline_completion(
 4621        &mut self,
 4622        debounce: bool,
 4623        user_requested: bool,
 4624        window: &mut Window,
 4625        cx: &mut Context<Self>,
 4626    ) -> Option<()> {
 4627        let provider = self.inline_completion_provider()?;
 4628        let cursor = self.selections.newest_anchor().head();
 4629        let (buffer, cursor_buffer_position) =
 4630            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4631
 4632        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4633            self.discard_inline_completion(false, cx);
 4634            return None;
 4635        }
 4636
 4637        if !user_requested
 4638            && (!self.show_inline_completions
 4639                || !self.should_show_inline_completions_in_buffer(
 4640                    &buffer,
 4641                    cursor_buffer_position,
 4642                    cx,
 4643                )
 4644                || !self.is_focused(window)
 4645                || buffer.read(cx).is_empty())
 4646        {
 4647            self.discard_inline_completion(false, cx);
 4648            return None;
 4649        }
 4650
 4651        self.update_visible_inline_completion(window, cx);
 4652        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4653        Some(())
 4654    }
 4655
 4656    pub fn should_show_inline_completions(&self, cx: &App) -> bool {
 4657        let cursor = self.selections.newest_anchor().head();
 4658        if let Some((buffer, cursor_position)) =
 4659            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4660        {
 4661            self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
 4662        } else {
 4663            false
 4664        }
 4665    }
 4666
 4667    fn inline_completion_preview_mode(&self, cx: &App) -> language::InlineCompletionPreviewMode {
 4668        let cursor = self.selections.newest_anchor().head();
 4669
 4670        self.buffer
 4671            .read(cx)
 4672            .text_anchor_for_position(cursor, cx)
 4673            .map(|(buffer, _)| {
 4674                all_language_settings(buffer.read(cx).file(), cx).inline_completions_preview_mode()
 4675            })
 4676            .unwrap_or_default()
 4677    }
 4678
 4679    fn should_show_inline_completions_in_buffer(
 4680        &self,
 4681        buffer: &Entity<Buffer>,
 4682        buffer_position: language::Anchor,
 4683        cx: &App,
 4684    ) -> bool {
 4685        if !self.snippet_stack.is_empty() {
 4686            return false;
 4687        }
 4688
 4689        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 4690            return false;
 4691        }
 4692
 4693        if let Some(show_inline_completions) = self.show_inline_completions_override {
 4694            show_inline_completions
 4695        } else {
 4696            let buffer = buffer.read(cx);
 4697            self.mode == EditorMode::Full
 4698                && language_settings(
 4699                    buffer.language_at(buffer_position).map(|l| l.name()),
 4700                    buffer.file(),
 4701                    cx,
 4702                )
 4703                .show_inline_completions
 4704        }
 4705    }
 4706
 4707    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4708        let cursor = self.selections.newest_anchor().head();
 4709        if let Some((buffer, cursor_position)) =
 4710            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4711        {
 4712            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4713        } else {
 4714            false
 4715        }
 4716    }
 4717
 4718    fn inline_completions_enabled_in_buffer(
 4719        &self,
 4720        buffer: &Entity<Buffer>,
 4721        buffer_position: language::Anchor,
 4722        cx: &App,
 4723    ) -> bool {
 4724        maybe!({
 4725            let provider = self.inline_completion_provider()?;
 4726            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4727                return Some(false);
 4728            }
 4729            let buffer = buffer.read(cx);
 4730            let Some(file) = buffer.file() else {
 4731                return Some(true);
 4732            };
 4733            let settings = all_language_settings(Some(file), cx);
 4734            Some(settings.inline_completions_enabled_for_path(file.path()))
 4735        })
 4736        .unwrap_or(false)
 4737    }
 4738
 4739    fn cycle_inline_completion(
 4740        &mut self,
 4741        direction: Direction,
 4742        window: &mut Window,
 4743        cx: &mut Context<Self>,
 4744    ) -> Option<()> {
 4745        let provider = self.inline_completion_provider()?;
 4746        let cursor = self.selections.newest_anchor().head();
 4747        let (buffer, cursor_buffer_position) =
 4748            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4749        if !self.show_inline_completions
 4750            || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4751        {
 4752            return None;
 4753        }
 4754
 4755        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4756        self.update_visible_inline_completion(window, cx);
 4757
 4758        Some(())
 4759    }
 4760
 4761    pub fn show_inline_completion(
 4762        &mut self,
 4763        _: &ShowInlineCompletion,
 4764        window: &mut Window,
 4765        cx: &mut Context<Self>,
 4766    ) {
 4767        if !self.has_active_inline_completion() {
 4768            self.refresh_inline_completion(false, true, window, cx);
 4769            return;
 4770        }
 4771
 4772        self.update_visible_inline_completion(window, cx);
 4773    }
 4774
 4775    pub fn display_cursor_names(
 4776        &mut self,
 4777        _: &DisplayCursorNames,
 4778        window: &mut Window,
 4779        cx: &mut Context<Self>,
 4780    ) {
 4781        self.show_cursor_names(window, cx);
 4782    }
 4783
 4784    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4785        self.show_cursor_names = true;
 4786        cx.notify();
 4787        cx.spawn_in(window, |this, mut cx| async move {
 4788            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4789            this.update(&mut cx, |this, cx| {
 4790                this.show_cursor_names = false;
 4791                cx.notify()
 4792            })
 4793            .ok()
 4794        })
 4795        .detach();
 4796    }
 4797
 4798    pub fn next_inline_completion(
 4799        &mut self,
 4800        _: &NextInlineCompletion,
 4801        window: &mut Window,
 4802        cx: &mut Context<Self>,
 4803    ) {
 4804        if self.has_active_inline_completion() {
 4805            self.cycle_inline_completion(Direction::Next, window, cx);
 4806        } else {
 4807            let is_copilot_disabled = self
 4808                .refresh_inline_completion(false, true, window, cx)
 4809                .is_none();
 4810            if is_copilot_disabled {
 4811                cx.propagate();
 4812            }
 4813        }
 4814    }
 4815
 4816    pub fn previous_inline_completion(
 4817        &mut self,
 4818        _: &PreviousInlineCompletion,
 4819        window: &mut Window,
 4820        cx: &mut Context<Self>,
 4821    ) {
 4822        if self.has_active_inline_completion() {
 4823            self.cycle_inline_completion(Direction::Prev, window, cx);
 4824        } else {
 4825            let is_copilot_disabled = self
 4826                .refresh_inline_completion(false, true, window, cx)
 4827                .is_none();
 4828            if is_copilot_disabled {
 4829                cx.propagate();
 4830            }
 4831        }
 4832    }
 4833
 4834    pub fn accept_inline_completion(
 4835        &mut self,
 4836        _: &AcceptInlineCompletion,
 4837        window: &mut Window,
 4838        cx: &mut Context<Self>,
 4839    ) {
 4840        let buffer = self.buffer.read(cx);
 4841        let snapshot = buffer.snapshot(cx);
 4842        let selection = self.selections.newest_adjusted(cx);
 4843        let cursor = selection.head();
 4844        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4845        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4846        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4847        {
 4848            if cursor.column < suggested_indent.len
 4849                && cursor.column <= current_indent.len
 4850                && current_indent.len <= suggested_indent.len
 4851            {
 4852                self.tab(&Default::default(), window, cx);
 4853                return;
 4854            }
 4855        }
 4856
 4857        if self.show_inline_completions_in_menu(cx) {
 4858            self.hide_context_menu(window, cx);
 4859        }
 4860
 4861        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4862            return;
 4863        };
 4864
 4865        self.report_inline_completion_event(true, cx);
 4866
 4867        match &active_inline_completion.completion {
 4868            InlineCompletion::Move { target, .. } => {
 4869                let target = *target;
 4870                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4871                    selections.select_anchor_ranges([target..target]);
 4872                });
 4873            }
 4874            InlineCompletion::Edit { edits, .. } => {
 4875                if let Some(provider) = self.inline_completion_provider() {
 4876                    provider.accept(cx);
 4877                }
 4878
 4879                let snapshot = self.buffer.read(cx).snapshot(cx);
 4880                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4881
 4882                self.buffer.update(cx, |buffer, cx| {
 4883                    buffer.edit(edits.iter().cloned(), None, cx)
 4884                });
 4885
 4886                self.change_selections(None, window, cx, |s| {
 4887                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4888                });
 4889
 4890                self.update_visible_inline_completion(window, cx);
 4891                if self.active_inline_completion.is_none() {
 4892                    self.refresh_inline_completion(true, true, window, cx);
 4893                }
 4894
 4895                cx.notify();
 4896            }
 4897        }
 4898    }
 4899
 4900    pub fn accept_partial_inline_completion(
 4901        &mut self,
 4902        _: &AcceptPartialInlineCompletion,
 4903        window: &mut Window,
 4904        cx: &mut Context<Self>,
 4905    ) {
 4906        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4907            return;
 4908        };
 4909        if self.selections.count() != 1 {
 4910            return;
 4911        }
 4912
 4913        self.report_inline_completion_event(true, cx);
 4914
 4915        match &active_inline_completion.completion {
 4916            InlineCompletion::Move { target, .. } => {
 4917                let target = *target;
 4918                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4919                    selections.select_anchor_ranges([target..target]);
 4920                });
 4921            }
 4922            InlineCompletion::Edit { edits, .. } => {
 4923                // Find an insertion that starts at the cursor position.
 4924                let snapshot = self.buffer.read(cx).snapshot(cx);
 4925                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4926                let insertion = edits.iter().find_map(|(range, text)| {
 4927                    let range = range.to_offset(&snapshot);
 4928                    if range.is_empty() && range.start == cursor_offset {
 4929                        Some(text)
 4930                    } else {
 4931                        None
 4932                    }
 4933                });
 4934
 4935                if let Some(text) = insertion {
 4936                    let mut partial_completion = text
 4937                        .chars()
 4938                        .by_ref()
 4939                        .take_while(|c| c.is_alphabetic())
 4940                        .collect::<String>();
 4941                    if partial_completion.is_empty() {
 4942                        partial_completion = text
 4943                            .chars()
 4944                            .by_ref()
 4945                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4946                            .collect::<String>();
 4947                    }
 4948
 4949                    cx.emit(EditorEvent::InputHandled {
 4950                        utf16_range_to_replace: None,
 4951                        text: partial_completion.clone().into(),
 4952                    });
 4953
 4954                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4955
 4956                    self.refresh_inline_completion(true, true, window, cx);
 4957                    cx.notify();
 4958                } else {
 4959                    self.accept_inline_completion(&Default::default(), window, cx);
 4960                }
 4961            }
 4962        }
 4963    }
 4964
 4965    fn discard_inline_completion(
 4966        &mut self,
 4967        should_report_inline_completion_event: bool,
 4968        cx: &mut Context<Self>,
 4969    ) -> bool {
 4970        if should_report_inline_completion_event {
 4971            self.report_inline_completion_event(false, cx);
 4972        }
 4973
 4974        if let Some(provider) = self.inline_completion_provider() {
 4975            provider.discard(cx);
 4976        }
 4977
 4978        self.take_active_inline_completion(cx)
 4979    }
 4980
 4981    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4982        let Some(provider) = self.inline_completion_provider() else {
 4983            return;
 4984        };
 4985
 4986        let Some((_, buffer, _)) = self
 4987            .buffer
 4988            .read(cx)
 4989            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4990        else {
 4991            return;
 4992        };
 4993
 4994        let extension = buffer
 4995            .read(cx)
 4996            .file()
 4997            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4998
 4999        let event_type = match accepted {
 5000            true => "Edit Prediction Accepted",
 5001            false => "Edit Prediction Discarded",
 5002        };
 5003        telemetry::event!(
 5004            event_type,
 5005            provider = provider.name(),
 5006            suggestion_accepted = accepted,
 5007            file_extension = extension,
 5008        );
 5009    }
 5010
 5011    pub fn has_active_inline_completion(&self) -> bool {
 5012        self.active_inline_completion.is_some()
 5013    }
 5014
 5015    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5016        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5017            return false;
 5018        };
 5019
 5020        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5021        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5022        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5023        true
 5024    }
 5025
 5026    /// Returns true when we're displaying the inline completion popover below the cursor
 5027    /// like we are not previewing and the LSP autocomplete menu is visible
 5028    /// or we are in `when_holding_modifier` mode.
 5029    pub fn inline_completion_visible_in_cursor_popover(
 5030        &self,
 5031        has_completion: bool,
 5032        cx: &App,
 5033    ) -> bool {
 5034        if self.previewing_inline_completion
 5035            || !self.show_inline_completions_in_menu(cx)
 5036            || !self.should_show_inline_completions(cx)
 5037        {
 5038            return false;
 5039        }
 5040
 5041        if self.has_visible_completions_menu() {
 5042            return true;
 5043        }
 5044
 5045        has_completion
 5046            && self.inline_completion_preview_mode(cx)
 5047                == InlineCompletionPreviewMode::WhenHoldingModifier
 5048    }
 5049
 5050    fn update_inline_completion_preview(
 5051        &mut self,
 5052        modifiers: &Modifiers,
 5053        window: &mut Window,
 5054        cx: &mut Context<Self>,
 5055    ) {
 5056        // Moves jump directly without a preview step
 5057        if self
 5058            .active_inline_completion
 5059            .as_ref()
 5060            .map_or(true, |c| c.is_move())
 5061        {
 5062            self.previewing_inline_completion = false;
 5063            cx.notify();
 5064            return;
 5065        }
 5066
 5067        if !self.show_inline_completions_in_menu(cx) {
 5068            return;
 5069        }
 5070
 5071        self.previewing_inline_completion = modifiers.alt;
 5072        self.update_visible_inline_completion(window, cx);
 5073    }
 5074
 5075    fn update_visible_inline_completion(
 5076        &mut self,
 5077        _window: &mut Window,
 5078        cx: &mut Context<Self>,
 5079    ) -> Option<()> {
 5080        let selection = self.selections.newest_anchor();
 5081        let cursor = selection.head();
 5082        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5083        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5084        let excerpt_id = cursor.excerpt_id;
 5085
 5086        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5087        let completions_menu_has_precedence = !show_in_menu
 5088            && (self.context_menu.borrow().is_some()
 5089                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5090        if completions_menu_has_precedence
 5091            || !offset_selection.is_empty()
 5092            || !self.show_inline_completions
 5093            || self
 5094                .active_inline_completion
 5095                .as_ref()
 5096                .map_or(false, |completion| {
 5097                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5098                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5099                    !invalidation_range.contains(&offset_selection.head())
 5100                })
 5101        {
 5102            self.discard_inline_completion(false, cx);
 5103            return None;
 5104        }
 5105
 5106        self.take_active_inline_completion(cx);
 5107        let provider = self.inline_completion_provider()?;
 5108
 5109        let (buffer, cursor_buffer_position) =
 5110            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5111
 5112        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5113        let edits = inline_completion
 5114            .edits
 5115            .into_iter()
 5116            .flat_map(|(range, new_text)| {
 5117                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5118                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5119                Some((start..end, new_text))
 5120            })
 5121            .collect::<Vec<_>>();
 5122        if edits.is_empty() {
 5123            return None;
 5124        }
 5125
 5126        let first_edit_start = edits.first().unwrap().0.start;
 5127        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5128        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5129
 5130        let last_edit_end = edits.last().unwrap().0.end;
 5131        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5132        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5133
 5134        let cursor_row = cursor.to_point(&multibuffer).row;
 5135
 5136        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5137
 5138        let mut inlay_ids = Vec::new();
 5139        let invalidation_row_range;
 5140        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5141            Some(cursor_row..edit_end_row)
 5142        } else if cursor_row > edit_end_row {
 5143            Some(edit_start_row..cursor_row)
 5144        } else {
 5145            None
 5146        };
 5147        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5148            invalidation_row_range = move_invalidation_row_range;
 5149            let target = first_edit_start;
 5150            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5151            // TODO: Base this off of TreeSitter or word boundaries?
 5152            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5153                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5154                Bias::Left,
 5155            ));
 5156            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5157                Point::new(target_point.row, target_point.column + 20),
 5158                Bias::Right,
 5159            ));
 5160            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5161            InlineCompletion::Move {
 5162                target,
 5163                range_around_target,
 5164                snapshot,
 5165            }
 5166        } else {
 5167            if !self.inline_completion_visible_in_cursor_popover(true, cx) {
 5168                if edits
 5169                    .iter()
 5170                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5171                {
 5172                    let mut inlays = Vec::new();
 5173                    for (range, new_text) in &edits {
 5174                        let inlay = Inlay::inline_completion(
 5175                            post_inc(&mut self.next_inlay_id),
 5176                            range.start,
 5177                            new_text.as_str(),
 5178                        );
 5179                        inlay_ids.push(inlay.id);
 5180                        inlays.push(inlay);
 5181                    }
 5182
 5183                    self.splice_inlays(&[], inlays, cx);
 5184                } else {
 5185                    let background_color = cx.theme().status().deleted_background;
 5186                    self.highlight_text::<InlineCompletionHighlight>(
 5187                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5188                        HighlightStyle {
 5189                            background_color: Some(background_color),
 5190                            ..Default::default()
 5191                        },
 5192                        cx,
 5193                    );
 5194                }
 5195            }
 5196
 5197            invalidation_row_range = edit_start_row..edit_end_row;
 5198
 5199            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5200                if provider.show_tab_accept_marker() {
 5201                    EditDisplayMode::TabAccept(self.previewing_inline_completion)
 5202                } else {
 5203                    EditDisplayMode::Inline
 5204                }
 5205            } else {
 5206                EditDisplayMode::DiffPopover
 5207            };
 5208
 5209            InlineCompletion::Edit {
 5210                edits,
 5211                edit_preview: inline_completion.edit_preview,
 5212                display_mode,
 5213                snapshot,
 5214            }
 5215        };
 5216
 5217        let invalidation_range = multibuffer
 5218            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5219            ..multibuffer.anchor_after(Point::new(
 5220                invalidation_row_range.end,
 5221                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5222            ));
 5223
 5224        self.stale_inline_completion_in_menu = None;
 5225        self.active_inline_completion = Some(InlineCompletionState {
 5226            inlay_ids,
 5227            completion,
 5228            invalidation_range,
 5229        });
 5230
 5231        cx.notify();
 5232
 5233        Some(())
 5234    }
 5235
 5236    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5237        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5238    }
 5239
 5240    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5241        let by_provider = matches!(
 5242            self.menu_inline_completions_policy,
 5243            MenuInlineCompletionsPolicy::ByProvider
 5244        );
 5245
 5246        by_provider
 5247            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5248            && self
 5249                .inline_completion_provider()
 5250                .map_or(false, |provider| provider.show_completions_in_menu())
 5251    }
 5252
 5253    fn render_code_actions_indicator(
 5254        &self,
 5255        _style: &EditorStyle,
 5256        row: DisplayRow,
 5257        is_active: bool,
 5258        cx: &mut Context<Self>,
 5259    ) -> Option<IconButton> {
 5260        if self.available_code_actions.is_some() {
 5261            Some(
 5262                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5263                    .shape(ui::IconButtonShape::Square)
 5264                    .icon_size(IconSize::XSmall)
 5265                    .icon_color(Color::Muted)
 5266                    .toggle_state(is_active)
 5267                    .tooltip({
 5268                        let focus_handle = self.focus_handle.clone();
 5269                        move |window, cx| {
 5270                            Tooltip::for_action_in(
 5271                                "Toggle Code Actions",
 5272                                &ToggleCodeActions {
 5273                                    deployed_from_indicator: None,
 5274                                },
 5275                                &focus_handle,
 5276                                window,
 5277                                cx,
 5278                            )
 5279                        }
 5280                    })
 5281                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5282                        window.focus(&editor.focus_handle(cx));
 5283                        editor.toggle_code_actions(
 5284                            &ToggleCodeActions {
 5285                                deployed_from_indicator: Some(row),
 5286                            },
 5287                            window,
 5288                            cx,
 5289                        );
 5290                    })),
 5291            )
 5292        } else {
 5293            None
 5294        }
 5295    }
 5296
 5297    fn clear_tasks(&mut self) {
 5298        self.tasks.clear()
 5299    }
 5300
 5301    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5302        if self.tasks.insert(key, value).is_some() {
 5303            // This case should hopefully be rare, but just in case...
 5304            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5305        }
 5306    }
 5307
 5308    fn build_tasks_context(
 5309        project: &Entity<Project>,
 5310        buffer: &Entity<Buffer>,
 5311        buffer_row: u32,
 5312        tasks: &Arc<RunnableTasks>,
 5313        cx: &mut Context<Self>,
 5314    ) -> Task<Option<task::TaskContext>> {
 5315        let position = Point::new(buffer_row, tasks.column);
 5316        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5317        let location = Location {
 5318            buffer: buffer.clone(),
 5319            range: range_start..range_start,
 5320        };
 5321        // Fill in the environmental variables from the tree-sitter captures
 5322        let mut captured_task_variables = TaskVariables::default();
 5323        for (capture_name, value) in tasks.extra_variables.clone() {
 5324            captured_task_variables.insert(
 5325                task::VariableName::Custom(capture_name.into()),
 5326                value.clone(),
 5327            );
 5328        }
 5329        project.update(cx, |project, cx| {
 5330            project.task_store().update(cx, |task_store, cx| {
 5331                task_store.task_context_for_location(captured_task_variables, location, cx)
 5332            })
 5333        })
 5334    }
 5335
 5336    pub fn spawn_nearest_task(
 5337        &mut self,
 5338        action: &SpawnNearestTask,
 5339        window: &mut Window,
 5340        cx: &mut Context<Self>,
 5341    ) {
 5342        let Some((workspace, _)) = self.workspace.clone() else {
 5343            return;
 5344        };
 5345        let Some(project) = self.project.clone() else {
 5346            return;
 5347        };
 5348
 5349        // Try to find a closest, enclosing node using tree-sitter that has a
 5350        // task
 5351        let Some((buffer, buffer_row, tasks)) = self
 5352            .find_enclosing_node_task(cx)
 5353            // Or find the task that's closest in row-distance.
 5354            .or_else(|| self.find_closest_task(cx))
 5355        else {
 5356            return;
 5357        };
 5358
 5359        let reveal_strategy = action.reveal;
 5360        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5361        cx.spawn_in(window, |_, mut cx| async move {
 5362            let context = task_context.await?;
 5363            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5364
 5365            let resolved = resolved_task.resolved.as_mut()?;
 5366            resolved.reveal = reveal_strategy;
 5367
 5368            workspace
 5369                .update(&mut cx, |workspace, cx| {
 5370                    workspace::tasks::schedule_resolved_task(
 5371                        workspace,
 5372                        task_source_kind,
 5373                        resolved_task,
 5374                        false,
 5375                        cx,
 5376                    );
 5377                })
 5378                .ok()
 5379        })
 5380        .detach();
 5381    }
 5382
 5383    fn find_closest_task(
 5384        &mut self,
 5385        cx: &mut Context<Self>,
 5386    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5387        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5388
 5389        let ((buffer_id, row), tasks) = self
 5390            .tasks
 5391            .iter()
 5392            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5393
 5394        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5395        let tasks = Arc::new(tasks.to_owned());
 5396        Some((buffer, *row, tasks))
 5397    }
 5398
 5399    fn find_enclosing_node_task(
 5400        &mut self,
 5401        cx: &mut Context<Self>,
 5402    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5403        let snapshot = self.buffer.read(cx).snapshot(cx);
 5404        let offset = self.selections.newest::<usize>(cx).head();
 5405        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5406        let buffer_id = excerpt.buffer().remote_id();
 5407
 5408        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5409        let mut cursor = layer.node().walk();
 5410
 5411        while cursor.goto_first_child_for_byte(offset).is_some() {
 5412            if cursor.node().end_byte() == offset {
 5413                cursor.goto_next_sibling();
 5414            }
 5415        }
 5416
 5417        // Ascend to the smallest ancestor that contains the range and has a task.
 5418        loop {
 5419            let node = cursor.node();
 5420            let node_range = node.byte_range();
 5421            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5422
 5423            // Check if this node contains our offset
 5424            if node_range.start <= offset && node_range.end >= offset {
 5425                // If it contains offset, check for task
 5426                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5427                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5428                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5429                }
 5430            }
 5431
 5432            if !cursor.goto_parent() {
 5433                break;
 5434            }
 5435        }
 5436        None
 5437    }
 5438
 5439    fn render_run_indicator(
 5440        &self,
 5441        _style: &EditorStyle,
 5442        is_active: bool,
 5443        row: DisplayRow,
 5444        cx: &mut Context<Self>,
 5445    ) -> IconButton {
 5446        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5447            .shape(ui::IconButtonShape::Square)
 5448            .icon_size(IconSize::XSmall)
 5449            .icon_color(Color::Muted)
 5450            .toggle_state(is_active)
 5451            .on_click(cx.listener(move |editor, _e, window, cx| {
 5452                window.focus(&editor.focus_handle(cx));
 5453                editor.toggle_code_actions(
 5454                    &ToggleCodeActions {
 5455                        deployed_from_indicator: Some(row),
 5456                    },
 5457                    window,
 5458                    cx,
 5459                );
 5460            }))
 5461    }
 5462
 5463    pub fn context_menu_visible(&self) -> bool {
 5464        !self.previewing_inline_completion
 5465            && self
 5466                .context_menu
 5467                .borrow()
 5468                .as_ref()
 5469                .map_or(false, |menu| menu.visible())
 5470    }
 5471
 5472    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5473        self.context_menu
 5474            .borrow()
 5475            .as_ref()
 5476            .map(|menu| menu.origin())
 5477    }
 5478
 5479    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5480        px(30.)
 5481    }
 5482
 5483    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5484        if self.read_only(cx) {
 5485            cx.theme().players().read_only()
 5486        } else {
 5487            self.style.as_ref().unwrap().local_player
 5488        }
 5489    }
 5490
 5491    #[allow(clippy::too_many_arguments)]
 5492    fn render_edit_prediction_cursor_popover(
 5493        &self,
 5494        min_width: Pixels,
 5495        max_width: Pixels,
 5496        cursor_point: Point,
 5497        start_row: DisplayRow,
 5498        line_layouts: &[LineWithInvisibles],
 5499        style: &EditorStyle,
 5500        accept_keystroke: &gpui::Keystroke,
 5501        window: &Window,
 5502        cx: &mut Context<Editor>,
 5503    ) -> Option<AnyElement> {
 5504        let provider = self.inline_completion_provider.as_ref()?;
 5505
 5506        if provider.provider.needs_terms_acceptance(cx) {
 5507            return Some(
 5508                h_flex()
 5509                    .h(self.edit_prediction_cursor_popover_height())
 5510                    .min_w(min_width)
 5511                    .flex_1()
 5512                    .px_2()
 5513                    .gap_3()
 5514                    .elevation_2(cx)
 5515                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5516                    .id("accept-terms")
 5517                    .cursor_pointer()
 5518                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5519                    .on_click(cx.listener(|this, _event, window, cx| {
 5520                        cx.stop_propagation();
 5521                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5522                        window.dispatch_action(
 5523                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5524                            cx,
 5525                        );
 5526                    }))
 5527                    .child(
 5528                        h_flex()
 5529                            .w_full()
 5530                            .gap_2()
 5531                            .child(Icon::new(IconName::ZedPredict))
 5532                            .child(Label::new("Accept Terms of Service"))
 5533                            .child(div().w_full())
 5534                            .child(
 5535                                Icon::new(IconName::ArrowUpRight)
 5536                                    .color(Color::Muted)
 5537                                    .size(IconSize::Small),
 5538                            )
 5539                            .into_any_element(),
 5540                    )
 5541                    .into_any(),
 5542            );
 5543        }
 5544
 5545        let is_refreshing = provider.provider.is_refreshing(cx);
 5546
 5547        fn pending_completion_container() -> Div {
 5548            h_flex()
 5549                .h_full()
 5550                .flex_1()
 5551                .gap_2()
 5552                .child(Icon::new(IconName::ZedPredict))
 5553        }
 5554
 5555        let completion = match &self.active_inline_completion {
 5556            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5557                completion,
 5558                cursor_point,
 5559                start_row,
 5560                line_layouts,
 5561                style,
 5562                cx,
 5563            )?,
 5564
 5565            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5566                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5567                    stale_completion,
 5568                    cursor_point,
 5569                    start_row,
 5570                    line_layouts,
 5571                    style,
 5572                    cx,
 5573                )?,
 5574
 5575                None => {
 5576                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5577                }
 5578            },
 5579
 5580            None => pending_completion_container().child(Label::new("No Prediction")),
 5581        };
 5582
 5583        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5584        let completion = completion.font(buffer_font.clone());
 5585
 5586        let completion = if is_refreshing {
 5587            completion
 5588                .with_animation(
 5589                    "loading-completion",
 5590                    Animation::new(Duration::from_secs(2))
 5591                        .repeat()
 5592                        .with_easing(pulsating_between(0.4, 0.8)),
 5593                    |label, delta| label.opacity(delta),
 5594                )
 5595                .into_any_element()
 5596        } else {
 5597            completion.into_any_element()
 5598        };
 5599
 5600        let has_completion = self.active_inline_completion.is_some();
 5601
 5602        let is_move = self
 5603            .active_inline_completion
 5604            .as_ref()
 5605            .map_or(false, |c| c.is_move());
 5606
 5607        let modifier_color = if !has_completion {
 5608            Color::Muted
 5609        } else if window.modifiers() == accept_keystroke.modifiers {
 5610            Color::Accent
 5611        } else {
 5612            Color::Default
 5613        };
 5614
 5615        Some(
 5616            h_flex()
 5617                .h(self.edit_prediction_cursor_popover_height())
 5618                .min_w(min_width)
 5619                .max_w(max_width)
 5620                .flex_1()
 5621                .px_2()
 5622                .elevation_2(cx)
 5623                .child(completion)
 5624                .child(ui::Divider::vertical())
 5625                .child(
 5626                    h_flex()
 5627                        .h_full()
 5628                        .gap_1()
 5629                        .pl_2()
 5630                        .child(h_flex().font(buffer_font.clone()).gap_1().children(
 5631                            ui::render_modifiers(
 5632                                &accept_keystroke.modifiers,
 5633                                PlatformStyle::platform(),
 5634                                Some(modifier_color),
 5635                                !is_move,
 5636                            ),
 5637                        ))
 5638                        .child(if is_move {
 5639                            div()
 5640                                .child(ui::Key::new(&accept_keystroke.key, None))
 5641                                .font(buffer_font.clone())
 5642                                .into_any()
 5643                        } else {
 5644                            Label::new("Preview").into_any_element()
 5645                        })
 5646                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5647                )
 5648                .into_any(),
 5649        )
 5650    }
 5651
 5652    fn render_edit_prediction_cursor_popover_preview(
 5653        &self,
 5654        completion: &InlineCompletionState,
 5655        cursor_point: Point,
 5656        start_row: DisplayRow,
 5657        line_layouts: &[LineWithInvisibles],
 5658        style: &EditorStyle,
 5659        cx: &mut Context<Editor>,
 5660    ) -> Option<Div> {
 5661        use text::ToPoint as _;
 5662
 5663        fn render_relative_row_jump(
 5664            prefix: impl Into<String>,
 5665            current_row: u32,
 5666            target_row: u32,
 5667        ) -> Div {
 5668            let (row_diff, arrow) = if target_row < current_row {
 5669                (current_row - target_row, IconName::ArrowUp)
 5670            } else {
 5671                (target_row - current_row, IconName::ArrowDown)
 5672            };
 5673
 5674            h_flex()
 5675                .child(
 5676                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5677                        .color(Color::Muted)
 5678                        .size(LabelSize::Small),
 5679                )
 5680                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5681        }
 5682
 5683        match &completion.completion {
 5684            InlineCompletion::Edit {
 5685                edits,
 5686                edit_preview,
 5687                snapshot,
 5688                display_mode: _,
 5689            } => {
 5690                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5691
 5692                let highlighted_edits = crate::inline_completion_edit_text(
 5693                    &snapshot,
 5694                    &edits,
 5695                    edit_preview.as_ref()?,
 5696                    true,
 5697                    cx,
 5698                );
 5699
 5700                let len_total = highlighted_edits.text.len();
 5701                let first_line = &highlighted_edits.text
 5702                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5703                let first_line_len = first_line.len();
 5704
 5705                let first_highlight_start = highlighted_edits
 5706                    .highlights
 5707                    .first()
 5708                    .map_or(0, |(range, _)| range.start);
 5709                let drop_prefix_len = first_line
 5710                    .char_indices()
 5711                    .find(|(_, c)| !c.is_whitespace())
 5712                    .map_or(first_highlight_start, |(ix, _)| {
 5713                        ix.min(first_highlight_start)
 5714                    });
 5715
 5716                let preview_text = &first_line[drop_prefix_len..];
 5717                let preview_len = preview_text.len();
 5718                let highlights = highlighted_edits
 5719                    .highlights
 5720                    .into_iter()
 5721                    .take_until(|(range, _)| range.start > first_line_len)
 5722                    .map(|(range, style)| {
 5723                        (
 5724                            range.start - drop_prefix_len
 5725                                ..(range.end - drop_prefix_len).min(preview_len),
 5726                            style,
 5727                        )
 5728                    });
 5729
 5730                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5731                    .with_highlights(&style.text, highlights);
 5732
 5733                let preview = h_flex()
 5734                    .gap_1()
 5735                    .child(styled_text)
 5736                    .when(len_total > first_line_len, |parent| parent.child(""));
 5737
 5738                let left = if first_edit_row != cursor_point.row {
 5739                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5740                        .into_any_element()
 5741                } else {
 5742                    Icon::new(IconName::ZedPredict).into_any_element()
 5743                };
 5744
 5745                Some(
 5746                    h_flex()
 5747                        .h_full()
 5748                        .flex_1()
 5749                        .gap_2()
 5750                        .pr_1()
 5751                        .overflow_x_hidden()
 5752                        .child(left)
 5753                        .child(preview),
 5754                )
 5755            }
 5756
 5757            InlineCompletion::Move {
 5758                target,
 5759                range_around_target,
 5760                snapshot,
 5761            } => {
 5762                let highlighted_text = snapshot.highlighted_text_for_range(
 5763                    range_around_target.clone(),
 5764                    None,
 5765                    &style.syntax,
 5766                );
 5767                let cursor_color = self.current_user_player_color(cx).cursor;
 5768
 5769                let start_point = range_around_target.start.to_point(&snapshot);
 5770                let end_point = range_around_target.end.to_point(&snapshot);
 5771                let target_point = target.text_anchor.to_point(&snapshot);
 5772
 5773                let cursor_relative_position = line_layouts
 5774                    .get(start_point.row.saturating_sub(start_row.0) as usize)
 5775                    .map(|line| {
 5776                        let start_column_x = line.x_for_index(start_point.column as usize);
 5777                        let target_column_x = line.x_for_index(target_point.column as usize);
 5778                        target_column_x - start_column_x
 5779                    });
 5780
 5781                let fade_before = start_point.column > 0;
 5782                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5783
 5784                let background = cx.theme().colors().elevated_surface_background;
 5785
 5786                Some(
 5787                    h_flex()
 5788                        .gap_3()
 5789                        .flex_1()
 5790                        .child(render_relative_row_jump(
 5791                            "Jump ",
 5792                            cursor_point.row,
 5793                            target.text_anchor.to_point(&snapshot).row,
 5794                        ))
 5795                        .when(!highlighted_text.text.is_empty(), |parent| {
 5796                            parent.child(
 5797                                h_flex()
 5798                                    .relative()
 5799                                    .child(highlighted_text.to_styled_text(&style.text))
 5800                                    .when(fade_before, |parent| {
 5801                                        parent.child(
 5802                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5803                                                linear_gradient(
 5804                                                    90.,
 5805                                                    linear_color_stop(background, 0.),
 5806                                                    linear_color_stop(background.opacity(0.), 1.),
 5807                                                ),
 5808                                            ),
 5809                                        )
 5810                                    })
 5811                                    .when(fade_after, |parent| {
 5812                                        parent.child(
 5813                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5814                                                linear_gradient(
 5815                                                    -90.,
 5816                                                    linear_color_stop(background, 0.),
 5817                                                    linear_color_stop(background.opacity(0.), 1.),
 5818                                                ),
 5819                                            ),
 5820                                        )
 5821                                    })
 5822                                    .when_some(cursor_relative_position, |parent, position| {
 5823                                        parent.child(
 5824                                            div()
 5825                                                .w(px(2.))
 5826                                                .h_full()
 5827                                                .bg(cursor_color)
 5828                                                .absolute()
 5829                                                .top_0()
 5830                                                .left(position),
 5831                                        )
 5832                                    }),
 5833                            )
 5834                        }),
 5835                )
 5836            }
 5837        }
 5838    }
 5839
 5840    fn render_context_menu(
 5841        &self,
 5842        style: &EditorStyle,
 5843        max_height_in_lines: u32,
 5844        y_flipped: bool,
 5845        window: &mut Window,
 5846        cx: &mut Context<Editor>,
 5847    ) -> Option<AnyElement> {
 5848        let menu = self.context_menu.borrow();
 5849        let menu = menu.as_ref()?;
 5850        if !menu.visible() {
 5851            return None;
 5852        };
 5853        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5854    }
 5855
 5856    fn render_context_menu_aside(
 5857        &self,
 5858        style: &EditorStyle,
 5859        max_size: Size<Pixels>,
 5860        cx: &mut Context<Editor>,
 5861    ) -> Option<AnyElement> {
 5862        self.context_menu.borrow().as_ref().and_then(|menu| {
 5863            if menu.visible() {
 5864                menu.render_aside(
 5865                    style,
 5866                    max_size,
 5867                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5868                    cx,
 5869                )
 5870            } else {
 5871                None
 5872            }
 5873        })
 5874    }
 5875
 5876    fn hide_context_menu(
 5877        &mut self,
 5878        window: &mut Window,
 5879        cx: &mut Context<Self>,
 5880    ) -> Option<CodeContextMenu> {
 5881        cx.notify();
 5882        self.completion_tasks.clear();
 5883        let context_menu = self.context_menu.borrow_mut().take();
 5884        self.stale_inline_completion_in_menu.take();
 5885        self.update_visible_inline_completion(window, cx);
 5886        context_menu
 5887    }
 5888
 5889    fn show_snippet_choices(
 5890        &mut self,
 5891        choices: &Vec<String>,
 5892        selection: Range<Anchor>,
 5893        cx: &mut Context<Self>,
 5894    ) {
 5895        if selection.start.buffer_id.is_none() {
 5896            return;
 5897        }
 5898        let buffer_id = selection.start.buffer_id.unwrap();
 5899        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5900        let id = post_inc(&mut self.next_completion_id);
 5901
 5902        if let Some(buffer) = buffer {
 5903            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5904                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5905            ));
 5906        }
 5907    }
 5908
 5909    pub fn insert_snippet(
 5910        &mut self,
 5911        insertion_ranges: &[Range<usize>],
 5912        snippet: Snippet,
 5913        window: &mut Window,
 5914        cx: &mut Context<Self>,
 5915    ) -> Result<()> {
 5916        struct Tabstop<T> {
 5917            is_end_tabstop: bool,
 5918            ranges: Vec<Range<T>>,
 5919            choices: Option<Vec<String>>,
 5920        }
 5921
 5922        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5923            let snippet_text: Arc<str> = snippet.text.clone().into();
 5924            buffer.edit(
 5925                insertion_ranges
 5926                    .iter()
 5927                    .cloned()
 5928                    .map(|range| (range, snippet_text.clone())),
 5929                Some(AutoindentMode::EachLine),
 5930                cx,
 5931            );
 5932
 5933            let snapshot = &*buffer.read(cx);
 5934            let snippet = &snippet;
 5935            snippet
 5936                .tabstops
 5937                .iter()
 5938                .map(|tabstop| {
 5939                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5940                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5941                    });
 5942                    let mut tabstop_ranges = tabstop
 5943                        .ranges
 5944                        .iter()
 5945                        .flat_map(|tabstop_range| {
 5946                            let mut delta = 0_isize;
 5947                            insertion_ranges.iter().map(move |insertion_range| {
 5948                                let insertion_start = insertion_range.start as isize + delta;
 5949                                delta +=
 5950                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5951
 5952                                let start = ((insertion_start + tabstop_range.start) as usize)
 5953                                    .min(snapshot.len());
 5954                                let end = ((insertion_start + tabstop_range.end) as usize)
 5955                                    .min(snapshot.len());
 5956                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5957                            })
 5958                        })
 5959                        .collect::<Vec<_>>();
 5960                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5961
 5962                    Tabstop {
 5963                        is_end_tabstop,
 5964                        ranges: tabstop_ranges,
 5965                        choices: tabstop.choices.clone(),
 5966                    }
 5967                })
 5968                .collect::<Vec<_>>()
 5969        });
 5970        if let Some(tabstop) = tabstops.first() {
 5971            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5972                s.select_ranges(tabstop.ranges.iter().cloned());
 5973            });
 5974
 5975            if let Some(choices) = &tabstop.choices {
 5976                if let Some(selection) = tabstop.ranges.first() {
 5977                    self.show_snippet_choices(choices, selection.clone(), cx)
 5978                }
 5979            }
 5980
 5981            // If we're already at the last tabstop and it's at the end of the snippet,
 5982            // we're done, we don't need to keep the state around.
 5983            if !tabstop.is_end_tabstop {
 5984                let choices = tabstops
 5985                    .iter()
 5986                    .map(|tabstop| tabstop.choices.clone())
 5987                    .collect();
 5988
 5989                let ranges = tabstops
 5990                    .into_iter()
 5991                    .map(|tabstop| tabstop.ranges)
 5992                    .collect::<Vec<_>>();
 5993
 5994                self.snippet_stack.push(SnippetState {
 5995                    active_index: 0,
 5996                    ranges,
 5997                    choices,
 5998                });
 5999            }
 6000
 6001            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6002            if self.autoclose_regions.is_empty() {
 6003                let snapshot = self.buffer.read(cx).snapshot(cx);
 6004                for selection in &mut self.selections.all::<Point>(cx) {
 6005                    let selection_head = selection.head();
 6006                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6007                        continue;
 6008                    };
 6009
 6010                    let mut bracket_pair = None;
 6011                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6012                    let prev_chars = snapshot
 6013                        .reversed_chars_at(selection_head)
 6014                        .collect::<String>();
 6015                    for (pair, enabled) in scope.brackets() {
 6016                        if enabled
 6017                            && pair.close
 6018                            && prev_chars.starts_with(pair.start.as_str())
 6019                            && next_chars.starts_with(pair.end.as_str())
 6020                        {
 6021                            bracket_pair = Some(pair.clone());
 6022                            break;
 6023                        }
 6024                    }
 6025                    if let Some(pair) = bracket_pair {
 6026                        let start = snapshot.anchor_after(selection_head);
 6027                        let end = snapshot.anchor_after(selection_head);
 6028                        self.autoclose_regions.push(AutocloseRegion {
 6029                            selection_id: selection.id,
 6030                            range: start..end,
 6031                            pair,
 6032                        });
 6033                    }
 6034                }
 6035            }
 6036        }
 6037        Ok(())
 6038    }
 6039
 6040    pub fn move_to_next_snippet_tabstop(
 6041        &mut self,
 6042        window: &mut Window,
 6043        cx: &mut Context<Self>,
 6044    ) -> bool {
 6045        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6046    }
 6047
 6048    pub fn move_to_prev_snippet_tabstop(
 6049        &mut self,
 6050        window: &mut Window,
 6051        cx: &mut Context<Self>,
 6052    ) -> bool {
 6053        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6054    }
 6055
 6056    pub fn move_to_snippet_tabstop(
 6057        &mut self,
 6058        bias: Bias,
 6059        window: &mut Window,
 6060        cx: &mut Context<Self>,
 6061    ) -> bool {
 6062        if let Some(mut snippet) = self.snippet_stack.pop() {
 6063            match bias {
 6064                Bias::Left => {
 6065                    if snippet.active_index > 0 {
 6066                        snippet.active_index -= 1;
 6067                    } else {
 6068                        self.snippet_stack.push(snippet);
 6069                        return false;
 6070                    }
 6071                }
 6072                Bias::Right => {
 6073                    if snippet.active_index + 1 < snippet.ranges.len() {
 6074                        snippet.active_index += 1;
 6075                    } else {
 6076                        self.snippet_stack.push(snippet);
 6077                        return false;
 6078                    }
 6079                }
 6080            }
 6081            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6082                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6083                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6084                });
 6085
 6086                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6087                    if let Some(selection) = current_ranges.first() {
 6088                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6089                    }
 6090                }
 6091
 6092                // If snippet state is not at the last tabstop, push it back on the stack
 6093                if snippet.active_index + 1 < snippet.ranges.len() {
 6094                    self.snippet_stack.push(snippet);
 6095                }
 6096                return true;
 6097            }
 6098        }
 6099
 6100        false
 6101    }
 6102
 6103    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6104        self.transact(window, cx, |this, window, cx| {
 6105            this.select_all(&SelectAll, window, cx);
 6106            this.insert("", window, cx);
 6107        });
 6108    }
 6109
 6110    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6111        self.transact(window, cx, |this, window, cx| {
 6112            this.select_autoclose_pair(window, cx);
 6113            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6114            if !this.linked_edit_ranges.is_empty() {
 6115                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6116                let snapshot = this.buffer.read(cx).snapshot(cx);
 6117
 6118                for selection in selections.iter() {
 6119                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6120                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6121                    if selection_start.buffer_id != selection_end.buffer_id {
 6122                        continue;
 6123                    }
 6124                    if let Some(ranges) =
 6125                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6126                    {
 6127                        for (buffer, entries) in ranges {
 6128                            linked_ranges.entry(buffer).or_default().extend(entries);
 6129                        }
 6130                    }
 6131                }
 6132            }
 6133
 6134            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6135            if !this.selections.line_mode {
 6136                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6137                for selection in &mut selections {
 6138                    if selection.is_empty() {
 6139                        let old_head = selection.head();
 6140                        let mut new_head =
 6141                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6142                                .to_point(&display_map);
 6143                        if let Some((buffer, line_buffer_range)) = display_map
 6144                            .buffer_snapshot
 6145                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6146                        {
 6147                            let indent_size =
 6148                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6149                            let indent_len = match indent_size.kind {
 6150                                IndentKind::Space => {
 6151                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6152                                }
 6153                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6154                            };
 6155                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6156                                let indent_len = indent_len.get();
 6157                                new_head = cmp::min(
 6158                                    new_head,
 6159                                    MultiBufferPoint::new(
 6160                                        old_head.row,
 6161                                        ((old_head.column - 1) / indent_len) * indent_len,
 6162                                    ),
 6163                                );
 6164                            }
 6165                        }
 6166
 6167                        selection.set_head(new_head, SelectionGoal::None);
 6168                    }
 6169                }
 6170            }
 6171
 6172            this.signature_help_state.set_backspace_pressed(true);
 6173            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6174                s.select(selections)
 6175            });
 6176            this.insert("", window, cx);
 6177            let empty_str: Arc<str> = Arc::from("");
 6178            for (buffer, edits) in linked_ranges {
 6179                let snapshot = buffer.read(cx).snapshot();
 6180                use text::ToPoint as TP;
 6181
 6182                let edits = edits
 6183                    .into_iter()
 6184                    .map(|range| {
 6185                        let end_point = TP::to_point(&range.end, &snapshot);
 6186                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6187
 6188                        if end_point == start_point {
 6189                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6190                                .saturating_sub(1);
 6191                            start_point =
 6192                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6193                        };
 6194
 6195                        (start_point..end_point, empty_str.clone())
 6196                    })
 6197                    .sorted_by_key(|(range, _)| range.start)
 6198                    .collect::<Vec<_>>();
 6199                buffer.update(cx, |this, cx| {
 6200                    this.edit(edits, None, cx);
 6201                })
 6202            }
 6203            this.refresh_inline_completion(true, false, window, cx);
 6204            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6205        });
 6206    }
 6207
 6208    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6209        self.transact(window, cx, |this, window, cx| {
 6210            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6211                let line_mode = s.line_mode;
 6212                s.move_with(|map, selection| {
 6213                    if selection.is_empty() && !line_mode {
 6214                        let cursor = movement::right(map, selection.head());
 6215                        selection.end = cursor;
 6216                        selection.reversed = true;
 6217                        selection.goal = SelectionGoal::None;
 6218                    }
 6219                })
 6220            });
 6221            this.insert("", window, cx);
 6222            this.refresh_inline_completion(true, false, window, cx);
 6223        });
 6224    }
 6225
 6226    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6227        if self.move_to_prev_snippet_tabstop(window, cx) {
 6228            return;
 6229        }
 6230
 6231        self.outdent(&Outdent, window, cx);
 6232    }
 6233
 6234    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6235        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6236            return;
 6237        }
 6238
 6239        let mut selections = self.selections.all_adjusted(cx);
 6240        let buffer = self.buffer.read(cx);
 6241        let snapshot = buffer.snapshot(cx);
 6242        let rows_iter = selections.iter().map(|s| s.head().row);
 6243        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6244
 6245        let mut edits = Vec::new();
 6246        let mut prev_edited_row = 0;
 6247        let mut row_delta = 0;
 6248        for selection in &mut selections {
 6249            if selection.start.row != prev_edited_row {
 6250                row_delta = 0;
 6251            }
 6252            prev_edited_row = selection.end.row;
 6253
 6254            // If the selection is non-empty, then increase the indentation of the selected lines.
 6255            if !selection.is_empty() {
 6256                row_delta =
 6257                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6258                continue;
 6259            }
 6260
 6261            // If the selection is empty and the cursor is in the leading whitespace before the
 6262            // suggested indentation, then auto-indent the line.
 6263            let cursor = selection.head();
 6264            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6265            if let Some(suggested_indent) =
 6266                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6267            {
 6268                if cursor.column < suggested_indent.len
 6269                    && cursor.column <= current_indent.len
 6270                    && current_indent.len <= suggested_indent.len
 6271                {
 6272                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6273                    selection.end = selection.start;
 6274                    if row_delta == 0 {
 6275                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6276                            cursor.row,
 6277                            current_indent,
 6278                            suggested_indent,
 6279                        ));
 6280                        row_delta = suggested_indent.len - current_indent.len;
 6281                    }
 6282                    continue;
 6283                }
 6284            }
 6285
 6286            // Otherwise, insert a hard or soft tab.
 6287            let settings = buffer.settings_at(cursor, cx);
 6288            let tab_size = if settings.hard_tabs {
 6289                IndentSize::tab()
 6290            } else {
 6291                let tab_size = settings.tab_size.get();
 6292                let char_column = snapshot
 6293                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6294                    .flat_map(str::chars)
 6295                    .count()
 6296                    + row_delta as usize;
 6297                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6298                IndentSize::spaces(chars_to_next_tab_stop)
 6299            };
 6300            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6301            selection.end = selection.start;
 6302            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6303            row_delta += tab_size.len;
 6304        }
 6305
 6306        self.transact(window, cx, |this, window, cx| {
 6307            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6308            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6309                s.select(selections)
 6310            });
 6311            this.refresh_inline_completion(true, false, window, cx);
 6312        });
 6313    }
 6314
 6315    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6316        if self.read_only(cx) {
 6317            return;
 6318        }
 6319        let mut selections = self.selections.all::<Point>(cx);
 6320        let mut prev_edited_row = 0;
 6321        let mut row_delta = 0;
 6322        let mut edits = Vec::new();
 6323        let buffer = self.buffer.read(cx);
 6324        let snapshot = buffer.snapshot(cx);
 6325        for selection in &mut selections {
 6326            if selection.start.row != prev_edited_row {
 6327                row_delta = 0;
 6328            }
 6329            prev_edited_row = selection.end.row;
 6330
 6331            row_delta =
 6332                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6333        }
 6334
 6335        self.transact(window, cx, |this, window, cx| {
 6336            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6337            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6338                s.select(selections)
 6339            });
 6340        });
 6341    }
 6342
 6343    fn indent_selection(
 6344        buffer: &MultiBuffer,
 6345        snapshot: &MultiBufferSnapshot,
 6346        selection: &mut Selection<Point>,
 6347        edits: &mut Vec<(Range<Point>, String)>,
 6348        delta_for_start_row: u32,
 6349        cx: &App,
 6350    ) -> u32 {
 6351        let settings = buffer.settings_at(selection.start, cx);
 6352        let tab_size = settings.tab_size.get();
 6353        let indent_kind = if settings.hard_tabs {
 6354            IndentKind::Tab
 6355        } else {
 6356            IndentKind::Space
 6357        };
 6358        let mut start_row = selection.start.row;
 6359        let mut end_row = selection.end.row + 1;
 6360
 6361        // If a selection ends at the beginning of a line, don't indent
 6362        // that last line.
 6363        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6364            end_row -= 1;
 6365        }
 6366
 6367        // Avoid re-indenting a row that has already been indented by a
 6368        // previous selection, but still update this selection's column
 6369        // to reflect that indentation.
 6370        if delta_for_start_row > 0 {
 6371            start_row += 1;
 6372            selection.start.column += delta_for_start_row;
 6373            if selection.end.row == selection.start.row {
 6374                selection.end.column += delta_for_start_row;
 6375            }
 6376        }
 6377
 6378        let mut delta_for_end_row = 0;
 6379        let has_multiple_rows = start_row + 1 != end_row;
 6380        for row in start_row..end_row {
 6381            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6382            let indent_delta = match (current_indent.kind, indent_kind) {
 6383                (IndentKind::Space, IndentKind::Space) => {
 6384                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6385                    IndentSize::spaces(columns_to_next_tab_stop)
 6386                }
 6387                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6388                (_, IndentKind::Tab) => IndentSize::tab(),
 6389            };
 6390
 6391            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6392                0
 6393            } else {
 6394                selection.start.column
 6395            };
 6396            let row_start = Point::new(row, start);
 6397            edits.push((
 6398                row_start..row_start,
 6399                indent_delta.chars().collect::<String>(),
 6400            ));
 6401
 6402            // Update this selection's endpoints to reflect the indentation.
 6403            if row == selection.start.row {
 6404                selection.start.column += indent_delta.len;
 6405            }
 6406            if row == selection.end.row {
 6407                selection.end.column += indent_delta.len;
 6408                delta_for_end_row = indent_delta.len;
 6409            }
 6410        }
 6411
 6412        if selection.start.row == selection.end.row {
 6413            delta_for_start_row + delta_for_end_row
 6414        } else {
 6415            delta_for_end_row
 6416        }
 6417    }
 6418
 6419    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6420        if self.read_only(cx) {
 6421            return;
 6422        }
 6423        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6424        let selections = self.selections.all::<Point>(cx);
 6425        let mut deletion_ranges = Vec::new();
 6426        let mut last_outdent = None;
 6427        {
 6428            let buffer = self.buffer.read(cx);
 6429            let snapshot = buffer.snapshot(cx);
 6430            for selection in &selections {
 6431                let settings = buffer.settings_at(selection.start, cx);
 6432                let tab_size = settings.tab_size.get();
 6433                let mut rows = selection.spanned_rows(false, &display_map);
 6434
 6435                // Avoid re-outdenting a row that has already been outdented by a
 6436                // previous selection.
 6437                if let Some(last_row) = last_outdent {
 6438                    if last_row == rows.start {
 6439                        rows.start = rows.start.next_row();
 6440                    }
 6441                }
 6442                let has_multiple_rows = rows.len() > 1;
 6443                for row in rows.iter_rows() {
 6444                    let indent_size = snapshot.indent_size_for_line(row);
 6445                    if indent_size.len > 0 {
 6446                        let deletion_len = match indent_size.kind {
 6447                            IndentKind::Space => {
 6448                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6449                                if columns_to_prev_tab_stop == 0 {
 6450                                    tab_size
 6451                                } else {
 6452                                    columns_to_prev_tab_stop
 6453                                }
 6454                            }
 6455                            IndentKind::Tab => 1,
 6456                        };
 6457                        let start = if has_multiple_rows
 6458                            || deletion_len > selection.start.column
 6459                            || indent_size.len < selection.start.column
 6460                        {
 6461                            0
 6462                        } else {
 6463                            selection.start.column - deletion_len
 6464                        };
 6465                        deletion_ranges.push(
 6466                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6467                        );
 6468                        last_outdent = Some(row);
 6469                    }
 6470                }
 6471            }
 6472        }
 6473
 6474        self.transact(window, cx, |this, window, cx| {
 6475            this.buffer.update(cx, |buffer, cx| {
 6476                let empty_str: Arc<str> = Arc::default();
 6477                buffer.edit(
 6478                    deletion_ranges
 6479                        .into_iter()
 6480                        .map(|range| (range, empty_str.clone())),
 6481                    None,
 6482                    cx,
 6483                );
 6484            });
 6485            let selections = this.selections.all::<usize>(cx);
 6486            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6487                s.select(selections)
 6488            });
 6489        });
 6490    }
 6491
 6492    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6493        if self.read_only(cx) {
 6494            return;
 6495        }
 6496        let selections = self
 6497            .selections
 6498            .all::<usize>(cx)
 6499            .into_iter()
 6500            .map(|s| s.range());
 6501
 6502        self.transact(window, cx, |this, window, cx| {
 6503            this.buffer.update(cx, |buffer, cx| {
 6504                buffer.autoindent_ranges(selections, cx);
 6505            });
 6506            let selections = this.selections.all::<usize>(cx);
 6507            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6508                s.select(selections)
 6509            });
 6510        });
 6511    }
 6512
 6513    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6514        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6515        let selections = self.selections.all::<Point>(cx);
 6516
 6517        let mut new_cursors = Vec::new();
 6518        let mut edit_ranges = Vec::new();
 6519        let mut selections = selections.iter().peekable();
 6520        while let Some(selection) = selections.next() {
 6521            let mut rows = selection.spanned_rows(false, &display_map);
 6522            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6523
 6524            // Accumulate contiguous regions of rows that we want to delete.
 6525            while let Some(next_selection) = selections.peek() {
 6526                let next_rows = next_selection.spanned_rows(false, &display_map);
 6527                if next_rows.start <= rows.end {
 6528                    rows.end = next_rows.end;
 6529                    selections.next().unwrap();
 6530                } else {
 6531                    break;
 6532                }
 6533            }
 6534
 6535            let buffer = &display_map.buffer_snapshot;
 6536            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6537            let edit_end;
 6538            let cursor_buffer_row;
 6539            if buffer.max_point().row >= rows.end.0 {
 6540                // If there's a line after the range, delete the \n from the end of the row range
 6541                // and position the cursor on the next line.
 6542                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6543                cursor_buffer_row = rows.end;
 6544            } else {
 6545                // If there isn't a line after the range, delete the \n from the line before the
 6546                // start of the row range and position the cursor there.
 6547                edit_start = edit_start.saturating_sub(1);
 6548                edit_end = buffer.len();
 6549                cursor_buffer_row = rows.start.previous_row();
 6550            }
 6551
 6552            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6553            *cursor.column_mut() =
 6554                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6555
 6556            new_cursors.push((
 6557                selection.id,
 6558                buffer.anchor_after(cursor.to_point(&display_map)),
 6559            ));
 6560            edit_ranges.push(edit_start..edit_end);
 6561        }
 6562
 6563        self.transact(window, cx, |this, window, cx| {
 6564            let buffer = this.buffer.update(cx, |buffer, cx| {
 6565                let empty_str: Arc<str> = Arc::default();
 6566                buffer.edit(
 6567                    edit_ranges
 6568                        .into_iter()
 6569                        .map(|range| (range, empty_str.clone())),
 6570                    None,
 6571                    cx,
 6572                );
 6573                buffer.snapshot(cx)
 6574            });
 6575            let new_selections = new_cursors
 6576                .into_iter()
 6577                .map(|(id, cursor)| {
 6578                    let cursor = cursor.to_point(&buffer);
 6579                    Selection {
 6580                        id,
 6581                        start: cursor,
 6582                        end: cursor,
 6583                        reversed: false,
 6584                        goal: SelectionGoal::None,
 6585                    }
 6586                })
 6587                .collect();
 6588
 6589            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6590                s.select(new_selections);
 6591            });
 6592        });
 6593    }
 6594
 6595    pub fn join_lines_impl(
 6596        &mut self,
 6597        insert_whitespace: bool,
 6598        window: &mut Window,
 6599        cx: &mut Context<Self>,
 6600    ) {
 6601        if self.read_only(cx) {
 6602            return;
 6603        }
 6604        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6605        for selection in self.selections.all::<Point>(cx) {
 6606            let start = MultiBufferRow(selection.start.row);
 6607            // Treat single line selections as if they include the next line. Otherwise this action
 6608            // would do nothing for single line selections individual cursors.
 6609            let end = if selection.start.row == selection.end.row {
 6610                MultiBufferRow(selection.start.row + 1)
 6611            } else {
 6612                MultiBufferRow(selection.end.row)
 6613            };
 6614
 6615            if let Some(last_row_range) = row_ranges.last_mut() {
 6616                if start <= last_row_range.end {
 6617                    last_row_range.end = end;
 6618                    continue;
 6619                }
 6620            }
 6621            row_ranges.push(start..end);
 6622        }
 6623
 6624        let snapshot = self.buffer.read(cx).snapshot(cx);
 6625        let mut cursor_positions = Vec::new();
 6626        for row_range in &row_ranges {
 6627            let anchor = snapshot.anchor_before(Point::new(
 6628                row_range.end.previous_row().0,
 6629                snapshot.line_len(row_range.end.previous_row()),
 6630            ));
 6631            cursor_positions.push(anchor..anchor);
 6632        }
 6633
 6634        self.transact(window, cx, |this, window, cx| {
 6635            for row_range in row_ranges.into_iter().rev() {
 6636                for row in row_range.iter_rows().rev() {
 6637                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6638                    let next_line_row = row.next_row();
 6639                    let indent = snapshot.indent_size_for_line(next_line_row);
 6640                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6641
 6642                    let replace =
 6643                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6644                            " "
 6645                        } else {
 6646                            ""
 6647                        };
 6648
 6649                    this.buffer.update(cx, |buffer, cx| {
 6650                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6651                    });
 6652                }
 6653            }
 6654
 6655            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6656                s.select_anchor_ranges(cursor_positions)
 6657            });
 6658        });
 6659    }
 6660
 6661    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6662        self.join_lines_impl(true, window, cx);
 6663    }
 6664
 6665    pub fn sort_lines_case_sensitive(
 6666        &mut self,
 6667        _: &SortLinesCaseSensitive,
 6668        window: &mut Window,
 6669        cx: &mut Context<Self>,
 6670    ) {
 6671        self.manipulate_lines(window, cx, |lines| lines.sort())
 6672    }
 6673
 6674    pub fn sort_lines_case_insensitive(
 6675        &mut self,
 6676        _: &SortLinesCaseInsensitive,
 6677        window: &mut Window,
 6678        cx: &mut Context<Self>,
 6679    ) {
 6680        self.manipulate_lines(window, cx, |lines| {
 6681            lines.sort_by_key(|line| line.to_lowercase())
 6682        })
 6683    }
 6684
 6685    pub fn unique_lines_case_insensitive(
 6686        &mut self,
 6687        _: &UniqueLinesCaseInsensitive,
 6688        window: &mut Window,
 6689        cx: &mut Context<Self>,
 6690    ) {
 6691        self.manipulate_lines(window, cx, |lines| {
 6692            let mut seen = HashSet::default();
 6693            lines.retain(|line| seen.insert(line.to_lowercase()));
 6694        })
 6695    }
 6696
 6697    pub fn unique_lines_case_sensitive(
 6698        &mut self,
 6699        _: &UniqueLinesCaseSensitive,
 6700        window: &mut Window,
 6701        cx: &mut Context<Self>,
 6702    ) {
 6703        self.manipulate_lines(window, cx, |lines| {
 6704            let mut seen = HashSet::default();
 6705            lines.retain(|line| seen.insert(*line));
 6706        })
 6707    }
 6708
 6709    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6710        let mut revert_changes = HashMap::default();
 6711        let snapshot = self.snapshot(window, cx);
 6712        for hunk in snapshot
 6713            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6714        {
 6715            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6716        }
 6717        if !revert_changes.is_empty() {
 6718            self.transact(window, cx, |editor, window, cx| {
 6719                editor.revert(revert_changes, window, cx);
 6720            });
 6721        }
 6722    }
 6723
 6724    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6725        let Some(project) = self.project.clone() else {
 6726            return;
 6727        };
 6728        self.reload(project, window, cx)
 6729            .detach_and_notify_err(window, cx);
 6730    }
 6731
 6732    pub fn revert_selected_hunks(
 6733        &mut self,
 6734        _: &RevertSelectedHunks,
 6735        window: &mut Window,
 6736        cx: &mut Context<Self>,
 6737    ) {
 6738        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6739        self.revert_hunks_in_ranges(selections, window, cx);
 6740    }
 6741
 6742    fn revert_hunks_in_ranges(
 6743        &mut self,
 6744        ranges: impl Iterator<Item = Range<Point>>,
 6745        window: &mut Window,
 6746        cx: &mut Context<Editor>,
 6747    ) {
 6748        let mut revert_changes = HashMap::default();
 6749        let snapshot = self.snapshot(window, cx);
 6750        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6751            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6752        }
 6753        if !revert_changes.is_empty() {
 6754            self.transact(window, cx, |editor, window, cx| {
 6755                editor.revert(revert_changes, window, cx);
 6756            });
 6757        }
 6758    }
 6759
 6760    pub fn open_active_item_in_terminal(
 6761        &mut self,
 6762        _: &OpenInTerminal,
 6763        window: &mut Window,
 6764        cx: &mut Context<Self>,
 6765    ) {
 6766        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6767            let project_path = buffer.read(cx).project_path(cx)?;
 6768            let project = self.project.as_ref()?.read(cx);
 6769            let entry = project.entry_for_path(&project_path, cx)?;
 6770            let parent = match &entry.canonical_path {
 6771                Some(canonical_path) => canonical_path.to_path_buf(),
 6772                None => project.absolute_path(&project_path, cx)?,
 6773            }
 6774            .parent()?
 6775            .to_path_buf();
 6776            Some(parent)
 6777        }) {
 6778            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6779        }
 6780    }
 6781
 6782    pub fn prepare_revert_change(
 6783        &self,
 6784        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6785        hunk: &MultiBufferDiffHunk,
 6786        cx: &mut App,
 6787    ) -> Option<()> {
 6788        let buffer = self.buffer.read(cx);
 6789        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6790        let buffer = buffer.buffer(hunk.buffer_id)?;
 6791        let buffer = buffer.read(cx);
 6792        let original_text = change_set
 6793            .read(cx)
 6794            .base_text
 6795            .as_ref()?
 6796            .as_rope()
 6797            .slice(hunk.diff_base_byte_range.clone());
 6798        let buffer_snapshot = buffer.snapshot();
 6799        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6800        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6801            probe
 6802                .0
 6803                .start
 6804                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6805                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6806        }) {
 6807            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6808            Some(())
 6809        } else {
 6810            None
 6811        }
 6812    }
 6813
 6814    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6815        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6816    }
 6817
 6818    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6819        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6820    }
 6821
 6822    fn manipulate_lines<Fn>(
 6823        &mut self,
 6824        window: &mut Window,
 6825        cx: &mut Context<Self>,
 6826        mut callback: Fn,
 6827    ) where
 6828        Fn: FnMut(&mut Vec<&str>),
 6829    {
 6830        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6831        let buffer = self.buffer.read(cx).snapshot(cx);
 6832
 6833        let mut edits = Vec::new();
 6834
 6835        let selections = self.selections.all::<Point>(cx);
 6836        let mut selections = selections.iter().peekable();
 6837        let mut contiguous_row_selections = Vec::new();
 6838        let mut new_selections = Vec::new();
 6839        let mut added_lines = 0;
 6840        let mut removed_lines = 0;
 6841
 6842        while let Some(selection) = selections.next() {
 6843            let (start_row, end_row) = consume_contiguous_rows(
 6844                &mut contiguous_row_selections,
 6845                selection,
 6846                &display_map,
 6847                &mut selections,
 6848            );
 6849
 6850            let start_point = Point::new(start_row.0, 0);
 6851            let end_point = Point::new(
 6852                end_row.previous_row().0,
 6853                buffer.line_len(end_row.previous_row()),
 6854            );
 6855            let text = buffer
 6856                .text_for_range(start_point..end_point)
 6857                .collect::<String>();
 6858
 6859            let mut lines = text.split('\n').collect_vec();
 6860
 6861            let lines_before = lines.len();
 6862            callback(&mut lines);
 6863            let lines_after = lines.len();
 6864
 6865            edits.push((start_point..end_point, lines.join("\n")));
 6866
 6867            // Selections must change based on added and removed line count
 6868            let start_row =
 6869                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6870            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6871            new_selections.push(Selection {
 6872                id: selection.id,
 6873                start: start_row,
 6874                end: end_row,
 6875                goal: SelectionGoal::None,
 6876                reversed: selection.reversed,
 6877            });
 6878
 6879            if lines_after > lines_before {
 6880                added_lines += lines_after - lines_before;
 6881            } else if lines_before > lines_after {
 6882                removed_lines += lines_before - lines_after;
 6883            }
 6884        }
 6885
 6886        self.transact(window, cx, |this, window, cx| {
 6887            let buffer = this.buffer.update(cx, |buffer, cx| {
 6888                buffer.edit(edits, None, cx);
 6889                buffer.snapshot(cx)
 6890            });
 6891
 6892            // Recalculate offsets on newly edited buffer
 6893            let new_selections = new_selections
 6894                .iter()
 6895                .map(|s| {
 6896                    let start_point = Point::new(s.start.0, 0);
 6897                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6898                    Selection {
 6899                        id: s.id,
 6900                        start: buffer.point_to_offset(start_point),
 6901                        end: buffer.point_to_offset(end_point),
 6902                        goal: s.goal,
 6903                        reversed: s.reversed,
 6904                    }
 6905                })
 6906                .collect();
 6907
 6908            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6909                s.select(new_selections);
 6910            });
 6911
 6912            this.request_autoscroll(Autoscroll::fit(), cx);
 6913        });
 6914    }
 6915
 6916    pub fn convert_to_upper_case(
 6917        &mut self,
 6918        _: &ConvertToUpperCase,
 6919        window: &mut Window,
 6920        cx: &mut Context<Self>,
 6921    ) {
 6922        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6923    }
 6924
 6925    pub fn convert_to_lower_case(
 6926        &mut self,
 6927        _: &ConvertToLowerCase,
 6928        window: &mut Window,
 6929        cx: &mut Context<Self>,
 6930    ) {
 6931        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6932    }
 6933
 6934    pub fn convert_to_title_case(
 6935        &mut self,
 6936        _: &ConvertToTitleCase,
 6937        window: &mut Window,
 6938        cx: &mut Context<Self>,
 6939    ) {
 6940        self.manipulate_text(window, cx, |text| {
 6941            text.split('\n')
 6942                .map(|line| line.to_case(Case::Title))
 6943                .join("\n")
 6944        })
 6945    }
 6946
 6947    pub fn convert_to_snake_case(
 6948        &mut self,
 6949        _: &ConvertToSnakeCase,
 6950        window: &mut Window,
 6951        cx: &mut Context<Self>,
 6952    ) {
 6953        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6954    }
 6955
 6956    pub fn convert_to_kebab_case(
 6957        &mut self,
 6958        _: &ConvertToKebabCase,
 6959        window: &mut Window,
 6960        cx: &mut Context<Self>,
 6961    ) {
 6962        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6963    }
 6964
 6965    pub fn convert_to_upper_camel_case(
 6966        &mut self,
 6967        _: &ConvertToUpperCamelCase,
 6968        window: &mut Window,
 6969        cx: &mut Context<Self>,
 6970    ) {
 6971        self.manipulate_text(window, cx, |text| {
 6972            text.split('\n')
 6973                .map(|line| line.to_case(Case::UpperCamel))
 6974                .join("\n")
 6975        })
 6976    }
 6977
 6978    pub fn convert_to_lower_camel_case(
 6979        &mut self,
 6980        _: &ConvertToLowerCamelCase,
 6981        window: &mut Window,
 6982        cx: &mut Context<Self>,
 6983    ) {
 6984        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6985    }
 6986
 6987    pub fn convert_to_opposite_case(
 6988        &mut self,
 6989        _: &ConvertToOppositeCase,
 6990        window: &mut Window,
 6991        cx: &mut Context<Self>,
 6992    ) {
 6993        self.manipulate_text(window, cx, |text| {
 6994            text.chars()
 6995                .fold(String::with_capacity(text.len()), |mut t, c| {
 6996                    if c.is_uppercase() {
 6997                        t.extend(c.to_lowercase());
 6998                    } else {
 6999                        t.extend(c.to_uppercase());
 7000                    }
 7001                    t
 7002                })
 7003        })
 7004    }
 7005
 7006    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7007    where
 7008        Fn: FnMut(&str) -> String,
 7009    {
 7010        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7011        let buffer = self.buffer.read(cx).snapshot(cx);
 7012
 7013        let mut new_selections = Vec::new();
 7014        let mut edits = Vec::new();
 7015        let mut selection_adjustment = 0i32;
 7016
 7017        for selection in self.selections.all::<usize>(cx) {
 7018            let selection_is_empty = selection.is_empty();
 7019
 7020            let (start, end) = if selection_is_empty {
 7021                let word_range = movement::surrounding_word(
 7022                    &display_map,
 7023                    selection.start.to_display_point(&display_map),
 7024                );
 7025                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7026                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7027                (start, end)
 7028            } else {
 7029                (selection.start, selection.end)
 7030            };
 7031
 7032            let text = buffer.text_for_range(start..end).collect::<String>();
 7033            let old_length = text.len() as i32;
 7034            let text = callback(&text);
 7035
 7036            new_selections.push(Selection {
 7037                start: (start as i32 - selection_adjustment) as usize,
 7038                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7039                goal: SelectionGoal::None,
 7040                ..selection
 7041            });
 7042
 7043            selection_adjustment += old_length - text.len() as i32;
 7044
 7045            edits.push((start..end, text));
 7046        }
 7047
 7048        self.transact(window, cx, |this, window, cx| {
 7049            this.buffer.update(cx, |buffer, cx| {
 7050                buffer.edit(edits, None, cx);
 7051            });
 7052
 7053            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7054                s.select(new_selections);
 7055            });
 7056
 7057            this.request_autoscroll(Autoscroll::fit(), cx);
 7058        });
 7059    }
 7060
 7061    pub fn duplicate(
 7062        &mut self,
 7063        upwards: bool,
 7064        whole_lines: bool,
 7065        window: &mut Window,
 7066        cx: &mut Context<Self>,
 7067    ) {
 7068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7069        let buffer = &display_map.buffer_snapshot;
 7070        let selections = self.selections.all::<Point>(cx);
 7071
 7072        let mut edits = Vec::new();
 7073        let mut selections_iter = selections.iter().peekable();
 7074        while let Some(selection) = selections_iter.next() {
 7075            let mut rows = selection.spanned_rows(false, &display_map);
 7076            // duplicate line-wise
 7077            if whole_lines || selection.start == selection.end {
 7078                // Avoid duplicating the same lines twice.
 7079                while let Some(next_selection) = selections_iter.peek() {
 7080                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7081                    if next_rows.start < rows.end {
 7082                        rows.end = next_rows.end;
 7083                        selections_iter.next().unwrap();
 7084                    } else {
 7085                        break;
 7086                    }
 7087                }
 7088
 7089                // Copy the text from the selected row region and splice it either at the start
 7090                // or end of the region.
 7091                let start = Point::new(rows.start.0, 0);
 7092                let end = Point::new(
 7093                    rows.end.previous_row().0,
 7094                    buffer.line_len(rows.end.previous_row()),
 7095                );
 7096                let text = buffer
 7097                    .text_for_range(start..end)
 7098                    .chain(Some("\n"))
 7099                    .collect::<String>();
 7100                let insert_location = if upwards {
 7101                    Point::new(rows.end.0, 0)
 7102                } else {
 7103                    start
 7104                };
 7105                edits.push((insert_location..insert_location, text));
 7106            } else {
 7107                // duplicate character-wise
 7108                let start = selection.start;
 7109                let end = selection.end;
 7110                let text = buffer.text_for_range(start..end).collect::<String>();
 7111                edits.push((selection.end..selection.end, text));
 7112            }
 7113        }
 7114
 7115        self.transact(window, cx, |this, _, cx| {
 7116            this.buffer.update(cx, |buffer, cx| {
 7117                buffer.edit(edits, None, cx);
 7118            });
 7119
 7120            this.request_autoscroll(Autoscroll::fit(), cx);
 7121        });
 7122    }
 7123
 7124    pub fn duplicate_line_up(
 7125        &mut self,
 7126        _: &DuplicateLineUp,
 7127        window: &mut Window,
 7128        cx: &mut Context<Self>,
 7129    ) {
 7130        self.duplicate(true, true, window, cx);
 7131    }
 7132
 7133    pub fn duplicate_line_down(
 7134        &mut self,
 7135        _: &DuplicateLineDown,
 7136        window: &mut Window,
 7137        cx: &mut Context<Self>,
 7138    ) {
 7139        self.duplicate(false, true, window, cx);
 7140    }
 7141
 7142    pub fn duplicate_selection(
 7143        &mut self,
 7144        _: &DuplicateSelection,
 7145        window: &mut Window,
 7146        cx: &mut Context<Self>,
 7147    ) {
 7148        self.duplicate(false, false, window, cx);
 7149    }
 7150
 7151    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7152        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7153        let buffer = self.buffer.read(cx).snapshot(cx);
 7154
 7155        let mut edits = Vec::new();
 7156        let mut unfold_ranges = Vec::new();
 7157        let mut refold_creases = Vec::new();
 7158
 7159        let selections = self.selections.all::<Point>(cx);
 7160        let mut selections = selections.iter().peekable();
 7161        let mut contiguous_row_selections = Vec::new();
 7162        let mut new_selections = Vec::new();
 7163
 7164        while let Some(selection) = selections.next() {
 7165            // Find all the selections that span a contiguous row range
 7166            let (start_row, end_row) = consume_contiguous_rows(
 7167                &mut contiguous_row_selections,
 7168                selection,
 7169                &display_map,
 7170                &mut selections,
 7171            );
 7172
 7173            // Move the text spanned by the row range to be before the line preceding the row range
 7174            if start_row.0 > 0 {
 7175                let range_to_move = Point::new(
 7176                    start_row.previous_row().0,
 7177                    buffer.line_len(start_row.previous_row()),
 7178                )
 7179                    ..Point::new(
 7180                        end_row.previous_row().0,
 7181                        buffer.line_len(end_row.previous_row()),
 7182                    );
 7183                let insertion_point = display_map
 7184                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7185                    .0;
 7186
 7187                // Don't move lines across excerpts
 7188                if buffer
 7189                    .excerpt_containing(insertion_point..range_to_move.end)
 7190                    .is_some()
 7191                {
 7192                    let text = buffer
 7193                        .text_for_range(range_to_move.clone())
 7194                        .flat_map(|s| s.chars())
 7195                        .skip(1)
 7196                        .chain(['\n'])
 7197                        .collect::<String>();
 7198
 7199                    edits.push((
 7200                        buffer.anchor_after(range_to_move.start)
 7201                            ..buffer.anchor_before(range_to_move.end),
 7202                        String::new(),
 7203                    ));
 7204                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7205                    edits.push((insertion_anchor..insertion_anchor, text));
 7206
 7207                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7208
 7209                    // Move selections up
 7210                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7211                        |mut selection| {
 7212                            selection.start.row -= row_delta;
 7213                            selection.end.row -= row_delta;
 7214                            selection
 7215                        },
 7216                    ));
 7217
 7218                    // Move folds up
 7219                    unfold_ranges.push(range_to_move.clone());
 7220                    for fold in display_map.folds_in_range(
 7221                        buffer.anchor_before(range_to_move.start)
 7222                            ..buffer.anchor_after(range_to_move.end),
 7223                    ) {
 7224                        let mut start = fold.range.start.to_point(&buffer);
 7225                        let mut end = fold.range.end.to_point(&buffer);
 7226                        start.row -= row_delta;
 7227                        end.row -= row_delta;
 7228                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7229                    }
 7230                }
 7231            }
 7232
 7233            // If we didn't move line(s), preserve the existing selections
 7234            new_selections.append(&mut contiguous_row_selections);
 7235        }
 7236
 7237        self.transact(window, cx, |this, window, cx| {
 7238            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7239            this.buffer.update(cx, |buffer, cx| {
 7240                for (range, text) in edits {
 7241                    buffer.edit([(range, text)], None, cx);
 7242                }
 7243            });
 7244            this.fold_creases(refold_creases, true, window, cx);
 7245            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7246                s.select(new_selections);
 7247            })
 7248        });
 7249    }
 7250
 7251    pub fn move_line_down(
 7252        &mut self,
 7253        _: &MoveLineDown,
 7254        window: &mut Window,
 7255        cx: &mut Context<Self>,
 7256    ) {
 7257        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7258        let buffer = self.buffer.read(cx).snapshot(cx);
 7259
 7260        let mut edits = Vec::new();
 7261        let mut unfold_ranges = Vec::new();
 7262        let mut refold_creases = Vec::new();
 7263
 7264        let selections = self.selections.all::<Point>(cx);
 7265        let mut selections = selections.iter().peekable();
 7266        let mut contiguous_row_selections = Vec::new();
 7267        let mut new_selections = Vec::new();
 7268
 7269        while let Some(selection) = selections.next() {
 7270            // Find all the selections that span a contiguous row range
 7271            let (start_row, end_row) = consume_contiguous_rows(
 7272                &mut contiguous_row_selections,
 7273                selection,
 7274                &display_map,
 7275                &mut selections,
 7276            );
 7277
 7278            // Move the text spanned by the row range to be after the last line of the row range
 7279            if end_row.0 <= buffer.max_point().row {
 7280                let range_to_move =
 7281                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7282                let insertion_point = display_map
 7283                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7284                    .0;
 7285
 7286                // Don't move lines across excerpt boundaries
 7287                if buffer
 7288                    .excerpt_containing(range_to_move.start..insertion_point)
 7289                    .is_some()
 7290                {
 7291                    let mut text = String::from("\n");
 7292                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7293                    text.pop(); // Drop trailing newline
 7294                    edits.push((
 7295                        buffer.anchor_after(range_to_move.start)
 7296                            ..buffer.anchor_before(range_to_move.end),
 7297                        String::new(),
 7298                    ));
 7299                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7300                    edits.push((insertion_anchor..insertion_anchor, text));
 7301
 7302                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7303
 7304                    // Move selections down
 7305                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7306                        |mut selection| {
 7307                            selection.start.row += row_delta;
 7308                            selection.end.row += row_delta;
 7309                            selection
 7310                        },
 7311                    ));
 7312
 7313                    // Move folds down
 7314                    unfold_ranges.push(range_to_move.clone());
 7315                    for fold in display_map.folds_in_range(
 7316                        buffer.anchor_before(range_to_move.start)
 7317                            ..buffer.anchor_after(range_to_move.end),
 7318                    ) {
 7319                        let mut start = fold.range.start.to_point(&buffer);
 7320                        let mut end = fold.range.end.to_point(&buffer);
 7321                        start.row += row_delta;
 7322                        end.row += row_delta;
 7323                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7324                    }
 7325                }
 7326            }
 7327
 7328            // If we didn't move line(s), preserve the existing selections
 7329            new_selections.append(&mut contiguous_row_selections);
 7330        }
 7331
 7332        self.transact(window, cx, |this, window, cx| {
 7333            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7334            this.buffer.update(cx, |buffer, cx| {
 7335                for (range, text) in edits {
 7336                    buffer.edit([(range, text)], None, cx);
 7337                }
 7338            });
 7339            this.fold_creases(refold_creases, true, window, cx);
 7340            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7341                s.select(new_selections)
 7342            });
 7343        });
 7344    }
 7345
 7346    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7347        let text_layout_details = &self.text_layout_details(window);
 7348        self.transact(window, cx, |this, window, cx| {
 7349            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7350                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7351                let line_mode = s.line_mode;
 7352                s.move_with(|display_map, selection| {
 7353                    if !selection.is_empty() || line_mode {
 7354                        return;
 7355                    }
 7356
 7357                    let mut head = selection.head();
 7358                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7359                    if head.column() == display_map.line_len(head.row()) {
 7360                        transpose_offset = display_map
 7361                            .buffer_snapshot
 7362                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7363                    }
 7364
 7365                    if transpose_offset == 0 {
 7366                        return;
 7367                    }
 7368
 7369                    *head.column_mut() += 1;
 7370                    head = display_map.clip_point(head, Bias::Right);
 7371                    let goal = SelectionGoal::HorizontalPosition(
 7372                        display_map
 7373                            .x_for_display_point(head, text_layout_details)
 7374                            .into(),
 7375                    );
 7376                    selection.collapse_to(head, goal);
 7377
 7378                    let transpose_start = display_map
 7379                        .buffer_snapshot
 7380                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7381                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7382                        let transpose_end = display_map
 7383                            .buffer_snapshot
 7384                            .clip_offset(transpose_offset + 1, Bias::Right);
 7385                        if let Some(ch) =
 7386                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7387                        {
 7388                            edits.push((transpose_start..transpose_offset, String::new()));
 7389                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7390                        }
 7391                    }
 7392                });
 7393                edits
 7394            });
 7395            this.buffer
 7396                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7397            let selections = this.selections.all::<usize>(cx);
 7398            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7399                s.select(selections);
 7400            });
 7401        });
 7402    }
 7403
 7404    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7405        self.rewrap_impl(IsVimMode::No, cx)
 7406    }
 7407
 7408    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7409        let buffer = self.buffer.read(cx).snapshot(cx);
 7410        let selections = self.selections.all::<Point>(cx);
 7411        let mut selections = selections.iter().peekable();
 7412
 7413        let mut edits = Vec::new();
 7414        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7415
 7416        while let Some(selection) = selections.next() {
 7417            let mut start_row = selection.start.row;
 7418            let mut end_row = selection.end.row;
 7419
 7420            // Skip selections that overlap with a range that has already been rewrapped.
 7421            let selection_range = start_row..end_row;
 7422            if rewrapped_row_ranges
 7423                .iter()
 7424                .any(|range| range.overlaps(&selection_range))
 7425            {
 7426                continue;
 7427            }
 7428
 7429            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7430
 7431            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7432                match language_scope.language_name().as_ref() {
 7433                    "Markdown" | "Plain Text" => {
 7434                        should_rewrap = true;
 7435                    }
 7436                    _ => {}
 7437                }
 7438            }
 7439
 7440            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7441
 7442            // Since not all lines in the selection may be at the same indent
 7443            // level, choose the indent size that is the most common between all
 7444            // of the lines.
 7445            //
 7446            // If there is a tie, we use the deepest indent.
 7447            let (indent_size, indent_end) = {
 7448                let mut indent_size_occurrences = HashMap::default();
 7449                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7450
 7451                for row in start_row..=end_row {
 7452                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7453                    rows_by_indent_size.entry(indent).or_default().push(row);
 7454                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7455                }
 7456
 7457                let indent_size = indent_size_occurrences
 7458                    .into_iter()
 7459                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7460                    .map(|(indent, _)| indent)
 7461                    .unwrap_or_default();
 7462                let row = rows_by_indent_size[&indent_size][0];
 7463                let indent_end = Point::new(row, indent_size.len);
 7464
 7465                (indent_size, indent_end)
 7466            };
 7467
 7468            let mut line_prefix = indent_size.chars().collect::<String>();
 7469
 7470            if let Some(comment_prefix) =
 7471                buffer
 7472                    .language_scope_at(selection.head())
 7473                    .and_then(|language| {
 7474                        language
 7475                            .line_comment_prefixes()
 7476                            .iter()
 7477                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7478                            .cloned()
 7479                    })
 7480            {
 7481                line_prefix.push_str(&comment_prefix);
 7482                should_rewrap = true;
 7483            }
 7484
 7485            if !should_rewrap {
 7486                continue;
 7487            }
 7488
 7489            if selection.is_empty() {
 7490                'expand_upwards: while start_row > 0 {
 7491                    let prev_row = start_row - 1;
 7492                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7493                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7494                    {
 7495                        start_row = prev_row;
 7496                    } else {
 7497                        break 'expand_upwards;
 7498                    }
 7499                }
 7500
 7501                'expand_downwards: while end_row < buffer.max_point().row {
 7502                    let next_row = end_row + 1;
 7503                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7504                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7505                    {
 7506                        end_row = next_row;
 7507                    } else {
 7508                        break 'expand_downwards;
 7509                    }
 7510                }
 7511            }
 7512
 7513            let start = Point::new(start_row, 0);
 7514            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7515            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7516            let Some(lines_without_prefixes) = selection_text
 7517                .lines()
 7518                .map(|line| {
 7519                    line.strip_prefix(&line_prefix)
 7520                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7521                        .ok_or_else(|| {
 7522                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7523                        })
 7524                })
 7525                .collect::<Result<Vec<_>, _>>()
 7526                .log_err()
 7527            else {
 7528                continue;
 7529            };
 7530
 7531            let wrap_column = buffer
 7532                .settings_at(Point::new(start_row, 0), cx)
 7533                .preferred_line_length as usize;
 7534            let wrapped_text = wrap_with_prefix(
 7535                line_prefix,
 7536                lines_without_prefixes.join(" "),
 7537                wrap_column,
 7538                tab_size,
 7539            );
 7540
 7541            // TODO: should always use char-based diff while still supporting cursor behavior that
 7542            // matches vim.
 7543            let diff = match is_vim_mode {
 7544                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7545                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7546            };
 7547            let mut offset = start.to_offset(&buffer);
 7548            let mut moved_since_edit = true;
 7549
 7550            for change in diff.iter_all_changes() {
 7551                let value = change.value();
 7552                match change.tag() {
 7553                    ChangeTag::Equal => {
 7554                        offset += value.len();
 7555                        moved_since_edit = true;
 7556                    }
 7557                    ChangeTag::Delete => {
 7558                        let start = buffer.anchor_after(offset);
 7559                        let end = buffer.anchor_before(offset + value.len());
 7560
 7561                        if moved_since_edit {
 7562                            edits.push((start..end, String::new()));
 7563                        } else {
 7564                            edits.last_mut().unwrap().0.end = end;
 7565                        }
 7566
 7567                        offset += value.len();
 7568                        moved_since_edit = false;
 7569                    }
 7570                    ChangeTag::Insert => {
 7571                        if moved_since_edit {
 7572                            let anchor = buffer.anchor_after(offset);
 7573                            edits.push((anchor..anchor, value.to_string()));
 7574                        } else {
 7575                            edits.last_mut().unwrap().1.push_str(value);
 7576                        }
 7577
 7578                        moved_since_edit = false;
 7579                    }
 7580                }
 7581            }
 7582
 7583            rewrapped_row_ranges.push(start_row..=end_row);
 7584        }
 7585
 7586        self.buffer
 7587            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7588    }
 7589
 7590    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7591        let mut text = String::new();
 7592        let buffer = self.buffer.read(cx).snapshot(cx);
 7593        let mut selections = self.selections.all::<Point>(cx);
 7594        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7595        {
 7596            let max_point = buffer.max_point();
 7597            let mut is_first = true;
 7598            for selection in &mut selections {
 7599                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7600                if is_entire_line {
 7601                    selection.start = Point::new(selection.start.row, 0);
 7602                    if !selection.is_empty() && selection.end.column == 0 {
 7603                        selection.end = cmp::min(max_point, selection.end);
 7604                    } else {
 7605                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7606                    }
 7607                    selection.goal = SelectionGoal::None;
 7608                }
 7609                if is_first {
 7610                    is_first = false;
 7611                } else {
 7612                    text += "\n";
 7613                }
 7614                let mut len = 0;
 7615                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7616                    text.push_str(chunk);
 7617                    len += chunk.len();
 7618                }
 7619                clipboard_selections.push(ClipboardSelection {
 7620                    len,
 7621                    is_entire_line,
 7622                    first_line_indent: buffer
 7623                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7624                        .len,
 7625                });
 7626            }
 7627        }
 7628
 7629        self.transact(window, cx, |this, window, cx| {
 7630            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7631                s.select(selections);
 7632            });
 7633            this.insert("", window, cx);
 7634        });
 7635        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7636    }
 7637
 7638    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7639        let item = self.cut_common(window, cx);
 7640        cx.write_to_clipboard(item);
 7641    }
 7642
 7643    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7644        self.change_selections(None, window, cx, |s| {
 7645            s.move_with(|snapshot, sel| {
 7646                if sel.is_empty() {
 7647                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7648                }
 7649            });
 7650        });
 7651        let item = self.cut_common(window, cx);
 7652        cx.set_global(KillRing(item))
 7653    }
 7654
 7655    pub fn kill_ring_yank(
 7656        &mut self,
 7657        _: &KillRingYank,
 7658        window: &mut Window,
 7659        cx: &mut Context<Self>,
 7660    ) {
 7661        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7662            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7663                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7664            } else {
 7665                return;
 7666            }
 7667        } else {
 7668            return;
 7669        };
 7670        self.do_paste(&text, metadata, false, window, cx);
 7671    }
 7672
 7673    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7674        let selections = self.selections.all::<Point>(cx);
 7675        let buffer = self.buffer.read(cx).read(cx);
 7676        let mut text = String::new();
 7677
 7678        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7679        {
 7680            let max_point = buffer.max_point();
 7681            let mut is_first = true;
 7682            for selection in selections.iter() {
 7683                let mut start = selection.start;
 7684                let mut end = selection.end;
 7685                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7686                if is_entire_line {
 7687                    start = Point::new(start.row, 0);
 7688                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7689                }
 7690                if is_first {
 7691                    is_first = false;
 7692                } else {
 7693                    text += "\n";
 7694                }
 7695                let mut len = 0;
 7696                for chunk in buffer.text_for_range(start..end) {
 7697                    text.push_str(chunk);
 7698                    len += chunk.len();
 7699                }
 7700                clipboard_selections.push(ClipboardSelection {
 7701                    len,
 7702                    is_entire_line,
 7703                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7704                });
 7705            }
 7706        }
 7707
 7708        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7709            text,
 7710            clipboard_selections,
 7711        ));
 7712    }
 7713
 7714    pub fn do_paste(
 7715        &mut self,
 7716        text: &String,
 7717        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7718        handle_entire_lines: bool,
 7719        window: &mut Window,
 7720        cx: &mut Context<Self>,
 7721    ) {
 7722        if self.read_only(cx) {
 7723            return;
 7724        }
 7725
 7726        let clipboard_text = Cow::Borrowed(text);
 7727
 7728        self.transact(window, cx, |this, window, cx| {
 7729            if let Some(mut clipboard_selections) = clipboard_selections {
 7730                let old_selections = this.selections.all::<usize>(cx);
 7731                let all_selections_were_entire_line =
 7732                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7733                let first_selection_indent_column =
 7734                    clipboard_selections.first().map(|s| s.first_line_indent);
 7735                if clipboard_selections.len() != old_selections.len() {
 7736                    clipboard_selections.drain(..);
 7737                }
 7738                let cursor_offset = this.selections.last::<usize>(cx).head();
 7739                let mut auto_indent_on_paste = true;
 7740
 7741                this.buffer.update(cx, |buffer, cx| {
 7742                    let snapshot = buffer.read(cx);
 7743                    auto_indent_on_paste =
 7744                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7745
 7746                    let mut start_offset = 0;
 7747                    let mut edits = Vec::new();
 7748                    let mut original_indent_columns = Vec::new();
 7749                    for (ix, selection) in old_selections.iter().enumerate() {
 7750                        let to_insert;
 7751                        let entire_line;
 7752                        let original_indent_column;
 7753                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7754                            let end_offset = start_offset + clipboard_selection.len;
 7755                            to_insert = &clipboard_text[start_offset..end_offset];
 7756                            entire_line = clipboard_selection.is_entire_line;
 7757                            start_offset = end_offset + 1;
 7758                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7759                        } else {
 7760                            to_insert = clipboard_text.as_str();
 7761                            entire_line = all_selections_were_entire_line;
 7762                            original_indent_column = first_selection_indent_column
 7763                        }
 7764
 7765                        // If the corresponding selection was empty when this slice of the
 7766                        // clipboard text was written, then the entire line containing the
 7767                        // selection was copied. If this selection is also currently empty,
 7768                        // then paste the line before the current line of the buffer.
 7769                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7770                            let column = selection.start.to_point(&snapshot).column as usize;
 7771                            let line_start = selection.start - column;
 7772                            line_start..line_start
 7773                        } else {
 7774                            selection.range()
 7775                        };
 7776
 7777                        edits.push((range, to_insert));
 7778                        original_indent_columns.extend(original_indent_column);
 7779                    }
 7780                    drop(snapshot);
 7781
 7782                    buffer.edit(
 7783                        edits,
 7784                        if auto_indent_on_paste {
 7785                            Some(AutoindentMode::Block {
 7786                                original_indent_columns,
 7787                            })
 7788                        } else {
 7789                            None
 7790                        },
 7791                        cx,
 7792                    );
 7793                });
 7794
 7795                let selections = this.selections.all::<usize>(cx);
 7796                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7797                    s.select(selections)
 7798                });
 7799            } else {
 7800                this.insert(&clipboard_text, window, cx);
 7801            }
 7802        });
 7803    }
 7804
 7805    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7806        if let Some(item) = cx.read_from_clipboard() {
 7807            let entries = item.entries();
 7808
 7809            match entries.first() {
 7810                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7811                // of all the pasted entries.
 7812                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7813                    .do_paste(
 7814                        clipboard_string.text(),
 7815                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7816                        true,
 7817                        window,
 7818                        cx,
 7819                    ),
 7820                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7821            }
 7822        }
 7823    }
 7824
 7825    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7826        if self.read_only(cx) {
 7827            return;
 7828        }
 7829
 7830        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7831            if let Some((selections, _)) =
 7832                self.selection_history.transaction(transaction_id).cloned()
 7833            {
 7834                self.change_selections(None, window, cx, |s| {
 7835                    s.select_anchors(selections.to_vec());
 7836                });
 7837            }
 7838            self.request_autoscroll(Autoscroll::fit(), cx);
 7839            self.unmark_text(window, cx);
 7840            self.refresh_inline_completion(true, false, window, cx);
 7841            cx.emit(EditorEvent::Edited { transaction_id });
 7842            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7843        }
 7844    }
 7845
 7846    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7847        if self.read_only(cx) {
 7848            return;
 7849        }
 7850
 7851        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7852            if let Some((_, Some(selections))) =
 7853                self.selection_history.transaction(transaction_id).cloned()
 7854            {
 7855                self.change_selections(None, window, cx, |s| {
 7856                    s.select_anchors(selections.to_vec());
 7857                });
 7858            }
 7859            self.request_autoscroll(Autoscroll::fit(), cx);
 7860            self.unmark_text(window, cx);
 7861            self.refresh_inline_completion(true, false, window, cx);
 7862            cx.emit(EditorEvent::Edited { transaction_id });
 7863        }
 7864    }
 7865
 7866    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7867        self.buffer
 7868            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7869    }
 7870
 7871    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7872        self.buffer
 7873            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7874    }
 7875
 7876    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7877        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7878            let line_mode = s.line_mode;
 7879            s.move_with(|map, selection| {
 7880                let cursor = if selection.is_empty() && !line_mode {
 7881                    movement::left(map, selection.start)
 7882                } else {
 7883                    selection.start
 7884                };
 7885                selection.collapse_to(cursor, SelectionGoal::None);
 7886            });
 7887        })
 7888    }
 7889
 7890    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7891        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7892            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7893        })
 7894    }
 7895
 7896    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7897        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7898            let line_mode = s.line_mode;
 7899            s.move_with(|map, selection| {
 7900                let cursor = if selection.is_empty() && !line_mode {
 7901                    movement::right(map, selection.end)
 7902                } else {
 7903                    selection.end
 7904                };
 7905                selection.collapse_to(cursor, SelectionGoal::None)
 7906            });
 7907        })
 7908    }
 7909
 7910    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7911        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7912            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7913        })
 7914    }
 7915
 7916    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7917        if self.take_rename(true, window, cx).is_some() {
 7918            return;
 7919        }
 7920
 7921        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7922            cx.propagate();
 7923            return;
 7924        }
 7925
 7926        let text_layout_details = &self.text_layout_details(window);
 7927        let selection_count = self.selections.count();
 7928        let first_selection = self.selections.first_anchor();
 7929
 7930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7931            let line_mode = s.line_mode;
 7932            s.move_with(|map, selection| {
 7933                if !selection.is_empty() && !line_mode {
 7934                    selection.goal = SelectionGoal::None;
 7935                }
 7936                let (cursor, goal) = movement::up(
 7937                    map,
 7938                    selection.start,
 7939                    selection.goal,
 7940                    false,
 7941                    text_layout_details,
 7942                );
 7943                selection.collapse_to(cursor, goal);
 7944            });
 7945        });
 7946
 7947        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7948        {
 7949            cx.propagate();
 7950        }
 7951    }
 7952
 7953    pub fn move_up_by_lines(
 7954        &mut self,
 7955        action: &MoveUpByLines,
 7956        window: &mut Window,
 7957        cx: &mut Context<Self>,
 7958    ) {
 7959        if self.take_rename(true, window, cx).is_some() {
 7960            return;
 7961        }
 7962
 7963        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7964            cx.propagate();
 7965            return;
 7966        }
 7967
 7968        let text_layout_details = &self.text_layout_details(window);
 7969
 7970        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7971            let line_mode = s.line_mode;
 7972            s.move_with(|map, selection| {
 7973                if !selection.is_empty() && !line_mode {
 7974                    selection.goal = SelectionGoal::None;
 7975                }
 7976                let (cursor, goal) = movement::up_by_rows(
 7977                    map,
 7978                    selection.start,
 7979                    action.lines,
 7980                    selection.goal,
 7981                    false,
 7982                    text_layout_details,
 7983                );
 7984                selection.collapse_to(cursor, goal);
 7985            });
 7986        })
 7987    }
 7988
 7989    pub fn move_down_by_lines(
 7990        &mut self,
 7991        action: &MoveDownByLines,
 7992        window: &mut Window,
 7993        cx: &mut Context<Self>,
 7994    ) {
 7995        if self.take_rename(true, window, cx).is_some() {
 7996            return;
 7997        }
 7998
 7999        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8000            cx.propagate();
 8001            return;
 8002        }
 8003
 8004        let text_layout_details = &self.text_layout_details(window);
 8005
 8006        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8007            let line_mode = s.line_mode;
 8008            s.move_with(|map, selection| {
 8009                if !selection.is_empty() && !line_mode {
 8010                    selection.goal = SelectionGoal::None;
 8011                }
 8012                let (cursor, goal) = movement::down_by_rows(
 8013                    map,
 8014                    selection.start,
 8015                    action.lines,
 8016                    selection.goal,
 8017                    false,
 8018                    text_layout_details,
 8019                );
 8020                selection.collapse_to(cursor, goal);
 8021            });
 8022        })
 8023    }
 8024
 8025    pub fn select_down_by_lines(
 8026        &mut self,
 8027        action: &SelectDownByLines,
 8028        window: &mut Window,
 8029        cx: &mut Context<Self>,
 8030    ) {
 8031        let text_layout_details = &self.text_layout_details(window);
 8032        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8033            s.move_heads_with(|map, head, goal| {
 8034                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8035            })
 8036        })
 8037    }
 8038
 8039    pub fn select_up_by_lines(
 8040        &mut self,
 8041        action: &SelectUpByLines,
 8042        window: &mut Window,
 8043        cx: &mut Context<Self>,
 8044    ) {
 8045        let text_layout_details = &self.text_layout_details(window);
 8046        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8047            s.move_heads_with(|map, head, goal| {
 8048                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8049            })
 8050        })
 8051    }
 8052
 8053    pub fn select_page_up(
 8054        &mut self,
 8055        _: &SelectPageUp,
 8056        window: &mut Window,
 8057        cx: &mut Context<Self>,
 8058    ) {
 8059        let Some(row_count) = self.visible_row_count() else {
 8060            return;
 8061        };
 8062
 8063        let text_layout_details = &self.text_layout_details(window);
 8064
 8065        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8066            s.move_heads_with(|map, head, goal| {
 8067                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8068            })
 8069        })
 8070    }
 8071
 8072    pub fn move_page_up(
 8073        &mut self,
 8074        action: &MovePageUp,
 8075        window: &mut Window,
 8076        cx: &mut Context<Self>,
 8077    ) {
 8078        if self.take_rename(true, window, cx).is_some() {
 8079            return;
 8080        }
 8081
 8082        if self
 8083            .context_menu
 8084            .borrow_mut()
 8085            .as_mut()
 8086            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8087            .unwrap_or(false)
 8088        {
 8089            return;
 8090        }
 8091
 8092        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8093            cx.propagate();
 8094            return;
 8095        }
 8096
 8097        let Some(row_count) = self.visible_row_count() else {
 8098            return;
 8099        };
 8100
 8101        let autoscroll = if action.center_cursor {
 8102            Autoscroll::center()
 8103        } else {
 8104            Autoscroll::fit()
 8105        };
 8106
 8107        let text_layout_details = &self.text_layout_details(window);
 8108
 8109        self.change_selections(Some(autoscroll), window, cx, |s| {
 8110            let line_mode = s.line_mode;
 8111            s.move_with(|map, selection| {
 8112                if !selection.is_empty() && !line_mode {
 8113                    selection.goal = SelectionGoal::None;
 8114                }
 8115                let (cursor, goal) = movement::up_by_rows(
 8116                    map,
 8117                    selection.end,
 8118                    row_count,
 8119                    selection.goal,
 8120                    false,
 8121                    text_layout_details,
 8122                );
 8123                selection.collapse_to(cursor, goal);
 8124            });
 8125        });
 8126    }
 8127
 8128    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8129        let text_layout_details = &self.text_layout_details(window);
 8130        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8131            s.move_heads_with(|map, head, goal| {
 8132                movement::up(map, head, goal, false, text_layout_details)
 8133            })
 8134        })
 8135    }
 8136
 8137    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8138        self.take_rename(true, window, cx);
 8139
 8140        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8141            cx.propagate();
 8142            return;
 8143        }
 8144
 8145        let text_layout_details = &self.text_layout_details(window);
 8146        let selection_count = self.selections.count();
 8147        let first_selection = self.selections.first_anchor();
 8148
 8149        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8150            let line_mode = s.line_mode;
 8151            s.move_with(|map, selection| {
 8152                if !selection.is_empty() && !line_mode {
 8153                    selection.goal = SelectionGoal::None;
 8154                }
 8155                let (cursor, goal) = movement::down(
 8156                    map,
 8157                    selection.end,
 8158                    selection.goal,
 8159                    false,
 8160                    text_layout_details,
 8161                );
 8162                selection.collapse_to(cursor, goal);
 8163            });
 8164        });
 8165
 8166        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8167        {
 8168            cx.propagate();
 8169        }
 8170    }
 8171
 8172    pub fn select_page_down(
 8173        &mut self,
 8174        _: &SelectPageDown,
 8175        window: &mut Window,
 8176        cx: &mut Context<Self>,
 8177    ) {
 8178        let Some(row_count) = self.visible_row_count() else {
 8179            return;
 8180        };
 8181
 8182        let text_layout_details = &self.text_layout_details(window);
 8183
 8184        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8185            s.move_heads_with(|map, head, goal| {
 8186                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8187            })
 8188        })
 8189    }
 8190
 8191    pub fn move_page_down(
 8192        &mut self,
 8193        action: &MovePageDown,
 8194        window: &mut Window,
 8195        cx: &mut Context<Self>,
 8196    ) {
 8197        if self.take_rename(true, window, cx).is_some() {
 8198            return;
 8199        }
 8200
 8201        if self
 8202            .context_menu
 8203            .borrow_mut()
 8204            .as_mut()
 8205            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8206            .unwrap_or(false)
 8207        {
 8208            return;
 8209        }
 8210
 8211        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8212            cx.propagate();
 8213            return;
 8214        }
 8215
 8216        let Some(row_count) = self.visible_row_count() else {
 8217            return;
 8218        };
 8219
 8220        let autoscroll = if action.center_cursor {
 8221            Autoscroll::center()
 8222        } else {
 8223            Autoscroll::fit()
 8224        };
 8225
 8226        let text_layout_details = &self.text_layout_details(window);
 8227        self.change_selections(Some(autoscroll), window, cx, |s| {
 8228            let line_mode = s.line_mode;
 8229            s.move_with(|map, selection| {
 8230                if !selection.is_empty() && !line_mode {
 8231                    selection.goal = SelectionGoal::None;
 8232                }
 8233                let (cursor, goal) = movement::down_by_rows(
 8234                    map,
 8235                    selection.end,
 8236                    row_count,
 8237                    selection.goal,
 8238                    false,
 8239                    text_layout_details,
 8240                );
 8241                selection.collapse_to(cursor, goal);
 8242            });
 8243        });
 8244    }
 8245
 8246    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8247        let text_layout_details = &self.text_layout_details(window);
 8248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8249            s.move_heads_with(|map, head, goal| {
 8250                movement::down(map, head, goal, false, text_layout_details)
 8251            })
 8252        });
 8253    }
 8254
 8255    pub fn context_menu_first(
 8256        &mut self,
 8257        _: &ContextMenuFirst,
 8258        _window: &mut Window,
 8259        cx: &mut Context<Self>,
 8260    ) {
 8261        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8262            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8263        }
 8264    }
 8265
 8266    pub fn context_menu_prev(
 8267        &mut self,
 8268        _: &ContextMenuPrev,
 8269        _window: &mut Window,
 8270        cx: &mut Context<Self>,
 8271    ) {
 8272        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8273            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8274        }
 8275    }
 8276
 8277    pub fn context_menu_next(
 8278        &mut self,
 8279        _: &ContextMenuNext,
 8280        _window: &mut Window,
 8281        cx: &mut Context<Self>,
 8282    ) {
 8283        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8284            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8285        }
 8286    }
 8287
 8288    pub fn context_menu_last(
 8289        &mut self,
 8290        _: &ContextMenuLast,
 8291        _window: &mut Window,
 8292        cx: &mut Context<Self>,
 8293    ) {
 8294        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8295            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8296        }
 8297    }
 8298
 8299    pub fn move_to_previous_word_start(
 8300        &mut self,
 8301        _: &MoveToPreviousWordStart,
 8302        window: &mut Window,
 8303        cx: &mut Context<Self>,
 8304    ) {
 8305        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8306            s.move_cursors_with(|map, head, _| {
 8307                (
 8308                    movement::previous_word_start(map, head),
 8309                    SelectionGoal::None,
 8310                )
 8311            });
 8312        })
 8313    }
 8314
 8315    pub fn move_to_previous_subword_start(
 8316        &mut self,
 8317        _: &MoveToPreviousSubwordStart,
 8318        window: &mut Window,
 8319        cx: &mut Context<Self>,
 8320    ) {
 8321        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8322            s.move_cursors_with(|map, head, _| {
 8323                (
 8324                    movement::previous_subword_start(map, head),
 8325                    SelectionGoal::None,
 8326                )
 8327            });
 8328        })
 8329    }
 8330
 8331    pub fn select_to_previous_word_start(
 8332        &mut self,
 8333        _: &SelectToPreviousWordStart,
 8334        window: &mut Window,
 8335        cx: &mut Context<Self>,
 8336    ) {
 8337        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8338            s.move_heads_with(|map, head, _| {
 8339                (
 8340                    movement::previous_word_start(map, head),
 8341                    SelectionGoal::None,
 8342                )
 8343            });
 8344        })
 8345    }
 8346
 8347    pub fn select_to_previous_subword_start(
 8348        &mut self,
 8349        _: &SelectToPreviousSubwordStart,
 8350        window: &mut Window,
 8351        cx: &mut Context<Self>,
 8352    ) {
 8353        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8354            s.move_heads_with(|map, head, _| {
 8355                (
 8356                    movement::previous_subword_start(map, head),
 8357                    SelectionGoal::None,
 8358                )
 8359            });
 8360        })
 8361    }
 8362
 8363    pub fn delete_to_previous_word_start(
 8364        &mut self,
 8365        action: &DeleteToPreviousWordStart,
 8366        window: &mut Window,
 8367        cx: &mut Context<Self>,
 8368    ) {
 8369        self.transact(window, cx, |this, window, cx| {
 8370            this.select_autoclose_pair(window, cx);
 8371            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8372                let line_mode = s.line_mode;
 8373                s.move_with(|map, selection| {
 8374                    if selection.is_empty() && !line_mode {
 8375                        let cursor = if action.ignore_newlines {
 8376                            movement::previous_word_start(map, selection.head())
 8377                        } else {
 8378                            movement::previous_word_start_or_newline(map, selection.head())
 8379                        };
 8380                        selection.set_head(cursor, SelectionGoal::None);
 8381                    }
 8382                });
 8383            });
 8384            this.insert("", window, cx);
 8385        });
 8386    }
 8387
 8388    pub fn delete_to_previous_subword_start(
 8389        &mut self,
 8390        _: &DeleteToPreviousSubwordStart,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        self.transact(window, cx, |this, window, cx| {
 8395            this.select_autoclose_pair(window, cx);
 8396            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8397                let line_mode = s.line_mode;
 8398                s.move_with(|map, selection| {
 8399                    if selection.is_empty() && !line_mode {
 8400                        let cursor = movement::previous_subword_start(map, selection.head());
 8401                        selection.set_head(cursor, SelectionGoal::None);
 8402                    }
 8403                });
 8404            });
 8405            this.insert("", window, cx);
 8406        });
 8407    }
 8408
 8409    pub fn move_to_next_word_end(
 8410        &mut self,
 8411        _: &MoveToNextWordEnd,
 8412        window: &mut Window,
 8413        cx: &mut Context<Self>,
 8414    ) {
 8415        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8416            s.move_cursors_with(|map, head, _| {
 8417                (movement::next_word_end(map, head), SelectionGoal::None)
 8418            });
 8419        })
 8420    }
 8421
 8422    pub fn move_to_next_subword_end(
 8423        &mut self,
 8424        _: &MoveToNextSubwordEnd,
 8425        window: &mut Window,
 8426        cx: &mut Context<Self>,
 8427    ) {
 8428        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8429            s.move_cursors_with(|map, head, _| {
 8430                (movement::next_subword_end(map, head), SelectionGoal::None)
 8431            });
 8432        })
 8433    }
 8434
 8435    pub fn select_to_next_word_end(
 8436        &mut self,
 8437        _: &SelectToNextWordEnd,
 8438        window: &mut Window,
 8439        cx: &mut Context<Self>,
 8440    ) {
 8441        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8442            s.move_heads_with(|map, head, _| {
 8443                (movement::next_word_end(map, head), SelectionGoal::None)
 8444            });
 8445        })
 8446    }
 8447
 8448    pub fn select_to_next_subword_end(
 8449        &mut self,
 8450        _: &SelectToNextSubwordEnd,
 8451        window: &mut Window,
 8452        cx: &mut Context<Self>,
 8453    ) {
 8454        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8455            s.move_heads_with(|map, head, _| {
 8456                (movement::next_subword_end(map, head), SelectionGoal::None)
 8457            });
 8458        })
 8459    }
 8460
 8461    pub fn delete_to_next_word_end(
 8462        &mut self,
 8463        action: &DeleteToNextWordEnd,
 8464        window: &mut Window,
 8465        cx: &mut Context<Self>,
 8466    ) {
 8467        self.transact(window, cx, |this, window, cx| {
 8468            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8469                let line_mode = s.line_mode;
 8470                s.move_with(|map, selection| {
 8471                    if selection.is_empty() && !line_mode {
 8472                        let cursor = if action.ignore_newlines {
 8473                            movement::next_word_end(map, selection.head())
 8474                        } else {
 8475                            movement::next_word_end_or_newline(map, selection.head())
 8476                        };
 8477                        selection.set_head(cursor, SelectionGoal::None);
 8478                    }
 8479                });
 8480            });
 8481            this.insert("", window, cx);
 8482        });
 8483    }
 8484
 8485    pub fn delete_to_next_subword_end(
 8486        &mut self,
 8487        _: &DeleteToNextSubwordEnd,
 8488        window: &mut Window,
 8489        cx: &mut Context<Self>,
 8490    ) {
 8491        self.transact(window, cx, |this, window, cx| {
 8492            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8493                s.move_with(|map, selection| {
 8494                    if selection.is_empty() {
 8495                        let cursor = movement::next_subword_end(map, selection.head());
 8496                        selection.set_head(cursor, SelectionGoal::None);
 8497                    }
 8498                });
 8499            });
 8500            this.insert("", window, cx);
 8501        });
 8502    }
 8503
 8504    pub fn move_to_beginning_of_line(
 8505        &mut self,
 8506        action: &MoveToBeginningOfLine,
 8507        window: &mut Window,
 8508        cx: &mut Context<Self>,
 8509    ) {
 8510        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8511            s.move_cursors_with(|map, head, _| {
 8512                (
 8513                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8514                    SelectionGoal::None,
 8515                )
 8516            });
 8517        })
 8518    }
 8519
 8520    pub fn select_to_beginning_of_line(
 8521        &mut self,
 8522        action: &SelectToBeginningOfLine,
 8523        window: &mut Window,
 8524        cx: &mut Context<Self>,
 8525    ) {
 8526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8527            s.move_heads_with(|map, head, _| {
 8528                (
 8529                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8530                    SelectionGoal::None,
 8531                )
 8532            });
 8533        });
 8534    }
 8535
 8536    pub fn delete_to_beginning_of_line(
 8537        &mut self,
 8538        _: &DeleteToBeginningOfLine,
 8539        window: &mut Window,
 8540        cx: &mut Context<Self>,
 8541    ) {
 8542        self.transact(window, cx, |this, window, cx| {
 8543            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8544                s.move_with(|_, selection| {
 8545                    selection.reversed = true;
 8546                });
 8547            });
 8548
 8549            this.select_to_beginning_of_line(
 8550                &SelectToBeginningOfLine {
 8551                    stop_at_soft_wraps: false,
 8552                },
 8553                window,
 8554                cx,
 8555            );
 8556            this.backspace(&Backspace, window, cx);
 8557        });
 8558    }
 8559
 8560    pub fn move_to_end_of_line(
 8561        &mut self,
 8562        action: &MoveToEndOfLine,
 8563        window: &mut Window,
 8564        cx: &mut Context<Self>,
 8565    ) {
 8566        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8567            s.move_cursors_with(|map, head, _| {
 8568                (
 8569                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8570                    SelectionGoal::None,
 8571                )
 8572            });
 8573        })
 8574    }
 8575
 8576    pub fn select_to_end_of_line(
 8577        &mut self,
 8578        action: &SelectToEndOfLine,
 8579        window: &mut Window,
 8580        cx: &mut Context<Self>,
 8581    ) {
 8582        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8583            s.move_heads_with(|map, head, _| {
 8584                (
 8585                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8586                    SelectionGoal::None,
 8587                )
 8588            });
 8589        })
 8590    }
 8591
 8592    pub fn delete_to_end_of_line(
 8593        &mut self,
 8594        _: &DeleteToEndOfLine,
 8595        window: &mut Window,
 8596        cx: &mut Context<Self>,
 8597    ) {
 8598        self.transact(window, cx, |this, window, cx| {
 8599            this.select_to_end_of_line(
 8600                &SelectToEndOfLine {
 8601                    stop_at_soft_wraps: false,
 8602                },
 8603                window,
 8604                cx,
 8605            );
 8606            this.delete(&Delete, window, cx);
 8607        });
 8608    }
 8609
 8610    pub fn cut_to_end_of_line(
 8611        &mut self,
 8612        _: &CutToEndOfLine,
 8613        window: &mut Window,
 8614        cx: &mut Context<Self>,
 8615    ) {
 8616        self.transact(window, cx, |this, window, cx| {
 8617            this.select_to_end_of_line(
 8618                &SelectToEndOfLine {
 8619                    stop_at_soft_wraps: false,
 8620                },
 8621                window,
 8622                cx,
 8623            );
 8624            this.cut(&Cut, window, cx);
 8625        });
 8626    }
 8627
 8628    pub fn move_to_start_of_paragraph(
 8629        &mut self,
 8630        _: &MoveToStartOfParagraph,
 8631        window: &mut Window,
 8632        cx: &mut Context<Self>,
 8633    ) {
 8634        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8635            cx.propagate();
 8636            return;
 8637        }
 8638
 8639        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8640            s.move_with(|map, selection| {
 8641                selection.collapse_to(
 8642                    movement::start_of_paragraph(map, selection.head(), 1),
 8643                    SelectionGoal::None,
 8644                )
 8645            });
 8646        })
 8647    }
 8648
 8649    pub fn move_to_end_of_paragraph(
 8650        &mut self,
 8651        _: &MoveToEndOfParagraph,
 8652        window: &mut Window,
 8653        cx: &mut Context<Self>,
 8654    ) {
 8655        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8656            cx.propagate();
 8657            return;
 8658        }
 8659
 8660        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8661            s.move_with(|map, selection| {
 8662                selection.collapse_to(
 8663                    movement::end_of_paragraph(map, selection.head(), 1),
 8664                    SelectionGoal::None,
 8665                )
 8666            });
 8667        })
 8668    }
 8669
 8670    pub fn select_to_start_of_paragraph(
 8671        &mut self,
 8672        _: &SelectToStartOfParagraph,
 8673        window: &mut Window,
 8674        cx: &mut Context<Self>,
 8675    ) {
 8676        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8677            cx.propagate();
 8678            return;
 8679        }
 8680
 8681        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8682            s.move_heads_with(|map, head, _| {
 8683                (
 8684                    movement::start_of_paragraph(map, head, 1),
 8685                    SelectionGoal::None,
 8686                )
 8687            });
 8688        })
 8689    }
 8690
 8691    pub fn select_to_end_of_paragraph(
 8692        &mut self,
 8693        _: &SelectToEndOfParagraph,
 8694        window: &mut Window,
 8695        cx: &mut Context<Self>,
 8696    ) {
 8697        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8698            cx.propagate();
 8699            return;
 8700        }
 8701
 8702        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8703            s.move_heads_with(|map, head, _| {
 8704                (
 8705                    movement::end_of_paragraph(map, head, 1),
 8706                    SelectionGoal::None,
 8707                )
 8708            });
 8709        })
 8710    }
 8711
 8712    pub fn move_to_beginning(
 8713        &mut self,
 8714        _: &MoveToBeginning,
 8715        window: &mut Window,
 8716        cx: &mut Context<Self>,
 8717    ) {
 8718        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8719            cx.propagate();
 8720            return;
 8721        }
 8722
 8723        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8724            s.select_ranges(vec![0..0]);
 8725        });
 8726    }
 8727
 8728    pub fn select_to_beginning(
 8729        &mut self,
 8730        _: &SelectToBeginning,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        let mut selection = self.selections.last::<Point>(cx);
 8735        selection.set_head(Point::zero(), SelectionGoal::None);
 8736
 8737        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8738            s.select(vec![selection]);
 8739        });
 8740    }
 8741
 8742    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8743        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8744            cx.propagate();
 8745            return;
 8746        }
 8747
 8748        let cursor = self.buffer.read(cx).read(cx).len();
 8749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8750            s.select_ranges(vec![cursor..cursor])
 8751        });
 8752    }
 8753
 8754    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8755        self.nav_history = nav_history;
 8756    }
 8757
 8758    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8759        self.nav_history.as_ref()
 8760    }
 8761
 8762    fn push_to_nav_history(
 8763        &mut self,
 8764        cursor_anchor: Anchor,
 8765        new_position: Option<Point>,
 8766        cx: &mut Context<Self>,
 8767    ) {
 8768        if let Some(nav_history) = self.nav_history.as_mut() {
 8769            let buffer = self.buffer.read(cx).read(cx);
 8770            let cursor_position = cursor_anchor.to_point(&buffer);
 8771            let scroll_state = self.scroll_manager.anchor();
 8772            let scroll_top_row = scroll_state.top_row(&buffer);
 8773            drop(buffer);
 8774
 8775            if let Some(new_position) = new_position {
 8776                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8777                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8778                    return;
 8779                }
 8780            }
 8781
 8782            nav_history.push(
 8783                Some(NavigationData {
 8784                    cursor_anchor,
 8785                    cursor_position,
 8786                    scroll_anchor: scroll_state,
 8787                    scroll_top_row,
 8788                }),
 8789                cx,
 8790            );
 8791        }
 8792    }
 8793
 8794    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8795        let buffer = self.buffer.read(cx).snapshot(cx);
 8796        let mut selection = self.selections.first::<usize>(cx);
 8797        selection.set_head(buffer.len(), SelectionGoal::None);
 8798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8799            s.select(vec![selection]);
 8800        });
 8801    }
 8802
 8803    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8804        let end = self.buffer.read(cx).read(cx).len();
 8805        self.change_selections(None, window, cx, |s| {
 8806            s.select_ranges(vec![0..end]);
 8807        });
 8808    }
 8809
 8810    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8811        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8812        let mut selections = self.selections.all::<Point>(cx);
 8813        let max_point = display_map.buffer_snapshot.max_point();
 8814        for selection in &mut selections {
 8815            let rows = selection.spanned_rows(true, &display_map);
 8816            selection.start = Point::new(rows.start.0, 0);
 8817            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8818            selection.reversed = false;
 8819        }
 8820        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8821            s.select(selections);
 8822        });
 8823    }
 8824
 8825    pub fn split_selection_into_lines(
 8826        &mut self,
 8827        _: &SplitSelectionIntoLines,
 8828        window: &mut Window,
 8829        cx: &mut Context<Self>,
 8830    ) {
 8831        let mut to_unfold = Vec::new();
 8832        let mut new_selection_ranges = Vec::new();
 8833        {
 8834            let selections = self.selections.all::<Point>(cx);
 8835            let buffer = self.buffer.read(cx).read(cx);
 8836            for selection in selections {
 8837                for row in selection.start.row..selection.end.row {
 8838                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8839                    new_selection_ranges.push(cursor..cursor);
 8840                }
 8841                new_selection_ranges.push(selection.end..selection.end);
 8842                to_unfold.push(selection.start..selection.end);
 8843            }
 8844        }
 8845        self.unfold_ranges(&to_unfold, true, true, cx);
 8846        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8847            s.select_ranges(new_selection_ranges);
 8848        });
 8849    }
 8850
 8851    pub fn add_selection_above(
 8852        &mut self,
 8853        _: &AddSelectionAbove,
 8854        window: &mut Window,
 8855        cx: &mut Context<Self>,
 8856    ) {
 8857        self.add_selection(true, window, cx);
 8858    }
 8859
 8860    pub fn add_selection_below(
 8861        &mut self,
 8862        _: &AddSelectionBelow,
 8863        window: &mut Window,
 8864        cx: &mut Context<Self>,
 8865    ) {
 8866        self.add_selection(false, window, cx);
 8867    }
 8868
 8869    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8870        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8871        let mut selections = self.selections.all::<Point>(cx);
 8872        let text_layout_details = self.text_layout_details(window);
 8873        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8874            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8875            let range = oldest_selection.display_range(&display_map).sorted();
 8876
 8877            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8878            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8879            let positions = start_x.min(end_x)..start_x.max(end_x);
 8880
 8881            selections.clear();
 8882            let mut stack = Vec::new();
 8883            for row in range.start.row().0..=range.end.row().0 {
 8884                if let Some(selection) = self.selections.build_columnar_selection(
 8885                    &display_map,
 8886                    DisplayRow(row),
 8887                    &positions,
 8888                    oldest_selection.reversed,
 8889                    &text_layout_details,
 8890                ) {
 8891                    stack.push(selection.id);
 8892                    selections.push(selection);
 8893                }
 8894            }
 8895
 8896            if above {
 8897                stack.reverse();
 8898            }
 8899
 8900            AddSelectionsState { above, stack }
 8901        });
 8902
 8903        let last_added_selection = *state.stack.last().unwrap();
 8904        let mut new_selections = Vec::new();
 8905        if above == state.above {
 8906            let end_row = if above {
 8907                DisplayRow(0)
 8908            } else {
 8909                display_map.max_point().row()
 8910            };
 8911
 8912            'outer: for selection in selections {
 8913                if selection.id == last_added_selection {
 8914                    let range = selection.display_range(&display_map).sorted();
 8915                    debug_assert_eq!(range.start.row(), range.end.row());
 8916                    let mut row = range.start.row();
 8917                    let positions =
 8918                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8919                            px(start)..px(end)
 8920                        } else {
 8921                            let start_x =
 8922                                display_map.x_for_display_point(range.start, &text_layout_details);
 8923                            let end_x =
 8924                                display_map.x_for_display_point(range.end, &text_layout_details);
 8925                            start_x.min(end_x)..start_x.max(end_x)
 8926                        };
 8927
 8928                    while row != end_row {
 8929                        if above {
 8930                            row.0 -= 1;
 8931                        } else {
 8932                            row.0 += 1;
 8933                        }
 8934
 8935                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8936                            &display_map,
 8937                            row,
 8938                            &positions,
 8939                            selection.reversed,
 8940                            &text_layout_details,
 8941                        ) {
 8942                            state.stack.push(new_selection.id);
 8943                            if above {
 8944                                new_selections.push(new_selection);
 8945                                new_selections.push(selection);
 8946                            } else {
 8947                                new_selections.push(selection);
 8948                                new_selections.push(new_selection);
 8949                            }
 8950
 8951                            continue 'outer;
 8952                        }
 8953                    }
 8954                }
 8955
 8956                new_selections.push(selection);
 8957            }
 8958        } else {
 8959            new_selections = selections;
 8960            new_selections.retain(|s| s.id != last_added_selection);
 8961            state.stack.pop();
 8962        }
 8963
 8964        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8965            s.select(new_selections);
 8966        });
 8967        if state.stack.len() > 1 {
 8968            self.add_selections_state = Some(state);
 8969        }
 8970    }
 8971
 8972    pub fn select_next_match_internal(
 8973        &mut self,
 8974        display_map: &DisplaySnapshot,
 8975        replace_newest: bool,
 8976        autoscroll: Option<Autoscroll>,
 8977        window: &mut Window,
 8978        cx: &mut Context<Self>,
 8979    ) -> Result<()> {
 8980        fn select_next_match_ranges(
 8981            this: &mut Editor,
 8982            range: Range<usize>,
 8983            replace_newest: bool,
 8984            auto_scroll: Option<Autoscroll>,
 8985            window: &mut Window,
 8986            cx: &mut Context<Editor>,
 8987        ) {
 8988            this.unfold_ranges(&[range.clone()], false, true, cx);
 8989            this.change_selections(auto_scroll, window, cx, |s| {
 8990                if replace_newest {
 8991                    s.delete(s.newest_anchor().id);
 8992                }
 8993                s.insert_range(range.clone());
 8994            });
 8995        }
 8996
 8997        let buffer = &display_map.buffer_snapshot;
 8998        let mut selections = self.selections.all::<usize>(cx);
 8999        if let Some(mut select_next_state) = self.select_next_state.take() {
 9000            let query = &select_next_state.query;
 9001            if !select_next_state.done {
 9002                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9003                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9004                let mut next_selected_range = None;
 9005
 9006                let bytes_after_last_selection =
 9007                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9008                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9009                let query_matches = query
 9010                    .stream_find_iter(bytes_after_last_selection)
 9011                    .map(|result| (last_selection.end, result))
 9012                    .chain(
 9013                        query
 9014                            .stream_find_iter(bytes_before_first_selection)
 9015                            .map(|result| (0, result)),
 9016                    );
 9017
 9018                for (start_offset, query_match) in query_matches {
 9019                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9020                    let offset_range =
 9021                        start_offset + query_match.start()..start_offset + query_match.end();
 9022                    let display_range = offset_range.start.to_display_point(display_map)
 9023                        ..offset_range.end.to_display_point(display_map);
 9024
 9025                    if !select_next_state.wordwise
 9026                        || (!movement::is_inside_word(display_map, display_range.start)
 9027                            && !movement::is_inside_word(display_map, display_range.end))
 9028                    {
 9029                        // TODO: This is n^2, because we might check all the selections
 9030                        if !selections
 9031                            .iter()
 9032                            .any(|selection| selection.range().overlaps(&offset_range))
 9033                        {
 9034                            next_selected_range = Some(offset_range);
 9035                            break;
 9036                        }
 9037                    }
 9038                }
 9039
 9040                if let Some(next_selected_range) = next_selected_range {
 9041                    select_next_match_ranges(
 9042                        self,
 9043                        next_selected_range,
 9044                        replace_newest,
 9045                        autoscroll,
 9046                        window,
 9047                        cx,
 9048                    );
 9049                } else {
 9050                    select_next_state.done = true;
 9051                }
 9052            }
 9053
 9054            self.select_next_state = Some(select_next_state);
 9055        } else {
 9056            let mut only_carets = true;
 9057            let mut same_text_selected = true;
 9058            let mut selected_text = None;
 9059
 9060            let mut selections_iter = selections.iter().peekable();
 9061            while let Some(selection) = selections_iter.next() {
 9062                if selection.start != selection.end {
 9063                    only_carets = false;
 9064                }
 9065
 9066                if same_text_selected {
 9067                    if selected_text.is_none() {
 9068                        selected_text =
 9069                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9070                    }
 9071
 9072                    if let Some(next_selection) = selections_iter.peek() {
 9073                        if next_selection.range().len() == selection.range().len() {
 9074                            let next_selected_text = buffer
 9075                                .text_for_range(next_selection.range())
 9076                                .collect::<String>();
 9077                            if Some(next_selected_text) != selected_text {
 9078                                same_text_selected = false;
 9079                                selected_text = None;
 9080                            }
 9081                        } else {
 9082                            same_text_selected = false;
 9083                            selected_text = None;
 9084                        }
 9085                    }
 9086                }
 9087            }
 9088
 9089            if only_carets {
 9090                for selection in &mut selections {
 9091                    let word_range = movement::surrounding_word(
 9092                        display_map,
 9093                        selection.start.to_display_point(display_map),
 9094                    );
 9095                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9096                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9097                    selection.goal = SelectionGoal::None;
 9098                    selection.reversed = false;
 9099                    select_next_match_ranges(
 9100                        self,
 9101                        selection.start..selection.end,
 9102                        replace_newest,
 9103                        autoscroll,
 9104                        window,
 9105                        cx,
 9106                    );
 9107                }
 9108
 9109                if selections.len() == 1 {
 9110                    let selection = selections
 9111                        .last()
 9112                        .expect("ensured that there's only one selection");
 9113                    let query = buffer
 9114                        .text_for_range(selection.start..selection.end)
 9115                        .collect::<String>();
 9116                    let is_empty = query.is_empty();
 9117                    let select_state = SelectNextState {
 9118                        query: AhoCorasick::new(&[query])?,
 9119                        wordwise: true,
 9120                        done: is_empty,
 9121                    };
 9122                    self.select_next_state = Some(select_state);
 9123                } else {
 9124                    self.select_next_state = None;
 9125                }
 9126            } else if let Some(selected_text) = selected_text {
 9127                self.select_next_state = Some(SelectNextState {
 9128                    query: AhoCorasick::new(&[selected_text])?,
 9129                    wordwise: false,
 9130                    done: false,
 9131                });
 9132                self.select_next_match_internal(
 9133                    display_map,
 9134                    replace_newest,
 9135                    autoscroll,
 9136                    window,
 9137                    cx,
 9138                )?;
 9139            }
 9140        }
 9141        Ok(())
 9142    }
 9143
 9144    pub fn select_all_matches(
 9145        &mut self,
 9146        _action: &SelectAllMatches,
 9147        window: &mut Window,
 9148        cx: &mut Context<Self>,
 9149    ) -> Result<()> {
 9150        self.push_to_selection_history();
 9151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9152
 9153        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9154        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9155            return Ok(());
 9156        };
 9157        if select_next_state.done {
 9158            return Ok(());
 9159        }
 9160
 9161        let mut new_selections = self.selections.all::<usize>(cx);
 9162
 9163        let buffer = &display_map.buffer_snapshot;
 9164        let query_matches = select_next_state
 9165            .query
 9166            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9167
 9168        for query_match in query_matches {
 9169            let query_match = query_match.unwrap(); // can only fail due to I/O
 9170            let offset_range = query_match.start()..query_match.end();
 9171            let display_range = offset_range.start.to_display_point(&display_map)
 9172                ..offset_range.end.to_display_point(&display_map);
 9173
 9174            if !select_next_state.wordwise
 9175                || (!movement::is_inside_word(&display_map, display_range.start)
 9176                    && !movement::is_inside_word(&display_map, display_range.end))
 9177            {
 9178                self.selections.change_with(cx, |selections| {
 9179                    new_selections.push(Selection {
 9180                        id: selections.new_selection_id(),
 9181                        start: offset_range.start,
 9182                        end: offset_range.end,
 9183                        reversed: false,
 9184                        goal: SelectionGoal::None,
 9185                    });
 9186                });
 9187            }
 9188        }
 9189
 9190        new_selections.sort_by_key(|selection| selection.start);
 9191        let mut ix = 0;
 9192        while ix + 1 < new_selections.len() {
 9193            let current_selection = &new_selections[ix];
 9194            let next_selection = &new_selections[ix + 1];
 9195            if current_selection.range().overlaps(&next_selection.range()) {
 9196                if current_selection.id < next_selection.id {
 9197                    new_selections.remove(ix + 1);
 9198                } else {
 9199                    new_selections.remove(ix);
 9200                }
 9201            } else {
 9202                ix += 1;
 9203            }
 9204        }
 9205
 9206        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9207
 9208        for selection in new_selections.iter_mut() {
 9209            selection.reversed = reversed;
 9210        }
 9211
 9212        select_next_state.done = true;
 9213        self.unfold_ranges(
 9214            &new_selections
 9215                .iter()
 9216                .map(|selection| selection.range())
 9217                .collect::<Vec<_>>(),
 9218            false,
 9219            false,
 9220            cx,
 9221        );
 9222        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9223            selections.select(new_selections)
 9224        });
 9225
 9226        Ok(())
 9227    }
 9228
 9229    pub fn select_next(
 9230        &mut self,
 9231        action: &SelectNext,
 9232        window: &mut Window,
 9233        cx: &mut Context<Self>,
 9234    ) -> Result<()> {
 9235        self.push_to_selection_history();
 9236        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9237        self.select_next_match_internal(
 9238            &display_map,
 9239            action.replace_newest,
 9240            Some(Autoscroll::newest()),
 9241            window,
 9242            cx,
 9243        )?;
 9244        Ok(())
 9245    }
 9246
 9247    pub fn select_previous(
 9248        &mut self,
 9249        action: &SelectPrevious,
 9250        window: &mut Window,
 9251        cx: &mut Context<Self>,
 9252    ) -> Result<()> {
 9253        self.push_to_selection_history();
 9254        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9255        let buffer = &display_map.buffer_snapshot;
 9256        let mut selections = self.selections.all::<usize>(cx);
 9257        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9258            let query = &select_prev_state.query;
 9259            if !select_prev_state.done {
 9260                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9261                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9262                let mut next_selected_range = None;
 9263                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9264                let bytes_before_last_selection =
 9265                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9266                let bytes_after_first_selection =
 9267                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9268                let query_matches = query
 9269                    .stream_find_iter(bytes_before_last_selection)
 9270                    .map(|result| (last_selection.start, result))
 9271                    .chain(
 9272                        query
 9273                            .stream_find_iter(bytes_after_first_selection)
 9274                            .map(|result| (buffer.len(), result)),
 9275                    );
 9276                for (end_offset, query_match) in query_matches {
 9277                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9278                    let offset_range =
 9279                        end_offset - query_match.end()..end_offset - query_match.start();
 9280                    let display_range = offset_range.start.to_display_point(&display_map)
 9281                        ..offset_range.end.to_display_point(&display_map);
 9282
 9283                    if !select_prev_state.wordwise
 9284                        || (!movement::is_inside_word(&display_map, display_range.start)
 9285                            && !movement::is_inside_word(&display_map, display_range.end))
 9286                    {
 9287                        next_selected_range = Some(offset_range);
 9288                        break;
 9289                    }
 9290                }
 9291
 9292                if let Some(next_selected_range) = next_selected_range {
 9293                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9294                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9295                        if action.replace_newest {
 9296                            s.delete(s.newest_anchor().id);
 9297                        }
 9298                        s.insert_range(next_selected_range);
 9299                    });
 9300                } else {
 9301                    select_prev_state.done = true;
 9302                }
 9303            }
 9304
 9305            self.select_prev_state = Some(select_prev_state);
 9306        } else {
 9307            let mut only_carets = true;
 9308            let mut same_text_selected = true;
 9309            let mut selected_text = None;
 9310
 9311            let mut selections_iter = selections.iter().peekable();
 9312            while let Some(selection) = selections_iter.next() {
 9313                if selection.start != selection.end {
 9314                    only_carets = false;
 9315                }
 9316
 9317                if same_text_selected {
 9318                    if selected_text.is_none() {
 9319                        selected_text =
 9320                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9321                    }
 9322
 9323                    if let Some(next_selection) = selections_iter.peek() {
 9324                        if next_selection.range().len() == selection.range().len() {
 9325                            let next_selected_text = buffer
 9326                                .text_for_range(next_selection.range())
 9327                                .collect::<String>();
 9328                            if Some(next_selected_text) != selected_text {
 9329                                same_text_selected = false;
 9330                                selected_text = None;
 9331                            }
 9332                        } else {
 9333                            same_text_selected = false;
 9334                            selected_text = None;
 9335                        }
 9336                    }
 9337                }
 9338            }
 9339
 9340            if only_carets {
 9341                for selection in &mut selections {
 9342                    let word_range = movement::surrounding_word(
 9343                        &display_map,
 9344                        selection.start.to_display_point(&display_map),
 9345                    );
 9346                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9347                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9348                    selection.goal = SelectionGoal::None;
 9349                    selection.reversed = false;
 9350                }
 9351                if selections.len() == 1 {
 9352                    let selection = selections
 9353                        .last()
 9354                        .expect("ensured that there's only one selection");
 9355                    let query = buffer
 9356                        .text_for_range(selection.start..selection.end)
 9357                        .collect::<String>();
 9358                    let is_empty = query.is_empty();
 9359                    let select_state = SelectNextState {
 9360                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9361                        wordwise: true,
 9362                        done: is_empty,
 9363                    };
 9364                    self.select_prev_state = Some(select_state);
 9365                } else {
 9366                    self.select_prev_state = None;
 9367                }
 9368
 9369                self.unfold_ranges(
 9370                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9371                    false,
 9372                    true,
 9373                    cx,
 9374                );
 9375                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9376                    s.select(selections);
 9377                });
 9378            } else if let Some(selected_text) = selected_text {
 9379                self.select_prev_state = Some(SelectNextState {
 9380                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9381                    wordwise: false,
 9382                    done: false,
 9383                });
 9384                self.select_previous(action, window, cx)?;
 9385            }
 9386        }
 9387        Ok(())
 9388    }
 9389
 9390    pub fn toggle_comments(
 9391        &mut self,
 9392        action: &ToggleComments,
 9393        window: &mut Window,
 9394        cx: &mut Context<Self>,
 9395    ) {
 9396        if self.read_only(cx) {
 9397            return;
 9398        }
 9399        let text_layout_details = &self.text_layout_details(window);
 9400        self.transact(window, cx, |this, window, cx| {
 9401            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9402            let mut edits = Vec::new();
 9403            let mut selection_edit_ranges = Vec::new();
 9404            let mut last_toggled_row = None;
 9405            let snapshot = this.buffer.read(cx).read(cx);
 9406            let empty_str: Arc<str> = Arc::default();
 9407            let mut suffixes_inserted = Vec::new();
 9408            let ignore_indent = action.ignore_indent;
 9409
 9410            fn comment_prefix_range(
 9411                snapshot: &MultiBufferSnapshot,
 9412                row: MultiBufferRow,
 9413                comment_prefix: &str,
 9414                comment_prefix_whitespace: &str,
 9415                ignore_indent: bool,
 9416            ) -> Range<Point> {
 9417                let indent_size = if ignore_indent {
 9418                    0
 9419                } else {
 9420                    snapshot.indent_size_for_line(row).len
 9421                };
 9422
 9423                let start = Point::new(row.0, indent_size);
 9424
 9425                let mut line_bytes = snapshot
 9426                    .bytes_in_range(start..snapshot.max_point())
 9427                    .flatten()
 9428                    .copied();
 9429
 9430                // If this line currently begins with the line comment prefix, then record
 9431                // the range containing the prefix.
 9432                if line_bytes
 9433                    .by_ref()
 9434                    .take(comment_prefix.len())
 9435                    .eq(comment_prefix.bytes())
 9436                {
 9437                    // Include any whitespace that matches the comment prefix.
 9438                    let matching_whitespace_len = line_bytes
 9439                        .zip(comment_prefix_whitespace.bytes())
 9440                        .take_while(|(a, b)| a == b)
 9441                        .count() as u32;
 9442                    let end = Point::new(
 9443                        start.row,
 9444                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9445                    );
 9446                    start..end
 9447                } else {
 9448                    start..start
 9449                }
 9450            }
 9451
 9452            fn comment_suffix_range(
 9453                snapshot: &MultiBufferSnapshot,
 9454                row: MultiBufferRow,
 9455                comment_suffix: &str,
 9456                comment_suffix_has_leading_space: bool,
 9457            ) -> Range<Point> {
 9458                let end = Point::new(row.0, snapshot.line_len(row));
 9459                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9460
 9461                let mut line_end_bytes = snapshot
 9462                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9463                    .flatten()
 9464                    .copied();
 9465
 9466                let leading_space_len = if suffix_start_column > 0
 9467                    && line_end_bytes.next() == Some(b' ')
 9468                    && comment_suffix_has_leading_space
 9469                {
 9470                    1
 9471                } else {
 9472                    0
 9473                };
 9474
 9475                // If this line currently begins with the line comment prefix, then record
 9476                // the range containing the prefix.
 9477                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9478                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9479                    start..end
 9480                } else {
 9481                    end..end
 9482                }
 9483            }
 9484
 9485            // TODO: Handle selections that cross excerpts
 9486            for selection in &mut selections {
 9487                let start_column = snapshot
 9488                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9489                    .len;
 9490                let language = if let Some(language) =
 9491                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9492                {
 9493                    language
 9494                } else {
 9495                    continue;
 9496                };
 9497
 9498                selection_edit_ranges.clear();
 9499
 9500                // If multiple selections contain a given row, avoid processing that
 9501                // row more than once.
 9502                let mut start_row = MultiBufferRow(selection.start.row);
 9503                if last_toggled_row == Some(start_row) {
 9504                    start_row = start_row.next_row();
 9505                }
 9506                let end_row =
 9507                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9508                        MultiBufferRow(selection.end.row - 1)
 9509                    } else {
 9510                        MultiBufferRow(selection.end.row)
 9511                    };
 9512                last_toggled_row = Some(end_row);
 9513
 9514                if start_row > end_row {
 9515                    continue;
 9516                }
 9517
 9518                // If the language has line comments, toggle those.
 9519                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9520
 9521                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9522                if ignore_indent {
 9523                    full_comment_prefixes = full_comment_prefixes
 9524                        .into_iter()
 9525                        .map(|s| Arc::from(s.trim_end()))
 9526                        .collect();
 9527                }
 9528
 9529                if !full_comment_prefixes.is_empty() {
 9530                    let first_prefix = full_comment_prefixes
 9531                        .first()
 9532                        .expect("prefixes is non-empty");
 9533                    let prefix_trimmed_lengths = full_comment_prefixes
 9534                        .iter()
 9535                        .map(|p| p.trim_end_matches(' ').len())
 9536                        .collect::<SmallVec<[usize; 4]>>();
 9537
 9538                    let mut all_selection_lines_are_comments = true;
 9539
 9540                    for row in start_row.0..=end_row.0 {
 9541                        let row = MultiBufferRow(row);
 9542                        if start_row < end_row && snapshot.is_line_blank(row) {
 9543                            continue;
 9544                        }
 9545
 9546                        let prefix_range = full_comment_prefixes
 9547                            .iter()
 9548                            .zip(prefix_trimmed_lengths.iter().copied())
 9549                            .map(|(prefix, trimmed_prefix_len)| {
 9550                                comment_prefix_range(
 9551                                    snapshot.deref(),
 9552                                    row,
 9553                                    &prefix[..trimmed_prefix_len],
 9554                                    &prefix[trimmed_prefix_len..],
 9555                                    ignore_indent,
 9556                                )
 9557                            })
 9558                            .max_by_key(|range| range.end.column - range.start.column)
 9559                            .expect("prefixes is non-empty");
 9560
 9561                        if prefix_range.is_empty() {
 9562                            all_selection_lines_are_comments = false;
 9563                        }
 9564
 9565                        selection_edit_ranges.push(prefix_range);
 9566                    }
 9567
 9568                    if all_selection_lines_are_comments {
 9569                        edits.extend(
 9570                            selection_edit_ranges
 9571                                .iter()
 9572                                .cloned()
 9573                                .map(|range| (range, empty_str.clone())),
 9574                        );
 9575                    } else {
 9576                        let min_column = selection_edit_ranges
 9577                            .iter()
 9578                            .map(|range| range.start.column)
 9579                            .min()
 9580                            .unwrap_or(0);
 9581                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9582                            let position = Point::new(range.start.row, min_column);
 9583                            (position..position, first_prefix.clone())
 9584                        }));
 9585                    }
 9586                } else if let Some((full_comment_prefix, comment_suffix)) =
 9587                    language.block_comment_delimiters()
 9588                {
 9589                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9590                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9591                    let prefix_range = comment_prefix_range(
 9592                        snapshot.deref(),
 9593                        start_row,
 9594                        comment_prefix,
 9595                        comment_prefix_whitespace,
 9596                        ignore_indent,
 9597                    );
 9598                    let suffix_range = comment_suffix_range(
 9599                        snapshot.deref(),
 9600                        end_row,
 9601                        comment_suffix.trim_start_matches(' '),
 9602                        comment_suffix.starts_with(' '),
 9603                    );
 9604
 9605                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9606                        edits.push((
 9607                            prefix_range.start..prefix_range.start,
 9608                            full_comment_prefix.clone(),
 9609                        ));
 9610                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9611                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9612                    } else {
 9613                        edits.push((prefix_range, empty_str.clone()));
 9614                        edits.push((suffix_range, empty_str.clone()));
 9615                    }
 9616                } else {
 9617                    continue;
 9618                }
 9619            }
 9620
 9621            drop(snapshot);
 9622            this.buffer.update(cx, |buffer, cx| {
 9623                buffer.edit(edits, None, cx);
 9624            });
 9625
 9626            // Adjust selections so that they end before any comment suffixes that
 9627            // were inserted.
 9628            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9629            let mut selections = this.selections.all::<Point>(cx);
 9630            let snapshot = this.buffer.read(cx).read(cx);
 9631            for selection in &mut selections {
 9632                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9633                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9634                        Ordering::Less => {
 9635                            suffixes_inserted.next();
 9636                            continue;
 9637                        }
 9638                        Ordering::Greater => break,
 9639                        Ordering::Equal => {
 9640                            if selection.end.column == snapshot.line_len(row) {
 9641                                if selection.is_empty() {
 9642                                    selection.start.column -= suffix_len as u32;
 9643                                }
 9644                                selection.end.column -= suffix_len as u32;
 9645                            }
 9646                            break;
 9647                        }
 9648                    }
 9649                }
 9650            }
 9651
 9652            drop(snapshot);
 9653            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9654                s.select(selections)
 9655            });
 9656
 9657            let selections = this.selections.all::<Point>(cx);
 9658            let selections_on_single_row = selections.windows(2).all(|selections| {
 9659                selections[0].start.row == selections[1].start.row
 9660                    && selections[0].end.row == selections[1].end.row
 9661                    && selections[0].start.row == selections[0].end.row
 9662            });
 9663            let selections_selecting = selections
 9664                .iter()
 9665                .any(|selection| selection.start != selection.end);
 9666            let advance_downwards = action.advance_downwards
 9667                && selections_on_single_row
 9668                && !selections_selecting
 9669                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9670
 9671            if advance_downwards {
 9672                let snapshot = this.buffer.read(cx).snapshot(cx);
 9673
 9674                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9675                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9676                        let mut point = display_point.to_point(display_snapshot);
 9677                        point.row += 1;
 9678                        point = snapshot.clip_point(point, Bias::Left);
 9679                        let display_point = point.to_display_point(display_snapshot);
 9680                        let goal = SelectionGoal::HorizontalPosition(
 9681                            display_snapshot
 9682                                .x_for_display_point(display_point, text_layout_details)
 9683                                .into(),
 9684                        );
 9685                        (display_point, goal)
 9686                    })
 9687                });
 9688            }
 9689        });
 9690    }
 9691
 9692    pub fn select_enclosing_symbol(
 9693        &mut self,
 9694        _: &SelectEnclosingSymbol,
 9695        window: &mut Window,
 9696        cx: &mut Context<Self>,
 9697    ) {
 9698        let buffer = self.buffer.read(cx).snapshot(cx);
 9699        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9700
 9701        fn update_selection(
 9702            selection: &Selection<usize>,
 9703            buffer_snap: &MultiBufferSnapshot,
 9704        ) -> Option<Selection<usize>> {
 9705            let cursor = selection.head();
 9706            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9707            for symbol in symbols.iter().rev() {
 9708                let start = symbol.range.start.to_offset(buffer_snap);
 9709                let end = symbol.range.end.to_offset(buffer_snap);
 9710                let new_range = start..end;
 9711                if start < selection.start || end > selection.end {
 9712                    return Some(Selection {
 9713                        id: selection.id,
 9714                        start: new_range.start,
 9715                        end: new_range.end,
 9716                        goal: SelectionGoal::None,
 9717                        reversed: selection.reversed,
 9718                    });
 9719                }
 9720            }
 9721            None
 9722        }
 9723
 9724        let mut selected_larger_symbol = false;
 9725        let new_selections = old_selections
 9726            .iter()
 9727            .map(|selection| match update_selection(selection, &buffer) {
 9728                Some(new_selection) => {
 9729                    if new_selection.range() != selection.range() {
 9730                        selected_larger_symbol = true;
 9731                    }
 9732                    new_selection
 9733                }
 9734                None => selection.clone(),
 9735            })
 9736            .collect::<Vec<_>>();
 9737
 9738        if selected_larger_symbol {
 9739            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9740                s.select(new_selections);
 9741            });
 9742        }
 9743    }
 9744
 9745    pub fn select_larger_syntax_node(
 9746        &mut self,
 9747        _: &SelectLargerSyntaxNode,
 9748        window: &mut Window,
 9749        cx: &mut Context<Self>,
 9750    ) {
 9751        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9752        let buffer = self.buffer.read(cx).snapshot(cx);
 9753        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9754
 9755        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9756        let mut selected_larger_node = false;
 9757        let new_selections = old_selections
 9758            .iter()
 9759            .map(|selection| {
 9760                let old_range = selection.start..selection.end;
 9761                let mut new_range = old_range.clone();
 9762                let mut new_node = None;
 9763                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9764                {
 9765                    new_node = Some(node);
 9766                    new_range = containing_range;
 9767                    if !display_map.intersects_fold(new_range.start)
 9768                        && !display_map.intersects_fold(new_range.end)
 9769                    {
 9770                        break;
 9771                    }
 9772                }
 9773
 9774                if let Some(node) = new_node {
 9775                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9776                    // nodes. Parent and grandparent are also logged because this operation will not
 9777                    // visit nodes that have the same range as their parent.
 9778                    log::info!("Node: {node:?}");
 9779                    let parent = node.parent();
 9780                    log::info!("Parent: {parent:?}");
 9781                    let grandparent = parent.and_then(|x| x.parent());
 9782                    log::info!("Grandparent: {grandparent:?}");
 9783                }
 9784
 9785                selected_larger_node |= new_range != old_range;
 9786                Selection {
 9787                    id: selection.id,
 9788                    start: new_range.start,
 9789                    end: new_range.end,
 9790                    goal: SelectionGoal::None,
 9791                    reversed: selection.reversed,
 9792                }
 9793            })
 9794            .collect::<Vec<_>>();
 9795
 9796        if selected_larger_node {
 9797            stack.push(old_selections);
 9798            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9799                s.select(new_selections);
 9800            });
 9801        }
 9802        self.select_larger_syntax_node_stack = stack;
 9803    }
 9804
 9805    pub fn select_smaller_syntax_node(
 9806        &mut self,
 9807        _: &SelectSmallerSyntaxNode,
 9808        window: &mut Window,
 9809        cx: &mut Context<Self>,
 9810    ) {
 9811        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9812        if let Some(selections) = stack.pop() {
 9813            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9814                s.select(selections.to_vec());
 9815            });
 9816        }
 9817        self.select_larger_syntax_node_stack = stack;
 9818    }
 9819
 9820    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9821        if !EditorSettings::get_global(cx).gutter.runnables {
 9822            self.clear_tasks();
 9823            return Task::ready(());
 9824        }
 9825        let project = self.project.as_ref().map(Entity::downgrade);
 9826        cx.spawn_in(window, |this, mut cx| async move {
 9827            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9828            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9829                return;
 9830            };
 9831            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9832                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9833            }) else {
 9834                return;
 9835            };
 9836
 9837            let hide_runnables = project
 9838                .update(&mut cx, |project, cx| {
 9839                    // Do not display any test indicators in non-dev server remote projects.
 9840                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9841                })
 9842                .unwrap_or(true);
 9843            if hide_runnables {
 9844                return;
 9845            }
 9846            let new_rows =
 9847                cx.background_executor()
 9848                    .spawn({
 9849                        let snapshot = display_snapshot.clone();
 9850                        async move {
 9851                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9852                        }
 9853                    })
 9854                    .await;
 9855
 9856            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9857            this.update(&mut cx, |this, _| {
 9858                this.clear_tasks();
 9859                for (key, value) in rows {
 9860                    this.insert_tasks(key, value);
 9861                }
 9862            })
 9863            .ok();
 9864        })
 9865    }
 9866    fn fetch_runnable_ranges(
 9867        snapshot: &DisplaySnapshot,
 9868        range: Range<Anchor>,
 9869    ) -> Vec<language::RunnableRange> {
 9870        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9871    }
 9872
 9873    fn runnable_rows(
 9874        project: Entity<Project>,
 9875        snapshot: DisplaySnapshot,
 9876        runnable_ranges: Vec<RunnableRange>,
 9877        mut cx: AsyncWindowContext,
 9878    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9879        runnable_ranges
 9880            .into_iter()
 9881            .filter_map(|mut runnable| {
 9882                let tasks = cx
 9883                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9884                    .ok()?;
 9885                if tasks.is_empty() {
 9886                    return None;
 9887                }
 9888
 9889                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9890
 9891                let row = snapshot
 9892                    .buffer_snapshot
 9893                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9894                    .1
 9895                    .start
 9896                    .row;
 9897
 9898                let context_range =
 9899                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9900                Some((
 9901                    (runnable.buffer_id, row),
 9902                    RunnableTasks {
 9903                        templates: tasks,
 9904                        offset: MultiBufferOffset(runnable.run_range.start),
 9905                        context_range,
 9906                        column: point.column,
 9907                        extra_variables: runnable.extra_captures,
 9908                    },
 9909                ))
 9910            })
 9911            .collect()
 9912    }
 9913
 9914    fn templates_with_tags(
 9915        project: &Entity<Project>,
 9916        runnable: &mut Runnable,
 9917        cx: &mut App,
 9918    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9919        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9920            let (worktree_id, file) = project
 9921                .buffer_for_id(runnable.buffer, cx)
 9922                .and_then(|buffer| buffer.read(cx).file())
 9923                .map(|file| (file.worktree_id(cx), file.clone()))
 9924                .unzip();
 9925
 9926            (
 9927                project.task_store().read(cx).task_inventory().cloned(),
 9928                worktree_id,
 9929                file,
 9930            )
 9931        });
 9932
 9933        let tags = mem::take(&mut runnable.tags);
 9934        let mut tags: Vec<_> = tags
 9935            .into_iter()
 9936            .flat_map(|tag| {
 9937                let tag = tag.0.clone();
 9938                inventory
 9939                    .as_ref()
 9940                    .into_iter()
 9941                    .flat_map(|inventory| {
 9942                        inventory.read(cx).list_tasks(
 9943                            file.clone(),
 9944                            Some(runnable.language.clone()),
 9945                            worktree_id,
 9946                            cx,
 9947                        )
 9948                    })
 9949                    .filter(move |(_, template)| {
 9950                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9951                    })
 9952            })
 9953            .sorted_by_key(|(kind, _)| kind.to_owned())
 9954            .collect();
 9955        if let Some((leading_tag_source, _)) = tags.first() {
 9956            // Strongest source wins; if we have worktree tag binding, prefer that to
 9957            // global and language bindings;
 9958            // if we have a global binding, prefer that to language binding.
 9959            let first_mismatch = tags
 9960                .iter()
 9961                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9962            if let Some(index) = first_mismatch {
 9963                tags.truncate(index);
 9964            }
 9965        }
 9966
 9967        tags
 9968    }
 9969
 9970    pub fn move_to_enclosing_bracket(
 9971        &mut self,
 9972        _: &MoveToEnclosingBracket,
 9973        window: &mut Window,
 9974        cx: &mut Context<Self>,
 9975    ) {
 9976        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9977            s.move_offsets_with(|snapshot, selection| {
 9978                let Some(enclosing_bracket_ranges) =
 9979                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9980                else {
 9981                    return;
 9982                };
 9983
 9984                let mut best_length = usize::MAX;
 9985                let mut best_inside = false;
 9986                let mut best_in_bracket_range = false;
 9987                let mut best_destination = None;
 9988                for (open, close) in enclosing_bracket_ranges {
 9989                    let close = close.to_inclusive();
 9990                    let length = close.end() - open.start;
 9991                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9992                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9993                        || close.contains(&selection.head());
 9994
 9995                    // If best is next to a bracket and current isn't, skip
 9996                    if !in_bracket_range && best_in_bracket_range {
 9997                        continue;
 9998                    }
 9999
10000                    // Prefer smaller lengths unless best is inside and current isn't
10001                    if length > best_length && (best_inside || !inside) {
10002                        continue;
10003                    }
10004
10005                    best_length = length;
10006                    best_inside = inside;
10007                    best_in_bracket_range = in_bracket_range;
10008                    best_destination = Some(
10009                        if close.contains(&selection.start) && close.contains(&selection.end) {
10010                            if inside {
10011                                open.end
10012                            } else {
10013                                open.start
10014                            }
10015                        } else if inside {
10016                            *close.start()
10017                        } else {
10018                            *close.end()
10019                        },
10020                    );
10021                }
10022
10023                if let Some(destination) = best_destination {
10024                    selection.collapse_to(destination, SelectionGoal::None);
10025                }
10026            })
10027        });
10028    }
10029
10030    pub fn undo_selection(
10031        &mut self,
10032        _: &UndoSelection,
10033        window: &mut Window,
10034        cx: &mut Context<Self>,
10035    ) {
10036        self.end_selection(window, cx);
10037        self.selection_history.mode = SelectionHistoryMode::Undoing;
10038        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10039            self.change_selections(None, window, cx, |s| {
10040                s.select_anchors(entry.selections.to_vec())
10041            });
10042            self.select_next_state = entry.select_next_state;
10043            self.select_prev_state = entry.select_prev_state;
10044            self.add_selections_state = entry.add_selections_state;
10045            self.request_autoscroll(Autoscroll::newest(), cx);
10046        }
10047        self.selection_history.mode = SelectionHistoryMode::Normal;
10048    }
10049
10050    pub fn redo_selection(
10051        &mut self,
10052        _: &RedoSelection,
10053        window: &mut Window,
10054        cx: &mut Context<Self>,
10055    ) {
10056        self.end_selection(window, cx);
10057        self.selection_history.mode = SelectionHistoryMode::Redoing;
10058        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10059            self.change_selections(None, window, cx, |s| {
10060                s.select_anchors(entry.selections.to_vec())
10061            });
10062            self.select_next_state = entry.select_next_state;
10063            self.select_prev_state = entry.select_prev_state;
10064            self.add_selections_state = entry.add_selections_state;
10065            self.request_autoscroll(Autoscroll::newest(), cx);
10066        }
10067        self.selection_history.mode = SelectionHistoryMode::Normal;
10068    }
10069
10070    pub fn expand_excerpts(
10071        &mut self,
10072        action: &ExpandExcerpts,
10073        _: &mut Window,
10074        cx: &mut Context<Self>,
10075    ) {
10076        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10077    }
10078
10079    pub fn expand_excerpts_down(
10080        &mut self,
10081        action: &ExpandExcerptsDown,
10082        _: &mut Window,
10083        cx: &mut Context<Self>,
10084    ) {
10085        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10086    }
10087
10088    pub fn expand_excerpts_up(
10089        &mut self,
10090        action: &ExpandExcerptsUp,
10091        _: &mut Window,
10092        cx: &mut Context<Self>,
10093    ) {
10094        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10095    }
10096
10097    pub fn expand_excerpts_for_direction(
10098        &mut self,
10099        lines: u32,
10100        direction: ExpandExcerptDirection,
10101
10102        cx: &mut Context<Self>,
10103    ) {
10104        let selections = self.selections.disjoint_anchors();
10105
10106        let lines = if lines == 0 {
10107            EditorSettings::get_global(cx).expand_excerpt_lines
10108        } else {
10109            lines
10110        };
10111
10112        self.buffer.update(cx, |buffer, cx| {
10113            let snapshot = buffer.snapshot(cx);
10114            let mut excerpt_ids = selections
10115                .iter()
10116                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10117                .collect::<Vec<_>>();
10118            excerpt_ids.sort();
10119            excerpt_ids.dedup();
10120            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10121        })
10122    }
10123
10124    pub fn expand_excerpt(
10125        &mut self,
10126        excerpt: ExcerptId,
10127        direction: ExpandExcerptDirection,
10128        cx: &mut Context<Self>,
10129    ) {
10130        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10131        self.buffer.update(cx, |buffer, cx| {
10132            buffer.expand_excerpts([excerpt], lines, direction, cx)
10133        })
10134    }
10135
10136    pub fn go_to_singleton_buffer_point(
10137        &mut self,
10138        point: Point,
10139        window: &mut Window,
10140        cx: &mut Context<Self>,
10141    ) {
10142        self.go_to_singleton_buffer_range(point..point, window, cx);
10143    }
10144
10145    pub fn go_to_singleton_buffer_range(
10146        &mut self,
10147        range: Range<Point>,
10148        window: &mut Window,
10149        cx: &mut Context<Self>,
10150    ) {
10151        let multibuffer = self.buffer().read(cx);
10152        let Some(buffer) = multibuffer.as_singleton() else {
10153            return;
10154        };
10155        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10156            return;
10157        };
10158        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10159            return;
10160        };
10161        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10162            s.select_anchor_ranges([start..end])
10163        });
10164    }
10165
10166    fn go_to_diagnostic(
10167        &mut self,
10168        _: &GoToDiagnostic,
10169        window: &mut Window,
10170        cx: &mut Context<Self>,
10171    ) {
10172        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10173    }
10174
10175    fn go_to_prev_diagnostic(
10176        &mut self,
10177        _: &GoToPrevDiagnostic,
10178        window: &mut Window,
10179        cx: &mut Context<Self>,
10180    ) {
10181        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10182    }
10183
10184    pub fn go_to_diagnostic_impl(
10185        &mut self,
10186        direction: Direction,
10187        window: &mut Window,
10188        cx: &mut Context<Self>,
10189    ) {
10190        let buffer = self.buffer.read(cx).snapshot(cx);
10191        let selection = self.selections.newest::<usize>(cx);
10192
10193        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10194        if direction == Direction::Next {
10195            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10196                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10197                    return;
10198                };
10199                self.activate_diagnostics(
10200                    buffer_id,
10201                    popover.local_diagnostic.diagnostic.group_id,
10202                    window,
10203                    cx,
10204                );
10205                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10206                    let primary_range_start = active_diagnostics.primary_range.start;
10207                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10208                        let mut new_selection = s.newest_anchor().clone();
10209                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10210                        s.select_anchors(vec![new_selection.clone()]);
10211                    });
10212                    self.refresh_inline_completion(false, true, window, cx);
10213                }
10214                return;
10215            }
10216        }
10217
10218        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10219            active_diagnostics
10220                .primary_range
10221                .to_offset(&buffer)
10222                .to_inclusive()
10223        });
10224        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10225            if active_primary_range.contains(&selection.head()) {
10226                *active_primary_range.start()
10227            } else {
10228                selection.head()
10229            }
10230        } else {
10231            selection.head()
10232        };
10233        let snapshot = self.snapshot(window, cx);
10234        loop {
10235            let mut diagnostics;
10236            if direction == Direction::Prev {
10237                diagnostics = buffer
10238                    .diagnostics_in_range::<usize>(0..search_start)
10239                    .collect::<Vec<_>>();
10240                diagnostics.reverse();
10241            } else {
10242                diagnostics = buffer
10243                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10244                    .collect::<Vec<_>>();
10245            };
10246            let group = diagnostics
10247                .into_iter()
10248                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10249                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10250                // be sorted in a stable way
10251                // skip until we are at current active diagnostic, if it exists
10252                .skip_while(|entry| {
10253                    let is_in_range = match direction {
10254                        Direction::Prev => entry.range.end > search_start,
10255                        Direction::Next => entry.range.start < search_start,
10256                    };
10257                    is_in_range
10258                        && self
10259                            .active_diagnostics
10260                            .as_ref()
10261                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10262                })
10263                .find_map(|entry| {
10264                    if entry.diagnostic.is_primary
10265                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10266                        && entry.range.start != entry.range.end
10267                        // if we match with the active diagnostic, skip it
10268                        && Some(entry.diagnostic.group_id)
10269                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10270                    {
10271                        Some((entry.range, entry.diagnostic.group_id))
10272                    } else {
10273                        None
10274                    }
10275                });
10276
10277            if let Some((primary_range, group_id)) = group {
10278                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10279                    return;
10280                };
10281                self.activate_diagnostics(buffer_id, group_id, window, cx);
10282                if self.active_diagnostics.is_some() {
10283                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10284                        s.select(vec![Selection {
10285                            id: selection.id,
10286                            start: primary_range.start,
10287                            end: primary_range.start,
10288                            reversed: false,
10289                            goal: SelectionGoal::None,
10290                        }]);
10291                    });
10292                    self.refresh_inline_completion(false, true, window, cx);
10293                }
10294                break;
10295            } else {
10296                // Cycle around to the start of the buffer, potentially moving back to the start of
10297                // the currently active diagnostic.
10298                active_primary_range.take();
10299                if direction == Direction::Prev {
10300                    if search_start == buffer.len() {
10301                        break;
10302                    } else {
10303                        search_start = buffer.len();
10304                    }
10305                } else if search_start == 0 {
10306                    break;
10307                } else {
10308                    search_start = 0;
10309                }
10310            }
10311        }
10312    }
10313
10314    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10315        let snapshot = self.snapshot(window, cx);
10316        let selection = self.selections.newest::<Point>(cx);
10317        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10318    }
10319
10320    fn go_to_hunk_after_position(
10321        &mut self,
10322        snapshot: &EditorSnapshot,
10323        position: Point,
10324        window: &mut Window,
10325        cx: &mut Context<Editor>,
10326    ) -> Option<MultiBufferDiffHunk> {
10327        let mut hunk = snapshot
10328            .buffer_snapshot
10329            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10330            .find(|hunk| hunk.row_range.start.0 > position.row);
10331        if hunk.is_none() {
10332            hunk = snapshot
10333                .buffer_snapshot
10334                .diff_hunks_in_range(Point::zero()..position)
10335                .find(|hunk| hunk.row_range.end.0 < position.row)
10336        }
10337        if let Some(hunk) = &hunk {
10338            let destination = Point::new(hunk.row_range.start.0, 0);
10339            self.unfold_ranges(&[destination..destination], false, false, cx);
10340            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10341                s.select_ranges(vec![destination..destination]);
10342            });
10343        }
10344
10345        hunk
10346    }
10347
10348    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10349        let snapshot = self.snapshot(window, cx);
10350        let selection = self.selections.newest::<Point>(cx);
10351        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10352    }
10353
10354    fn go_to_hunk_before_position(
10355        &mut self,
10356        snapshot: &EditorSnapshot,
10357        position: Point,
10358        window: &mut Window,
10359        cx: &mut Context<Editor>,
10360    ) -> Option<MultiBufferDiffHunk> {
10361        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10362        if hunk.is_none() {
10363            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10364        }
10365        if let Some(hunk) = &hunk {
10366            let destination = Point::new(hunk.row_range.start.0, 0);
10367            self.unfold_ranges(&[destination..destination], false, false, cx);
10368            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10369                s.select_ranges(vec![destination..destination]);
10370            });
10371        }
10372
10373        hunk
10374    }
10375
10376    pub fn go_to_definition(
10377        &mut self,
10378        _: &GoToDefinition,
10379        window: &mut Window,
10380        cx: &mut Context<Self>,
10381    ) -> Task<Result<Navigated>> {
10382        let definition =
10383            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10384        cx.spawn_in(window, |editor, mut cx| async move {
10385            if definition.await? == Navigated::Yes {
10386                return Ok(Navigated::Yes);
10387            }
10388            match editor.update_in(&mut cx, |editor, window, cx| {
10389                editor.find_all_references(&FindAllReferences, window, cx)
10390            })? {
10391                Some(references) => references.await,
10392                None => Ok(Navigated::No),
10393            }
10394        })
10395    }
10396
10397    pub fn go_to_declaration(
10398        &mut self,
10399        _: &GoToDeclaration,
10400        window: &mut Window,
10401        cx: &mut Context<Self>,
10402    ) -> Task<Result<Navigated>> {
10403        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10404    }
10405
10406    pub fn go_to_declaration_split(
10407        &mut self,
10408        _: &GoToDeclaration,
10409        window: &mut Window,
10410        cx: &mut Context<Self>,
10411    ) -> Task<Result<Navigated>> {
10412        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10413    }
10414
10415    pub fn go_to_implementation(
10416        &mut self,
10417        _: &GoToImplementation,
10418        window: &mut Window,
10419        cx: &mut Context<Self>,
10420    ) -> Task<Result<Navigated>> {
10421        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10422    }
10423
10424    pub fn go_to_implementation_split(
10425        &mut self,
10426        _: &GoToImplementationSplit,
10427        window: &mut Window,
10428        cx: &mut Context<Self>,
10429    ) -> Task<Result<Navigated>> {
10430        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10431    }
10432
10433    pub fn go_to_type_definition(
10434        &mut self,
10435        _: &GoToTypeDefinition,
10436        window: &mut Window,
10437        cx: &mut Context<Self>,
10438    ) -> Task<Result<Navigated>> {
10439        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10440    }
10441
10442    pub fn go_to_definition_split(
10443        &mut self,
10444        _: &GoToDefinitionSplit,
10445        window: &mut Window,
10446        cx: &mut Context<Self>,
10447    ) -> Task<Result<Navigated>> {
10448        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10449    }
10450
10451    pub fn go_to_type_definition_split(
10452        &mut self,
10453        _: &GoToTypeDefinitionSplit,
10454        window: &mut Window,
10455        cx: &mut Context<Self>,
10456    ) -> Task<Result<Navigated>> {
10457        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10458    }
10459
10460    fn go_to_definition_of_kind(
10461        &mut self,
10462        kind: GotoDefinitionKind,
10463        split: bool,
10464        window: &mut Window,
10465        cx: &mut Context<Self>,
10466    ) -> Task<Result<Navigated>> {
10467        let Some(provider) = self.semantics_provider.clone() else {
10468            return Task::ready(Ok(Navigated::No));
10469        };
10470        let head = self.selections.newest::<usize>(cx).head();
10471        let buffer = self.buffer.read(cx);
10472        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10473            text_anchor
10474        } else {
10475            return Task::ready(Ok(Navigated::No));
10476        };
10477
10478        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10479            return Task::ready(Ok(Navigated::No));
10480        };
10481
10482        cx.spawn_in(window, |editor, mut cx| async move {
10483            let definitions = definitions.await?;
10484            let navigated = editor
10485                .update_in(&mut cx, |editor, window, cx| {
10486                    editor.navigate_to_hover_links(
10487                        Some(kind),
10488                        definitions
10489                            .into_iter()
10490                            .filter(|location| {
10491                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10492                            })
10493                            .map(HoverLink::Text)
10494                            .collect::<Vec<_>>(),
10495                        split,
10496                        window,
10497                        cx,
10498                    )
10499                })?
10500                .await?;
10501            anyhow::Ok(navigated)
10502        })
10503    }
10504
10505    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10506        let selection = self.selections.newest_anchor();
10507        let head = selection.head();
10508        let tail = selection.tail();
10509
10510        let Some((buffer, start_position)) =
10511            self.buffer.read(cx).text_anchor_for_position(head, cx)
10512        else {
10513            return;
10514        };
10515
10516        let end_position = if head != tail {
10517            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10518                return;
10519            };
10520            Some(pos)
10521        } else {
10522            None
10523        };
10524
10525        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10526            let url = if let Some(end_pos) = end_position {
10527                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10528            } else {
10529                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10530            };
10531
10532            if let Some(url) = url {
10533                editor.update(&mut cx, |_, cx| {
10534                    cx.open_url(&url);
10535                })
10536            } else {
10537                Ok(())
10538            }
10539        });
10540
10541        url_finder.detach();
10542    }
10543
10544    pub fn open_selected_filename(
10545        &mut self,
10546        _: &OpenSelectedFilename,
10547        window: &mut Window,
10548        cx: &mut Context<Self>,
10549    ) {
10550        let Some(workspace) = self.workspace() else {
10551            return;
10552        };
10553
10554        let position = self.selections.newest_anchor().head();
10555
10556        let Some((buffer, buffer_position)) =
10557            self.buffer.read(cx).text_anchor_for_position(position, cx)
10558        else {
10559            return;
10560        };
10561
10562        let project = self.project.clone();
10563
10564        cx.spawn_in(window, |_, mut cx| async move {
10565            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10566
10567            if let Some((_, path)) = result {
10568                workspace
10569                    .update_in(&mut cx, |workspace, window, cx| {
10570                        workspace.open_resolved_path(path, window, cx)
10571                    })?
10572                    .await?;
10573            }
10574            anyhow::Ok(())
10575        })
10576        .detach();
10577    }
10578
10579    pub(crate) fn navigate_to_hover_links(
10580        &mut self,
10581        kind: Option<GotoDefinitionKind>,
10582        mut definitions: Vec<HoverLink>,
10583        split: bool,
10584        window: &mut Window,
10585        cx: &mut Context<Editor>,
10586    ) -> Task<Result<Navigated>> {
10587        // If there is one definition, just open it directly
10588        if definitions.len() == 1 {
10589            let definition = definitions.pop().unwrap();
10590
10591            enum TargetTaskResult {
10592                Location(Option<Location>),
10593                AlreadyNavigated,
10594            }
10595
10596            let target_task = match definition {
10597                HoverLink::Text(link) => {
10598                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10599                }
10600                HoverLink::InlayHint(lsp_location, server_id) => {
10601                    let computation =
10602                        self.compute_target_location(lsp_location, server_id, window, cx);
10603                    cx.background_executor().spawn(async move {
10604                        let location = computation.await?;
10605                        Ok(TargetTaskResult::Location(location))
10606                    })
10607                }
10608                HoverLink::Url(url) => {
10609                    cx.open_url(&url);
10610                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10611                }
10612                HoverLink::File(path) => {
10613                    if let Some(workspace) = self.workspace() {
10614                        cx.spawn_in(window, |_, mut cx| async move {
10615                            workspace
10616                                .update_in(&mut cx, |workspace, window, cx| {
10617                                    workspace.open_resolved_path(path, window, cx)
10618                                })?
10619                                .await
10620                                .map(|_| TargetTaskResult::AlreadyNavigated)
10621                        })
10622                    } else {
10623                        Task::ready(Ok(TargetTaskResult::Location(None)))
10624                    }
10625                }
10626            };
10627            cx.spawn_in(window, |editor, mut cx| async move {
10628                let target = match target_task.await.context("target resolution task")? {
10629                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10630                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10631                    TargetTaskResult::Location(Some(target)) => target,
10632                };
10633
10634                editor.update_in(&mut cx, |editor, window, cx| {
10635                    let Some(workspace) = editor.workspace() else {
10636                        return Navigated::No;
10637                    };
10638                    let pane = workspace.read(cx).active_pane().clone();
10639
10640                    let range = target.range.to_point(target.buffer.read(cx));
10641                    let range = editor.range_for_match(&range);
10642                    let range = collapse_multiline_range(range);
10643
10644                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10645                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10646                    } else {
10647                        window.defer(cx, move |window, cx| {
10648                            let target_editor: Entity<Self> =
10649                                workspace.update(cx, |workspace, cx| {
10650                                    let pane = if split {
10651                                        workspace.adjacent_pane(window, cx)
10652                                    } else {
10653                                        workspace.active_pane().clone()
10654                                    };
10655
10656                                    workspace.open_project_item(
10657                                        pane,
10658                                        target.buffer.clone(),
10659                                        true,
10660                                        true,
10661                                        window,
10662                                        cx,
10663                                    )
10664                                });
10665                            target_editor.update(cx, |target_editor, cx| {
10666                                // When selecting a definition in a different buffer, disable the nav history
10667                                // to avoid creating a history entry at the previous cursor location.
10668                                pane.update(cx, |pane, _| pane.disable_history());
10669                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10670                                pane.update(cx, |pane, _| pane.enable_history());
10671                            });
10672                        });
10673                    }
10674                    Navigated::Yes
10675                })
10676            })
10677        } else if !definitions.is_empty() {
10678            cx.spawn_in(window, |editor, mut cx| async move {
10679                let (title, location_tasks, workspace) = editor
10680                    .update_in(&mut cx, |editor, window, cx| {
10681                        let tab_kind = match kind {
10682                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10683                            _ => "Definitions",
10684                        };
10685                        let title = definitions
10686                            .iter()
10687                            .find_map(|definition| match definition {
10688                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10689                                    let buffer = origin.buffer.read(cx);
10690                                    format!(
10691                                        "{} for {}",
10692                                        tab_kind,
10693                                        buffer
10694                                            .text_for_range(origin.range.clone())
10695                                            .collect::<String>()
10696                                    )
10697                                }),
10698                                HoverLink::InlayHint(_, _) => None,
10699                                HoverLink::Url(_) => None,
10700                                HoverLink::File(_) => None,
10701                            })
10702                            .unwrap_or(tab_kind.to_string());
10703                        let location_tasks = definitions
10704                            .into_iter()
10705                            .map(|definition| match definition {
10706                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10707                                HoverLink::InlayHint(lsp_location, server_id) => editor
10708                                    .compute_target_location(lsp_location, server_id, window, cx),
10709                                HoverLink::Url(_) => Task::ready(Ok(None)),
10710                                HoverLink::File(_) => Task::ready(Ok(None)),
10711                            })
10712                            .collect::<Vec<_>>();
10713                        (title, location_tasks, editor.workspace().clone())
10714                    })
10715                    .context("location tasks preparation")?;
10716
10717                let locations = future::join_all(location_tasks)
10718                    .await
10719                    .into_iter()
10720                    .filter_map(|location| location.transpose())
10721                    .collect::<Result<_>>()
10722                    .context("location tasks")?;
10723
10724                let Some(workspace) = workspace else {
10725                    return Ok(Navigated::No);
10726                };
10727                let opened = workspace
10728                    .update_in(&mut cx, |workspace, window, cx| {
10729                        Self::open_locations_in_multibuffer(
10730                            workspace,
10731                            locations,
10732                            title,
10733                            split,
10734                            MultibufferSelectionMode::First,
10735                            window,
10736                            cx,
10737                        )
10738                    })
10739                    .ok();
10740
10741                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10742            })
10743        } else {
10744            Task::ready(Ok(Navigated::No))
10745        }
10746    }
10747
10748    fn compute_target_location(
10749        &self,
10750        lsp_location: lsp::Location,
10751        server_id: LanguageServerId,
10752        window: &mut Window,
10753        cx: &mut Context<Self>,
10754    ) -> Task<anyhow::Result<Option<Location>>> {
10755        let Some(project) = self.project.clone() else {
10756            return Task::ready(Ok(None));
10757        };
10758
10759        cx.spawn_in(window, move |editor, mut cx| async move {
10760            let location_task = editor.update(&mut cx, |_, cx| {
10761                project.update(cx, |project, cx| {
10762                    let language_server_name = project
10763                        .language_server_statuses(cx)
10764                        .find(|(id, _)| server_id == *id)
10765                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10766                    language_server_name.map(|language_server_name| {
10767                        project.open_local_buffer_via_lsp(
10768                            lsp_location.uri.clone(),
10769                            server_id,
10770                            language_server_name,
10771                            cx,
10772                        )
10773                    })
10774                })
10775            })?;
10776            let location = match location_task {
10777                Some(task) => Some({
10778                    let target_buffer_handle = task.await.context("open local buffer")?;
10779                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10780                        let target_start = target_buffer
10781                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10782                        let target_end = target_buffer
10783                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10784                        target_buffer.anchor_after(target_start)
10785                            ..target_buffer.anchor_before(target_end)
10786                    })?;
10787                    Location {
10788                        buffer: target_buffer_handle,
10789                        range,
10790                    }
10791                }),
10792                None => None,
10793            };
10794            Ok(location)
10795        })
10796    }
10797
10798    pub fn find_all_references(
10799        &mut self,
10800        _: &FindAllReferences,
10801        window: &mut Window,
10802        cx: &mut Context<Self>,
10803    ) -> Option<Task<Result<Navigated>>> {
10804        let selection = self.selections.newest::<usize>(cx);
10805        let multi_buffer = self.buffer.read(cx);
10806        let head = selection.head();
10807
10808        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10809        let head_anchor = multi_buffer_snapshot.anchor_at(
10810            head,
10811            if head < selection.tail() {
10812                Bias::Right
10813            } else {
10814                Bias::Left
10815            },
10816        );
10817
10818        match self
10819            .find_all_references_task_sources
10820            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10821        {
10822            Ok(_) => {
10823                log::info!(
10824                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10825                );
10826                return None;
10827            }
10828            Err(i) => {
10829                self.find_all_references_task_sources.insert(i, head_anchor);
10830            }
10831        }
10832
10833        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10834        let workspace = self.workspace()?;
10835        let project = workspace.read(cx).project().clone();
10836        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10837        Some(cx.spawn_in(window, |editor, mut cx| async move {
10838            let _cleanup = defer({
10839                let mut cx = cx.clone();
10840                move || {
10841                    let _ = editor.update(&mut cx, |editor, _| {
10842                        if let Ok(i) =
10843                            editor
10844                                .find_all_references_task_sources
10845                                .binary_search_by(|anchor| {
10846                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10847                                })
10848                        {
10849                            editor.find_all_references_task_sources.remove(i);
10850                        }
10851                    });
10852                }
10853            });
10854
10855            let locations = references.await?;
10856            if locations.is_empty() {
10857                return anyhow::Ok(Navigated::No);
10858            }
10859
10860            workspace.update_in(&mut cx, |workspace, window, cx| {
10861                let title = locations
10862                    .first()
10863                    .as_ref()
10864                    .map(|location| {
10865                        let buffer = location.buffer.read(cx);
10866                        format!(
10867                            "References to `{}`",
10868                            buffer
10869                                .text_for_range(location.range.clone())
10870                                .collect::<String>()
10871                        )
10872                    })
10873                    .unwrap();
10874                Self::open_locations_in_multibuffer(
10875                    workspace,
10876                    locations,
10877                    title,
10878                    false,
10879                    MultibufferSelectionMode::First,
10880                    window,
10881                    cx,
10882                );
10883                Navigated::Yes
10884            })
10885        }))
10886    }
10887
10888    /// Opens a multibuffer with the given project locations in it
10889    pub fn open_locations_in_multibuffer(
10890        workspace: &mut Workspace,
10891        mut locations: Vec<Location>,
10892        title: String,
10893        split: bool,
10894        multibuffer_selection_mode: MultibufferSelectionMode,
10895        window: &mut Window,
10896        cx: &mut Context<Workspace>,
10897    ) {
10898        // If there are multiple definitions, open them in a multibuffer
10899        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10900        let mut locations = locations.into_iter().peekable();
10901        let mut ranges = Vec::new();
10902        let capability = workspace.project().read(cx).capability();
10903
10904        let excerpt_buffer = cx.new(|cx| {
10905            let mut multibuffer = MultiBuffer::new(capability);
10906            while let Some(location) = locations.next() {
10907                let buffer = location.buffer.read(cx);
10908                let mut ranges_for_buffer = Vec::new();
10909                let range = location.range.to_offset(buffer);
10910                ranges_for_buffer.push(range.clone());
10911
10912                while let Some(next_location) = locations.peek() {
10913                    if next_location.buffer == location.buffer {
10914                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10915                        locations.next();
10916                    } else {
10917                        break;
10918                    }
10919                }
10920
10921                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10922                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10923                    location.buffer.clone(),
10924                    ranges_for_buffer,
10925                    DEFAULT_MULTIBUFFER_CONTEXT,
10926                    cx,
10927                ))
10928            }
10929
10930            multibuffer.with_title(title)
10931        });
10932
10933        let editor = cx.new(|cx| {
10934            Editor::for_multibuffer(
10935                excerpt_buffer,
10936                Some(workspace.project().clone()),
10937                true,
10938                window,
10939                cx,
10940            )
10941        });
10942        editor.update(cx, |editor, cx| {
10943            match multibuffer_selection_mode {
10944                MultibufferSelectionMode::First => {
10945                    if let Some(first_range) = ranges.first() {
10946                        editor.change_selections(None, window, cx, |selections| {
10947                            selections.clear_disjoint();
10948                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10949                        });
10950                    }
10951                    editor.highlight_background::<Self>(
10952                        &ranges,
10953                        |theme| theme.editor_highlighted_line_background,
10954                        cx,
10955                    );
10956                }
10957                MultibufferSelectionMode::All => {
10958                    editor.change_selections(None, window, cx, |selections| {
10959                        selections.clear_disjoint();
10960                        selections.select_anchor_ranges(ranges);
10961                    });
10962                }
10963            }
10964            editor.register_buffers_with_language_servers(cx);
10965        });
10966
10967        let item = Box::new(editor);
10968        let item_id = item.item_id();
10969
10970        if split {
10971            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10972        } else {
10973            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10974                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10975                    pane.close_current_preview_item(window, cx)
10976                } else {
10977                    None
10978                }
10979            });
10980            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10981        }
10982        workspace.active_pane().update(cx, |pane, cx| {
10983            pane.set_preview_item_id(Some(item_id), cx);
10984        });
10985    }
10986
10987    pub fn rename(
10988        &mut self,
10989        _: &Rename,
10990        window: &mut Window,
10991        cx: &mut Context<Self>,
10992    ) -> Option<Task<Result<()>>> {
10993        use language::ToOffset as _;
10994
10995        let provider = self.semantics_provider.clone()?;
10996        let selection = self.selections.newest_anchor().clone();
10997        let (cursor_buffer, cursor_buffer_position) = self
10998            .buffer
10999            .read(cx)
11000            .text_anchor_for_position(selection.head(), cx)?;
11001        let (tail_buffer, cursor_buffer_position_end) = self
11002            .buffer
11003            .read(cx)
11004            .text_anchor_for_position(selection.tail(), cx)?;
11005        if tail_buffer != cursor_buffer {
11006            return None;
11007        }
11008
11009        let snapshot = cursor_buffer.read(cx).snapshot();
11010        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11011        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11012        let prepare_rename = provider
11013            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11014            .unwrap_or_else(|| Task::ready(Ok(None)));
11015        drop(snapshot);
11016
11017        Some(cx.spawn_in(window, |this, mut cx| async move {
11018            let rename_range = if let Some(range) = prepare_rename.await? {
11019                Some(range)
11020            } else {
11021                this.update(&mut cx, |this, cx| {
11022                    let buffer = this.buffer.read(cx).snapshot(cx);
11023                    let mut buffer_highlights = this
11024                        .document_highlights_for_position(selection.head(), &buffer)
11025                        .filter(|highlight| {
11026                            highlight.start.excerpt_id == selection.head().excerpt_id
11027                                && highlight.end.excerpt_id == selection.head().excerpt_id
11028                        });
11029                    buffer_highlights
11030                        .next()
11031                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11032                })?
11033            };
11034            if let Some(rename_range) = rename_range {
11035                this.update_in(&mut cx, |this, window, cx| {
11036                    let snapshot = cursor_buffer.read(cx).snapshot();
11037                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11038                    let cursor_offset_in_rename_range =
11039                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11040                    let cursor_offset_in_rename_range_end =
11041                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11042
11043                    this.take_rename(false, window, cx);
11044                    let buffer = this.buffer.read(cx).read(cx);
11045                    let cursor_offset = selection.head().to_offset(&buffer);
11046                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11047                    let rename_end = rename_start + rename_buffer_range.len();
11048                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11049                    let mut old_highlight_id = None;
11050                    let old_name: Arc<str> = buffer
11051                        .chunks(rename_start..rename_end, true)
11052                        .map(|chunk| {
11053                            if old_highlight_id.is_none() {
11054                                old_highlight_id = chunk.syntax_highlight_id;
11055                            }
11056                            chunk.text
11057                        })
11058                        .collect::<String>()
11059                        .into();
11060
11061                    drop(buffer);
11062
11063                    // Position the selection in the rename editor so that it matches the current selection.
11064                    this.show_local_selections = false;
11065                    let rename_editor = cx.new(|cx| {
11066                        let mut editor = Editor::single_line(window, cx);
11067                        editor.buffer.update(cx, |buffer, cx| {
11068                            buffer.edit([(0..0, old_name.clone())], None, cx)
11069                        });
11070                        let rename_selection_range = match cursor_offset_in_rename_range
11071                            .cmp(&cursor_offset_in_rename_range_end)
11072                        {
11073                            Ordering::Equal => {
11074                                editor.select_all(&SelectAll, window, cx);
11075                                return editor;
11076                            }
11077                            Ordering::Less => {
11078                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11079                            }
11080                            Ordering::Greater => {
11081                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11082                            }
11083                        };
11084                        if rename_selection_range.end > old_name.len() {
11085                            editor.select_all(&SelectAll, window, cx);
11086                        } else {
11087                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11088                                s.select_ranges([rename_selection_range]);
11089                            });
11090                        }
11091                        editor
11092                    });
11093                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11094                        if e == &EditorEvent::Focused {
11095                            cx.emit(EditorEvent::FocusedIn)
11096                        }
11097                    })
11098                    .detach();
11099
11100                    let write_highlights =
11101                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11102                    let read_highlights =
11103                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11104                    let ranges = write_highlights
11105                        .iter()
11106                        .flat_map(|(_, ranges)| ranges.iter())
11107                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11108                        .cloned()
11109                        .collect();
11110
11111                    this.highlight_text::<Rename>(
11112                        ranges,
11113                        HighlightStyle {
11114                            fade_out: Some(0.6),
11115                            ..Default::default()
11116                        },
11117                        cx,
11118                    );
11119                    let rename_focus_handle = rename_editor.focus_handle(cx);
11120                    window.focus(&rename_focus_handle);
11121                    let block_id = this.insert_blocks(
11122                        [BlockProperties {
11123                            style: BlockStyle::Flex,
11124                            placement: BlockPlacement::Below(range.start),
11125                            height: 1,
11126                            render: Arc::new({
11127                                let rename_editor = rename_editor.clone();
11128                                move |cx: &mut BlockContext| {
11129                                    let mut text_style = cx.editor_style.text.clone();
11130                                    if let Some(highlight_style) = old_highlight_id
11131                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11132                                    {
11133                                        text_style = text_style.highlight(highlight_style);
11134                                    }
11135                                    div()
11136                                        .block_mouse_down()
11137                                        .pl(cx.anchor_x)
11138                                        .child(EditorElement::new(
11139                                            &rename_editor,
11140                                            EditorStyle {
11141                                                background: cx.theme().system().transparent,
11142                                                local_player: cx.editor_style.local_player,
11143                                                text: text_style,
11144                                                scrollbar_width: cx.editor_style.scrollbar_width,
11145                                                syntax: cx.editor_style.syntax.clone(),
11146                                                status: cx.editor_style.status.clone(),
11147                                                inlay_hints_style: HighlightStyle {
11148                                                    font_weight: Some(FontWeight::BOLD),
11149                                                    ..make_inlay_hints_style(cx.app)
11150                                                },
11151                                                inline_completion_styles: make_suggestion_styles(
11152                                                    cx.app,
11153                                                ),
11154                                                ..EditorStyle::default()
11155                                            },
11156                                        ))
11157                                        .into_any_element()
11158                                }
11159                            }),
11160                            priority: 0,
11161                        }],
11162                        Some(Autoscroll::fit()),
11163                        cx,
11164                    )[0];
11165                    this.pending_rename = Some(RenameState {
11166                        range,
11167                        old_name,
11168                        editor: rename_editor,
11169                        block_id,
11170                    });
11171                })?;
11172            }
11173
11174            Ok(())
11175        }))
11176    }
11177
11178    pub fn confirm_rename(
11179        &mut self,
11180        _: &ConfirmRename,
11181        window: &mut Window,
11182        cx: &mut Context<Self>,
11183    ) -> Option<Task<Result<()>>> {
11184        let rename = self.take_rename(false, window, cx)?;
11185        let workspace = self.workspace()?.downgrade();
11186        let (buffer, start) = self
11187            .buffer
11188            .read(cx)
11189            .text_anchor_for_position(rename.range.start, cx)?;
11190        let (end_buffer, _) = self
11191            .buffer
11192            .read(cx)
11193            .text_anchor_for_position(rename.range.end, cx)?;
11194        if buffer != end_buffer {
11195            return None;
11196        }
11197
11198        let old_name = rename.old_name;
11199        let new_name = rename.editor.read(cx).text(cx);
11200
11201        let rename = self.semantics_provider.as_ref()?.perform_rename(
11202            &buffer,
11203            start,
11204            new_name.clone(),
11205            cx,
11206        )?;
11207
11208        Some(cx.spawn_in(window, |editor, mut cx| async move {
11209            let project_transaction = rename.await?;
11210            Self::open_project_transaction(
11211                &editor,
11212                workspace,
11213                project_transaction,
11214                format!("Rename: {}{}", old_name, new_name),
11215                cx.clone(),
11216            )
11217            .await?;
11218
11219            editor.update(&mut cx, |editor, cx| {
11220                editor.refresh_document_highlights(cx);
11221            })?;
11222            Ok(())
11223        }))
11224    }
11225
11226    fn take_rename(
11227        &mut self,
11228        moving_cursor: bool,
11229        window: &mut Window,
11230        cx: &mut Context<Self>,
11231    ) -> Option<RenameState> {
11232        let rename = self.pending_rename.take()?;
11233        if rename.editor.focus_handle(cx).is_focused(window) {
11234            window.focus(&self.focus_handle);
11235        }
11236
11237        self.remove_blocks(
11238            [rename.block_id].into_iter().collect(),
11239            Some(Autoscroll::fit()),
11240            cx,
11241        );
11242        self.clear_highlights::<Rename>(cx);
11243        self.show_local_selections = true;
11244
11245        if moving_cursor {
11246            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11247                editor.selections.newest::<usize>(cx).head()
11248            });
11249
11250            // Update the selection to match the position of the selection inside
11251            // the rename editor.
11252            let snapshot = self.buffer.read(cx).read(cx);
11253            let rename_range = rename.range.to_offset(&snapshot);
11254            let cursor_in_editor = snapshot
11255                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11256                .min(rename_range.end);
11257            drop(snapshot);
11258
11259            self.change_selections(None, window, cx, |s| {
11260                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11261            });
11262        } else {
11263            self.refresh_document_highlights(cx);
11264        }
11265
11266        Some(rename)
11267    }
11268
11269    pub fn pending_rename(&self) -> Option<&RenameState> {
11270        self.pending_rename.as_ref()
11271    }
11272
11273    fn format(
11274        &mut self,
11275        _: &Format,
11276        window: &mut Window,
11277        cx: &mut Context<Self>,
11278    ) -> Option<Task<Result<()>>> {
11279        let project = match &self.project {
11280            Some(project) => project.clone(),
11281            None => return None,
11282        };
11283
11284        Some(self.perform_format(
11285            project,
11286            FormatTrigger::Manual,
11287            FormatTarget::Buffers,
11288            window,
11289            cx,
11290        ))
11291    }
11292
11293    fn format_selections(
11294        &mut self,
11295        _: &FormatSelections,
11296        window: &mut Window,
11297        cx: &mut Context<Self>,
11298    ) -> Option<Task<Result<()>>> {
11299        let project = match &self.project {
11300            Some(project) => project.clone(),
11301            None => return None,
11302        };
11303
11304        let ranges = self
11305            .selections
11306            .all_adjusted(cx)
11307            .into_iter()
11308            .map(|selection| selection.range())
11309            .collect_vec();
11310
11311        Some(self.perform_format(
11312            project,
11313            FormatTrigger::Manual,
11314            FormatTarget::Ranges(ranges),
11315            window,
11316            cx,
11317        ))
11318    }
11319
11320    fn perform_format(
11321        &mut self,
11322        project: Entity<Project>,
11323        trigger: FormatTrigger,
11324        target: FormatTarget,
11325        window: &mut Window,
11326        cx: &mut Context<Self>,
11327    ) -> Task<Result<()>> {
11328        let buffer = self.buffer.clone();
11329        let (buffers, target) = match target {
11330            FormatTarget::Buffers => {
11331                let mut buffers = buffer.read(cx).all_buffers();
11332                if trigger == FormatTrigger::Save {
11333                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11334                }
11335                (buffers, LspFormatTarget::Buffers)
11336            }
11337            FormatTarget::Ranges(selection_ranges) => {
11338                let multi_buffer = buffer.read(cx);
11339                let snapshot = multi_buffer.read(cx);
11340                let mut buffers = HashSet::default();
11341                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11342                    BTreeMap::new();
11343                for selection_range in selection_ranges {
11344                    for (buffer, buffer_range, _) in
11345                        snapshot.range_to_buffer_ranges(selection_range)
11346                    {
11347                        let buffer_id = buffer.remote_id();
11348                        let start = buffer.anchor_before(buffer_range.start);
11349                        let end = buffer.anchor_after(buffer_range.end);
11350                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11351                        buffer_id_to_ranges
11352                            .entry(buffer_id)
11353                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11354                            .or_insert_with(|| vec![start..end]);
11355                    }
11356                }
11357                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11358            }
11359        };
11360
11361        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11362        let format = project.update(cx, |project, cx| {
11363            project.format(buffers, target, true, trigger, cx)
11364        });
11365
11366        cx.spawn_in(window, |_, mut cx| async move {
11367            let transaction = futures::select_biased! {
11368                () = timeout => {
11369                    log::warn!("timed out waiting for formatting");
11370                    None
11371                }
11372                transaction = format.log_err().fuse() => transaction,
11373            };
11374
11375            buffer
11376                .update(&mut cx, |buffer, cx| {
11377                    if let Some(transaction) = transaction {
11378                        if !buffer.is_singleton() {
11379                            buffer.push_transaction(&transaction.0, cx);
11380                        }
11381                    }
11382
11383                    cx.notify();
11384                })
11385                .ok();
11386
11387            Ok(())
11388        })
11389    }
11390
11391    fn restart_language_server(
11392        &mut self,
11393        _: &RestartLanguageServer,
11394        _: &mut Window,
11395        cx: &mut Context<Self>,
11396    ) {
11397        if let Some(project) = self.project.clone() {
11398            self.buffer.update(cx, |multi_buffer, cx| {
11399                project.update(cx, |project, cx| {
11400                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11401                });
11402            })
11403        }
11404    }
11405
11406    fn cancel_language_server_work(
11407        workspace: &mut Workspace,
11408        _: &actions::CancelLanguageServerWork,
11409        _: &mut Window,
11410        cx: &mut Context<Workspace>,
11411    ) {
11412        let project = workspace.project();
11413        let buffers = workspace
11414            .active_item(cx)
11415            .and_then(|item| item.act_as::<Editor>(cx))
11416            .map_or(HashSet::default(), |editor| {
11417                editor.read(cx).buffer.read(cx).all_buffers()
11418            });
11419        project.update(cx, |project, cx| {
11420            project.cancel_language_server_work_for_buffers(buffers, cx);
11421        });
11422    }
11423
11424    fn show_character_palette(
11425        &mut self,
11426        _: &ShowCharacterPalette,
11427        window: &mut Window,
11428        _: &mut Context<Self>,
11429    ) {
11430        window.show_character_palette();
11431    }
11432
11433    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11434        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11435            let buffer = self.buffer.read(cx).snapshot(cx);
11436            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11437            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11438            let is_valid = buffer
11439                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11440                .any(|entry| {
11441                    entry.diagnostic.is_primary
11442                        && !entry.range.is_empty()
11443                        && entry.range.start == primary_range_start
11444                        && entry.diagnostic.message == active_diagnostics.primary_message
11445                });
11446
11447            if is_valid != active_diagnostics.is_valid {
11448                active_diagnostics.is_valid = is_valid;
11449                let mut new_styles = HashMap::default();
11450                for (block_id, diagnostic) in &active_diagnostics.blocks {
11451                    new_styles.insert(
11452                        *block_id,
11453                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11454                    );
11455                }
11456                self.display_map.update(cx, |display_map, _cx| {
11457                    display_map.replace_blocks(new_styles)
11458                });
11459            }
11460        }
11461    }
11462
11463    fn activate_diagnostics(
11464        &mut self,
11465        buffer_id: BufferId,
11466        group_id: usize,
11467        window: &mut Window,
11468        cx: &mut Context<Self>,
11469    ) {
11470        self.dismiss_diagnostics(cx);
11471        let snapshot = self.snapshot(window, cx);
11472        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11473            let buffer = self.buffer.read(cx).snapshot(cx);
11474
11475            let mut primary_range = None;
11476            let mut primary_message = None;
11477            let diagnostic_group = buffer
11478                .diagnostic_group(buffer_id, group_id)
11479                .filter_map(|entry| {
11480                    let start = entry.range.start;
11481                    let end = entry.range.end;
11482                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11483                        && (start.row == end.row
11484                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11485                    {
11486                        return None;
11487                    }
11488                    if entry.diagnostic.is_primary {
11489                        primary_range = Some(entry.range.clone());
11490                        primary_message = Some(entry.diagnostic.message.clone());
11491                    }
11492                    Some(entry)
11493                })
11494                .collect::<Vec<_>>();
11495            let primary_range = primary_range?;
11496            let primary_message = primary_message?;
11497
11498            let blocks = display_map
11499                .insert_blocks(
11500                    diagnostic_group.iter().map(|entry| {
11501                        let diagnostic = entry.diagnostic.clone();
11502                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11503                        BlockProperties {
11504                            style: BlockStyle::Fixed,
11505                            placement: BlockPlacement::Below(
11506                                buffer.anchor_after(entry.range.start),
11507                            ),
11508                            height: message_height,
11509                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11510                            priority: 0,
11511                        }
11512                    }),
11513                    cx,
11514                )
11515                .into_iter()
11516                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11517                .collect();
11518
11519            Some(ActiveDiagnosticGroup {
11520                primary_range: buffer.anchor_before(primary_range.start)
11521                    ..buffer.anchor_after(primary_range.end),
11522                primary_message,
11523                group_id,
11524                blocks,
11525                is_valid: true,
11526            })
11527        });
11528    }
11529
11530    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11531        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11532            self.display_map.update(cx, |display_map, cx| {
11533                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11534            });
11535            cx.notify();
11536        }
11537    }
11538
11539    pub fn set_selections_from_remote(
11540        &mut self,
11541        selections: Vec<Selection<Anchor>>,
11542        pending_selection: Option<Selection<Anchor>>,
11543        window: &mut Window,
11544        cx: &mut Context<Self>,
11545    ) {
11546        let old_cursor_position = self.selections.newest_anchor().head();
11547        self.selections.change_with(cx, |s| {
11548            s.select_anchors(selections);
11549            if let Some(pending_selection) = pending_selection {
11550                s.set_pending(pending_selection, SelectMode::Character);
11551            } else {
11552                s.clear_pending();
11553            }
11554        });
11555        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11556    }
11557
11558    fn push_to_selection_history(&mut self) {
11559        self.selection_history.push(SelectionHistoryEntry {
11560            selections: self.selections.disjoint_anchors(),
11561            select_next_state: self.select_next_state.clone(),
11562            select_prev_state: self.select_prev_state.clone(),
11563            add_selections_state: self.add_selections_state.clone(),
11564        });
11565    }
11566
11567    pub fn transact(
11568        &mut self,
11569        window: &mut Window,
11570        cx: &mut Context<Self>,
11571        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11572    ) -> Option<TransactionId> {
11573        self.start_transaction_at(Instant::now(), window, cx);
11574        update(self, window, cx);
11575        self.end_transaction_at(Instant::now(), cx)
11576    }
11577
11578    pub fn start_transaction_at(
11579        &mut self,
11580        now: Instant,
11581        window: &mut Window,
11582        cx: &mut Context<Self>,
11583    ) {
11584        self.end_selection(window, cx);
11585        if let Some(tx_id) = self
11586            .buffer
11587            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11588        {
11589            self.selection_history
11590                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11591            cx.emit(EditorEvent::TransactionBegun {
11592                transaction_id: tx_id,
11593            })
11594        }
11595    }
11596
11597    pub fn end_transaction_at(
11598        &mut self,
11599        now: Instant,
11600        cx: &mut Context<Self>,
11601    ) -> Option<TransactionId> {
11602        if let Some(transaction_id) = self
11603            .buffer
11604            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11605        {
11606            if let Some((_, end_selections)) =
11607                self.selection_history.transaction_mut(transaction_id)
11608            {
11609                *end_selections = Some(self.selections.disjoint_anchors());
11610            } else {
11611                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11612            }
11613
11614            cx.emit(EditorEvent::Edited { transaction_id });
11615            Some(transaction_id)
11616        } else {
11617            None
11618        }
11619    }
11620
11621    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11622        if self.selection_mark_mode {
11623            self.change_selections(None, window, cx, |s| {
11624                s.move_with(|_, sel| {
11625                    sel.collapse_to(sel.head(), SelectionGoal::None);
11626                });
11627            })
11628        }
11629        self.selection_mark_mode = true;
11630        cx.notify();
11631    }
11632
11633    pub fn swap_selection_ends(
11634        &mut self,
11635        _: &actions::SwapSelectionEnds,
11636        window: &mut Window,
11637        cx: &mut Context<Self>,
11638    ) {
11639        self.change_selections(None, window, cx, |s| {
11640            s.move_with(|_, sel| {
11641                if sel.start != sel.end {
11642                    sel.reversed = !sel.reversed
11643                }
11644            });
11645        });
11646        self.request_autoscroll(Autoscroll::newest(), cx);
11647        cx.notify();
11648    }
11649
11650    pub fn toggle_fold(
11651        &mut self,
11652        _: &actions::ToggleFold,
11653        window: &mut Window,
11654        cx: &mut Context<Self>,
11655    ) {
11656        if self.is_singleton(cx) {
11657            let selection = self.selections.newest::<Point>(cx);
11658
11659            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11660            let range = if selection.is_empty() {
11661                let point = selection.head().to_display_point(&display_map);
11662                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11663                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11664                    .to_point(&display_map);
11665                start..end
11666            } else {
11667                selection.range()
11668            };
11669            if display_map.folds_in_range(range).next().is_some() {
11670                self.unfold_lines(&Default::default(), window, cx)
11671            } else {
11672                self.fold(&Default::default(), window, cx)
11673            }
11674        } else {
11675            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11676            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11677                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11678                .map(|(snapshot, _, _)| snapshot.remote_id())
11679                .collect();
11680
11681            for buffer_id in buffer_ids {
11682                if self.is_buffer_folded(buffer_id, cx) {
11683                    self.unfold_buffer(buffer_id, cx);
11684                } else {
11685                    self.fold_buffer(buffer_id, cx);
11686                }
11687            }
11688        }
11689    }
11690
11691    pub fn toggle_fold_recursive(
11692        &mut self,
11693        _: &actions::ToggleFoldRecursive,
11694        window: &mut Window,
11695        cx: &mut Context<Self>,
11696    ) {
11697        let selection = self.selections.newest::<Point>(cx);
11698
11699        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11700        let range = if selection.is_empty() {
11701            let point = selection.head().to_display_point(&display_map);
11702            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11703            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11704                .to_point(&display_map);
11705            start..end
11706        } else {
11707            selection.range()
11708        };
11709        if display_map.folds_in_range(range).next().is_some() {
11710            self.unfold_recursive(&Default::default(), window, cx)
11711        } else {
11712            self.fold_recursive(&Default::default(), window, cx)
11713        }
11714    }
11715
11716    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11717        if self.is_singleton(cx) {
11718            let mut to_fold = Vec::new();
11719            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11720            let selections = self.selections.all_adjusted(cx);
11721
11722            for selection in selections {
11723                let range = selection.range().sorted();
11724                let buffer_start_row = range.start.row;
11725
11726                if range.start.row != range.end.row {
11727                    let mut found = false;
11728                    let mut row = range.start.row;
11729                    while row <= range.end.row {
11730                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11731                        {
11732                            found = true;
11733                            row = crease.range().end.row + 1;
11734                            to_fold.push(crease);
11735                        } else {
11736                            row += 1
11737                        }
11738                    }
11739                    if found {
11740                        continue;
11741                    }
11742                }
11743
11744                for row in (0..=range.start.row).rev() {
11745                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11746                        if crease.range().end.row >= buffer_start_row {
11747                            to_fold.push(crease);
11748                            if row <= range.start.row {
11749                                break;
11750                            }
11751                        }
11752                    }
11753                }
11754            }
11755
11756            self.fold_creases(to_fold, true, window, cx);
11757        } else {
11758            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11759
11760            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11761                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11762                .map(|(snapshot, _, _)| snapshot.remote_id())
11763                .collect();
11764            for buffer_id in buffer_ids {
11765                self.fold_buffer(buffer_id, cx);
11766            }
11767        }
11768    }
11769
11770    fn fold_at_level(
11771        &mut self,
11772        fold_at: &FoldAtLevel,
11773        window: &mut Window,
11774        cx: &mut Context<Self>,
11775    ) {
11776        if !self.buffer.read(cx).is_singleton() {
11777            return;
11778        }
11779
11780        let fold_at_level = fold_at.level;
11781        let snapshot = self.buffer.read(cx).snapshot(cx);
11782        let mut to_fold = Vec::new();
11783        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11784
11785        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11786            while start_row < end_row {
11787                match self
11788                    .snapshot(window, cx)
11789                    .crease_for_buffer_row(MultiBufferRow(start_row))
11790                {
11791                    Some(crease) => {
11792                        let nested_start_row = crease.range().start.row + 1;
11793                        let nested_end_row = crease.range().end.row;
11794
11795                        if current_level < fold_at_level {
11796                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11797                        } else if current_level == fold_at_level {
11798                            to_fold.push(crease);
11799                        }
11800
11801                        start_row = nested_end_row + 1;
11802                    }
11803                    None => start_row += 1,
11804                }
11805            }
11806        }
11807
11808        self.fold_creases(to_fold, true, window, cx);
11809    }
11810
11811    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11812        if self.buffer.read(cx).is_singleton() {
11813            let mut fold_ranges = Vec::new();
11814            let snapshot = self.buffer.read(cx).snapshot(cx);
11815
11816            for row in 0..snapshot.max_row().0 {
11817                if let Some(foldable_range) = self
11818                    .snapshot(window, cx)
11819                    .crease_for_buffer_row(MultiBufferRow(row))
11820                {
11821                    fold_ranges.push(foldable_range);
11822                }
11823            }
11824
11825            self.fold_creases(fold_ranges, true, window, cx);
11826        } else {
11827            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11828                editor
11829                    .update_in(&mut cx, |editor, _, cx| {
11830                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11831                            editor.fold_buffer(buffer_id, cx);
11832                        }
11833                    })
11834                    .ok();
11835            });
11836        }
11837    }
11838
11839    pub fn fold_function_bodies(
11840        &mut self,
11841        _: &actions::FoldFunctionBodies,
11842        window: &mut Window,
11843        cx: &mut Context<Self>,
11844    ) {
11845        let snapshot = self.buffer.read(cx).snapshot(cx);
11846
11847        let ranges = snapshot
11848            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11849            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11850            .collect::<Vec<_>>();
11851
11852        let creases = ranges
11853            .into_iter()
11854            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11855            .collect();
11856
11857        self.fold_creases(creases, true, window, cx);
11858    }
11859
11860    pub fn fold_recursive(
11861        &mut self,
11862        _: &actions::FoldRecursive,
11863        window: &mut Window,
11864        cx: &mut Context<Self>,
11865    ) {
11866        let mut to_fold = Vec::new();
11867        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11868        let selections = self.selections.all_adjusted(cx);
11869
11870        for selection in selections {
11871            let range = selection.range().sorted();
11872            let buffer_start_row = range.start.row;
11873
11874            if range.start.row != range.end.row {
11875                let mut found = false;
11876                for row in range.start.row..=range.end.row {
11877                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11878                        found = true;
11879                        to_fold.push(crease);
11880                    }
11881                }
11882                if found {
11883                    continue;
11884                }
11885            }
11886
11887            for row in (0..=range.start.row).rev() {
11888                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11889                    if crease.range().end.row >= buffer_start_row {
11890                        to_fold.push(crease);
11891                    } else {
11892                        break;
11893                    }
11894                }
11895            }
11896        }
11897
11898        self.fold_creases(to_fold, true, window, cx);
11899    }
11900
11901    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11902        let buffer_row = fold_at.buffer_row;
11903        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11904
11905        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11906            let autoscroll = self
11907                .selections
11908                .all::<Point>(cx)
11909                .iter()
11910                .any(|selection| crease.range().overlaps(&selection.range()));
11911
11912            self.fold_creases(vec![crease], autoscroll, window, cx);
11913        }
11914    }
11915
11916    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11917        if self.is_singleton(cx) {
11918            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11919            let buffer = &display_map.buffer_snapshot;
11920            let selections = self.selections.all::<Point>(cx);
11921            let ranges = selections
11922                .iter()
11923                .map(|s| {
11924                    let range = s.display_range(&display_map).sorted();
11925                    let mut start = range.start.to_point(&display_map);
11926                    let mut end = range.end.to_point(&display_map);
11927                    start.column = 0;
11928                    end.column = buffer.line_len(MultiBufferRow(end.row));
11929                    start..end
11930                })
11931                .collect::<Vec<_>>();
11932
11933            self.unfold_ranges(&ranges, true, true, cx);
11934        } else {
11935            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11936            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11937                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11938                .map(|(snapshot, _, _)| snapshot.remote_id())
11939                .collect();
11940            for buffer_id in buffer_ids {
11941                self.unfold_buffer(buffer_id, cx);
11942            }
11943        }
11944    }
11945
11946    pub fn unfold_recursive(
11947        &mut self,
11948        _: &UnfoldRecursive,
11949        _window: &mut Window,
11950        cx: &mut Context<Self>,
11951    ) {
11952        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11953        let selections = self.selections.all::<Point>(cx);
11954        let ranges = selections
11955            .iter()
11956            .map(|s| {
11957                let mut range = s.display_range(&display_map).sorted();
11958                *range.start.column_mut() = 0;
11959                *range.end.column_mut() = display_map.line_len(range.end.row());
11960                let start = range.start.to_point(&display_map);
11961                let end = range.end.to_point(&display_map);
11962                start..end
11963            })
11964            .collect::<Vec<_>>();
11965
11966        self.unfold_ranges(&ranges, true, true, cx);
11967    }
11968
11969    pub fn unfold_at(
11970        &mut self,
11971        unfold_at: &UnfoldAt,
11972        _window: &mut Window,
11973        cx: &mut Context<Self>,
11974    ) {
11975        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11976
11977        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11978            ..Point::new(
11979                unfold_at.buffer_row.0,
11980                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11981            );
11982
11983        let autoscroll = self
11984            .selections
11985            .all::<Point>(cx)
11986            .iter()
11987            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11988
11989        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11990    }
11991
11992    pub fn unfold_all(
11993        &mut self,
11994        _: &actions::UnfoldAll,
11995        _window: &mut Window,
11996        cx: &mut Context<Self>,
11997    ) {
11998        if self.buffer.read(cx).is_singleton() {
11999            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12000            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12001        } else {
12002            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12003                editor
12004                    .update(&mut cx, |editor, cx| {
12005                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12006                            editor.unfold_buffer(buffer_id, cx);
12007                        }
12008                    })
12009                    .ok();
12010            });
12011        }
12012    }
12013
12014    pub fn fold_selected_ranges(
12015        &mut self,
12016        _: &FoldSelectedRanges,
12017        window: &mut Window,
12018        cx: &mut Context<Self>,
12019    ) {
12020        let selections = self.selections.all::<Point>(cx);
12021        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12022        let line_mode = self.selections.line_mode;
12023        let ranges = selections
12024            .into_iter()
12025            .map(|s| {
12026                if line_mode {
12027                    let start = Point::new(s.start.row, 0);
12028                    let end = Point::new(
12029                        s.end.row,
12030                        display_map
12031                            .buffer_snapshot
12032                            .line_len(MultiBufferRow(s.end.row)),
12033                    );
12034                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12035                } else {
12036                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12037                }
12038            })
12039            .collect::<Vec<_>>();
12040        self.fold_creases(ranges, true, window, cx);
12041    }
12042
12043    pub fn fold_ranges<T: ToOffset + Clone>(
12044        &mut self,
12045        ranges: Vec<Range<T>>,
12046        auto_scroll: bool,
12047        window: &mut Window,
12048        cx: &mut Context<Self>,
12049    ) {
12050        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12051        let ranges = ranges
12052            .into_iter()
12053            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12054            .collect::<Vec<_>>();
12055        self.fold_creases(ranges, auto_scroll, window, cx);
12056    }
12057
12058    pub fn fold_creases<T: ToOffset + Clone>(
12059        &mut self,
12060        creases: Vec<Crease<T>>,
12061        auto_scroll: bool,
12062        window: &mut Window,
12063        cx: &mut Context<Self>,
12064    ) {
12065        if creases.is_empty() {
12066            return;
12067        }
12068
12069        let mut buffers_affected = HashSet::default();
12070        let multi_buffer = self.buffer().read(cx);
12071        for crease in &creases {
12072            if let Some((_, buffer, _)) =
12073                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12074            {
12075                buffers_affected.insert(buffer.read(cx).remote_id());
12076            };
12077        }
12078
12079        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12080
12081        if auto_scroll {
12082            self.request_autoscroll(Autoscroll::fit(), cx);
12083        }
12084
12085        cx.notify();
12086
12087        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12088            // Clear diagnostics block when folding a range that contains it.
12089            let snapshot = self.snapshot(window, cx);
12090            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12091                drop(snapshot);
12092                self.active_diagnostics = Some(active_diagnostics);
12093                self.dismiss_diagnostics(cx);
12094            } else {
12095                self.active_diagnostics = Some(active_diagnostics);
12096            }
12097        }
12098
12099        self.scrollbar_marker_state.dirty = true;
12100    }
12101
12102    /// Removes any folds whose ranges intersect any of the given ranges.
12103    pub fn unfold_ranges<T: ToOffset + Clone>(
12104        &mut self,
12105        ranges: &[Range<T>],
12106        inclusive: bool,
12107        auto_scroll: bool,
12108        cx: &mut Context<Self>,
12109    ) {
12110        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12111            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12112        });
12113    }
12114
12115    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12116        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12117            return;
12118        }
12119        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12120        self.display_map
12121            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12122        cx.emit(EditorEvent::BufferFoldToggled {
12123            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12124            folded: true,
12125        });
12126        cx.notify();
12127    }
12128
12129    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12130        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12131            return;
12132        }
12133        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12134        self.display_map.update(cx, |display_map, cx| {
12135            display_map.unfold_buffer(buffer_id, cx);
12136        });
12137        cx.emit(EditorEvent::BufferFoldToggled {
12138            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12139            folded: false,
12140        });
12141        cx.notify();
12142    }
12143
12144    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12145        self.display_map.read(cx).is_buffer_folded(buffer)
12146    }
12147
12148    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12149        self.display_map.read(cx).folded_buffers()
12150    }
12151
12152    /// Removes any folds with the given ranges.
12153    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12154        &mut self,
12155        ranges: &[Range<T>],
12156        type_id: TypeId,
12157        auto_scroll: bool,
12158        cx: &mut Context<Self>,
12159    ) {
12160        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12161            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12162        });
12163    }
12164
12165    fn remove_folds_with<T: ToOffset + Clone>(
12166        &mut self,
12167        ranges: &[Range<T>],
12168        auto_scroll: bool,
12169        cx: &mut Context<Self>,
12170        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12171    ) {
12172        if ranges.is_empty() {
12173            return;
12174        }
12175
12176        let mut buffers_affected = HashSet::default();
12177        let multi_buffer = self.buffer().read(cx);
12178        for range in ranges {
12179            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12180                buffers_affected.insert(buffer.read(cx).remote_id());
12181            };
12182        }
12183
12184        self.display_map.update(cx, update);
12185
12186        if auto_scroll {
12187            self.request_autoscroll(Autoscroll::fit(), cx);
12188        }
12189
12190        cx.notify();
12191        self.scrollbar_marker_state.dirty = true;
12192        self.active_indent_guides_state.dirty = true;
12193    }
12194
12195    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12196        self.display_map.read(cx).fold_placeholder.clone()
12197    }
12198
12199    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12200        self.buffer.update(cx, |buffer, cx| {
12201            buffer.set_all_diff_hunks_expanded(cx);
12202        });
12203    }
12204
12205    pub fn expand_all_diff_hunks(
12206        &mut self,
12207        _: &ExpandAllHunkDiffs,
12208        _window: &mut Window,
12209        cx: &mut Context<Self>,
12210    ) {
12211        self.buffer.update(cx, |buffer, cx| {
12212            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12213        });
12214    }
12215
12216    pub fn toggle_selected_diff_hunks(
12217        &mut self,
12218        _: &ToggleSelectedDiffHunks,
12219        _window: &mut Window,
12220        cx: &mut Context<Self>,
12221    ) {
12222        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12223        self.toggle_diff_hunks_in_ranges(ranges, cx);
12224    }
12225
12226    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12227        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12228        self.buffer
12229            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12230    }
12231
12232    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12233        self.buffer.update(cx, |buffer, cx| {
12234            let ranges = vec![Anchor::min()..Anchor::max()];
12235            if !buffer.all_diff_hunks_expanded()
12236                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12237            {
12238                buffer.collapse_diff_hunks(ranges, cx);
12239                true
12240            } else {
12241                false
12242            }
12243        })
12244    }
12245
12246    fn toggle_diff_hunks_in_ranges(
12247        &mut self,
12248        ranges: Vec<Range<Anchor>>,
12249        cx: &mut Context<'_, Editor>,
12250    ) {
12251        self.buffer.update(cx, |buffer, cx| {
12252            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12253                buffer.collapse_diff_hunks(ranges, cx)
12254            } else {
12255                buffer.expand_diff_hunks(ranges, cx)
12256            }
12257        })
12258    }
12259
12260    pub(crate) fn apply_all_diff_hunks(
12261        &mut self,
12262        _: &ApplyAllDiffHunks,
12263        window: &mut Window,
12264        cx: &mut Context<Self>,
12265    ) {
12266        let buffers = self.buffer.read(cx).all_buffers();
12267        for branch_buffer in buffers {
12268            branch_buffer.update(cx, |branch_buffer, cx| {
12269                branch_buffer.merge_into_base(Vec::new(), cx);
12270            });
12271        }
12272
12273        if let Some(project) = self.project.clone() {
12274            self.save(true, project, window, cx).detach_and_log_err(cx);
12275        }
12276    }
12277
12278    pub(crate) fn apply_selected_diff_hunks(
12279        &mut self,
12280        _: &ApplyDiffHunk,
12281        window: &mut Window,
12282        cx: &mut Context<Self>,
12283    ) {
12284        let snapshot = self.snapshot(window, cx);
12285        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12286        let mut ranges_by_buffer = HashMap::default();
12287        self.transact(window, cx, |editor, _window, cx| {
12288            for hunk in hunks {
12289                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12290                    ranges_by_buffer
12291                        .entry(buffer.clone())
12292                        .or_insert_with(Vec::new)
12293                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12294                }
12295            }
12296
12297            for (buffer, ranges) in ranges_by_buffer {
12298                buffer.update(cx, |buffer, cx| {
12299                    buffer.merge_into_base(ranges, cx);
12300                });
12301            }
12302        });
12303
12304        if let Some(project) = self.project.clone() {
12305            self.save(true, project, window, cx).detach_and_log_err(cx);
12306        }
12307    }
12308
12309    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12310        if hovered != self.gutter_hovered {
12311            self.gutter_hovered = hovered;
12312            cx.notify();
12313        }
12314    }
12315
12316    pub fn insert_blocks(
12317        &mut self,
12318        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12319        autoscroll: Option<Autoscroll>,
12320        cx: &mut Context<Self>,
12321    ) -> Vec<CustomBlockId> {
12322        let blocks = self
12323            .display_map
12324            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12325        if let Some(autoscroll) = autoscroll {
12326            self.request_autoscroll(autoscroll, cx);
12327        }
12328        cx.notify();
12329        blocks
12330    }
12331
12332    pub fn resize_blocks(
12333        &mut self,
12334        heights: HashMap<CustomBlockId, u32>,
12335        autoscroll: Option<Autoscroll>,
12336        cx: &mut Context<Self>,
12337    ) {
12338        self.display_map
12339            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12340        if let Some(autoscroll) = autoscroll {
12341            self.request_autoscroll(autoscroll, cx);
12342        }
12343        cx.notify();
12344    }
12345
12346    pub fn replace_blocks(
12347        &mut self,
12348        renderers: HashMap<CustomBlockId, RenderBlock>,
12349        autoscroll: Option<Autoscroll>,
12350        cx: &mut Context<Self>,
12351    ) {
12352        self.display_map
12353            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12354        if let Some(autoscroll) = autoscroll {
12355            self.request_autoscroll(autoscroll, cx);
12356        }
12357        cx.notify();
12358    }
12359
12360    pub fn remove_blocks(
12361        &mut self,
12362        block_ids: HashSet<CustomBlockId>,
12363        autoscroll: Option<Autoscroll>,
12364        cx: &mut Context<Self>,
12365    ) {
12366        self.display_map.update(cx, |display_map, cx| {
12367            display_map.remove_blocks(block_ids, cx)
12368        });
12369        if let Some(autoscroll) = autoscroll {
12370            self.request_autoscroll(autoscroll, cx);
12371        }
12372        cx.notify();
12373    }
12374
12375    pub fn row_for_block(
12376        &self,
12377        block_id: CustomBlockId,
12378        cx: &mut Context<Self>,
12379    ) -> Option<DisplayRow> {
12380        self.display_map
12381            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12382    }
12383
12384    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12385        self.focused_block = Some(focused_block);
12386    }
12387
12388    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12389        self.focused_block.take()
12390    }
12391
12392    pub fn insert_creases(
12393        &mut self,
12394        creases: impl IntoIterator<Item = Crease<Anchor>>,
12395        cx: &mut Context<Self>,
12396    ) -> Vec<CreaseId> {
12397        self.display_map
12398            .update(cx, |map, cx| map.insert_creases(creases, cx))
12399    }
12400
12401    pub fn remove_creases(
12402        &mut self,
12403        ids: impl IntoIterator<Item = CreaseId>,
12404        cx: &mut Context<Self>,
12405    ) {
12406        self.display_map
12407            .update(cx, |map, cx| map.remove_creases(ids, cx));
12408    }
12409
12410    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12411        self.display_map
12412            .update(cx, |map, cx| map.snapshot(cx))
12413            .longest_row()
12414    }
12415
12416    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12417        self.display_map
12418            .update(cx, |map, cx| map.snapshot(cx))
12419            .max_point()
12420    }
12421
12422    pub fn text(&self, cx: &App) -> String {
12423        self.buffer.read(cx).read(cx).text()
12424    }
12425
12426    pub fn is_empty(&self, cx: &App) -> bool {
12427        self.buffer.read(cx).read(cx).is_empty()
12428    }
12429
12430    pub fn text_option(&self, cx: &App) -> Option<String> {
12431        let text = self.text(cx);
12432        let text = text.trim();
12433
12434        if text.is_empty() {
12435            return None;
12436        }
12437
12438        Some(text.to_string())
12439    }
12440
12441    pub fn set_text(
12442        &mut self,
12443        text: impl Into<Arc<str>>,
12444        window: &mut Window,
12445        cx: &mut Context<Self>,
12446    ) {
12447        self.transact(window, cx, |this, _, cx| {
12448            this.buffer
12449                .read(cx)
12450                .as_singleton()
12451                .expect("you can only call set_text on editors for singleton buffers")
12452                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12453        });
12454    }
12455
12456    pub fn display_text(&self, cx: &mut App) -> String {
12457        self.display_map
12458            .update(cx, |map, cx| map.snapshot(cx))
12459            .text()
12460    }
12461
12462    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12463        let mut wrap_guides = smallvec::smallvec![];
12464
12465        if self.show_wrap_guides == Some(false) {
12466            return wrap_guides;
12467        }
12468
12469        let settings = self.buffer.read(cx).settings_at(0, cx);
12470        if settings.show_wrap_guides {
12471            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12472                wrap_guides.push((soft_wrap as usize, true));
12473            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12474                wrap_guides.push((soft_wrap as usize, true));
12475            }
12476            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12477        }
12478
12479        wrap_guides
12480    }
12481
12482    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12483        let settings = self.buffer.read(cx).settings_at(0, cx);
12484        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12485        match mode {
12486            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12487                SoftWrap::None
12488            }
12489            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12490            language_settings::SoftWrap::PreferredLineLength => {
12491                SoftWrap::Column(settings.preferred_line_length)
12492            }
12493            language_settings::SoftWrap::Bounded => {
12494                SoftWrap::Bounded(settings.preferred_line_length)
12495            }
12496        }
12497    }
12498
12499    pub fn set_soft_wrap_mode(
12500        &mut self,
12501        mode: language_settings::SoftWrap,
12502
12503        cx: &mut Context<Self>,
12504    ) {
12505        self.soft_wrap_mode_override = Some(mode);
12506        cx.notify();
12507    }
12508
12509    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12510        self.text_style_refinement = Some(style);
12511    }
12512
12513    /// called by the Element so we know what style we were most recently rendered with.
12514    pub(crate) fn set_style(
12515        &mut self,
12516        style: EditorStyle,
12517        window: &mut Window,
12518        cx: &mut Context<Self>,
12519    ) {
12520        let rem_size = window.rem_size();
12521        self.display_map.update(cx, |map, cx| {
12522            map.set_font(
12523                style.text.font(),
12524                style.text.font_size.to_pixels(rem_size),
12525                cx,
12526            )
12527        });
12528        self.style = Some(style);
12529    }
12530
12531    pub fn style(&self) -> Option<&EditorStyle> {
12532        self.style.as_ref()
12533    }
12534
12535    // Called by the element. This method is not designed to be called outside of the editor
12536    // element's layout code because it does not notify when rewrapping is computed synchronously.
12537    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12538        self.display_map
12539            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12540    }
12541
12542    pub fn set_soft_wrap(&mut self) {
12543        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12544    }
12545
12546    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12547        if self.soft_wrap_mode_override.is_some() {
12548            self.soft_wrap_mode_override.take();
12549        } else {
12550            let soft_wrap = match self.soft_wrap_mode(cx) {
12551                SoftWrap::GitDiff => return,
12552                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12553                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12554                    language_settings::SoftWrap::None
12555                }
12556            };
12557            self.soft_wrap_mode_override = Some(soft_wrap);
12558        }
12559        cx.notify();
12560    }
12561
12562    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12563        let Some(workspace) = self.workspace() else {
12564            return;
12565        };
12566        let fs = workspace.read(cx).app_state().fs.clone();
12567        let current_show = TabBarSettings::get_global(cx).show;
12568        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12569            setting.show = Some(!current_show);
12570        });
12571    }
12572
12573    pub fn toggle_indent_guides(
12574        &mut self,
12575        _: &ToggleIndentGuides,
12576        _: &mut Window,
12577        cx: &mut Context<Self>,
12578    ) {
12579        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12580            self.buffer
12581                .read(cx)
12582                .settings_at(0, cx)
12583                .indent_guides
12584                .enabled
12585        });
12586        self.show_indent_guides = Some(!currently_enabled);
12587        cx.notify();
12588    }
12589
12590    fn should_show_indent_guides(&self) -> Option<bool> {
12591        self.show_indent_guides
12592    }
12593
12594    pub fn toggle_line_numbers(
12595        &mut self,
12596        _: &ToggleLineNumbers,
12597        _: &mut Window,
12598        cx: &mut Context<Self>,
12599    ) {
12600        let mut editor_settings = EditorSettings::get_global(cx).clone();
12601        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12602        EditorSettings::override_global(editor_settings, cx);
12603    }
12604
12605    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12606        self.use_relative_line_numbers
12607            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12608    }
12609
12610    pub fn toggle_relative_line_numbers(
12611        &mut self,
12612        _: &ToggleRelativeLineNumbers,
12613        _: &mut Window,
12614        cx: &mut Context<Self>,
12615    ) {
12616        let is_relative = self.should_use_relative_line_numbers(cx);
12617        self.set_relative_line_number(Some(!is_relative), cx)
12618    }
12619
12620    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12621        self.use_relative_line_numbers = is_relative;
12622        cx.notify();
12623    }
12624
12625    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12626        self.show_gutter = show_gutter;
12627        cx.notify();
12628    }
12629
12630    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12631        self.show_scrollbars = show_scrollbars;
12632        cx.notify();
12633    }
12634
12635    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12636        self.show_line_numbers = Some(show_line_numbers);
12637        cx.notify();
12638    }
12639
12640    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12641        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12642        cx.notify();
12643    }
12644
12645    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12646        self.show_code_actions = Some(show_code_actions);
12647        cx.notify();
12648    }
12649
12650    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12651        self.show_runnables = Some(show_runnables);
12652        cx.notify();
12653    }
12654
12655    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12656        if self.display_map.read(cx).masked != masked {
12657            self.display_map.update(cx, |map, _| map.masked = masked);
12658        }
12659        cx.notify()
12660    }
12661
12662    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12663        self.show_wrap_guides = Some(show_wrap_guides);
12664        cx.notify();
12665    }
12666
12667    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12668        self.show_indent_guides = Some(show_indent_guides);
12669        cx.notify();
12670    }
12671
12672    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12673        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12674            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12675                if let Some(dir) = file.abs_path(cx).parent() {
12676                    return Some(dir.to_owned());
12677                }
12678            }
12679
12680            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12681                return Some(project_path.path.to_path_buf());
12682            }
12683        }
12684
12685        None
12686    }
12687
12688    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12689        self.active_excerpt(cx)?
12690            .1
12691            .read(cx)
12692            .file()
12693            .and_then(|f| f.as_local())
12694    }
12695
12696    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12697        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12698            let project_path = buffer.read(cx).project_path(cx)?;
12699            let project = self.project.as_ref()?.read(cx);
12700            project.absolute_path(&project_path, cx)
12701        })
12702    }
12703
12704    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12705        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12706            let project_path = buffer.read(cx).project_path(cx)?;
12707            let project = self.project.as_ref()?.read(cx);
12708            let entry = project.entry_for_path(&project_path, cx)?;
12709            let path = entry.path.to_path_buf();
12710            Some(path)
12711        })
12712    }
12713
12714    pub fn reveal_in_finder(
12715        &mut self,
12716        _: &RevealInFileManager,
12717        _window: &mut Window,
12718        cx: &mut Context<Self>,
12719    ) {
12720        if let Some(target) = self.target_file(cx) {
12721            cx.reveal_path(&target.abs_path(cx));
12722        }
12723    }
12724
12725    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12726        if let Some(path) = self.target_file_abs_path(cx) {
12727            if let Some(path) = path.to_str() {
12728                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12729            }
12730        }
12731    }
12732
12733    pub fn copy_relative_path(
12734        &mut self,
12735        _: &CopyRelativePath,
12736        _window: &mut Window,
12737        cx: &mut Context<Self>,
12738    ) {
12739        if let Some(path) = self.target_file_path(cx) {
12740            if let Some(path) = path.to_str() {
12741                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12742            }
12743        }
12744    }
12745
12746    pub fn toggle_git_blame(
12747        &mut self,
12748        _: &ToggleGitBlame,
12749        window: &mut Window,
12750        cx: &mut Context<Self>,
12751    ) {
12752        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12753
12754        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12755            self.start_git_blame(true, window, cx);
12756        }
12757
12758        cx.notify();
12759    }
12760
12761    pub fn toggle_git_blame_inline(
12762        &mut self,
12763        _: &ToggleGitBlameInline,
12764        window: &mut Window,
12765        cx: &mut Context<Self>,
12766    ) {
12767        self.toggle_git_blame_inline_internal(true, window, cx);
12768        cx.notify();
12769    }
12770
12771    pub fn git_blame_inline_enabled(&self) -> bool {
12772        self.git_blame_inline_enabled
12773    }
12774
12775    pub fn toggle_selection_menu(
12776        &mut self,
12777        _: &ToggleSelectionMenu,
12778        _: &mut Window,
12779        cx: &mut Context<Self>,
12780    ) {
12781        self.show_selection_menu = self
12782            .show_selection_menu
12783            .map(|show_selections_menu| !show_selections_menu)
12784            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12785
12786        cx.notify();
12787    }
12788
12789    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12790        self.show_selection_menu
12791            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12792    }
12793
12794    fn start_git_blame(
12795        &mut self,
12796        user_triggered: bool,
12797        window: &mut Window,
12798        cx: &mut Context<Self>,
12799    ) {
12800        if let Some(project) = self.project.as_ref() {
12801            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12802                return;
12803            };
12804
12805            if buffer.read(cx).file().is_none() {
12806                return;
12807            }
12808
12809            let focused = self.focus_handle(cx).contains_focused(window, cx);
12810
12811            let project = project.clone();
12812            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12813            self.blame_subscription =
12814                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12815            self.blame = Some(blame);
12816        }
12817    }
12818
12819    fn toggle_git_blame_inline_internal(
12820        &mut self,
12821        user_triggered: bool,
12822        window: &mut Window,
12823        cx: &mut Context<Self>,
12824    ) {
12825        if self.git_blame_inline_enabled {
12826            self.git_blame_inline_enabled = false;
12827            self.show_git_blame_inline = false;
12828            self.show_git_blame_inline_delay_task.take();
12829        } else {
12830            self.git_blame_inline_enabled = true;
12831            self.start_git_blame_inline(user_triggered, window, cx);
12832        }
12833
12834        cx.notify();
12835    }
12836
12837    fn start_git_blame_inline(
12838        &mut self,
12839        user_triggered: bool,
12840        window: &mut Window,
12841        cx: &mut Context<Self>,
12842    ) {
12843        self.start_git_blame(user_triggered, window, cx);
12844
12845        if ProjectSettings::get_global(cx)
12846            .git
12847            .inline_blame_delay()
12848            .is_some()
12849        {
12850            self.start_inline_blame_timer(window, cx);
12851        } else {
12852            self.show_git_blame_inline = true
12853        }
12854    }
12855
12856    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12857        self.blame.as_ref()
12858    }
12859
12860    pub fn show_git_blame_gutter(&self) -> bool {
12861        self.show_git_blame_gutter
12862    }
12863
12864    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12865        self.show_git_blame_gutter && self.has_blame_entries(cx)
12866    }
12867
12868    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12869        self.show_git_blame_inline
12870            && self.focus_handle.is_focused(window)
12871            && !self.newest_selection_head_on_empty_line(cx)
12872            && self.has_blame_entries(cx)
12873    }
12874
12875    fn has_blame_entries(&self, cx: &App) -> bool {
12876        self.blame()
12877            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12878    }
12879
12880    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12881        let cursor_anchor = self.selections.newest_anchor().head();
12882
12883        let snapshot = self.buffer.read(cx).snapshot(cx);
12884        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12885
12886        snapshot.line_len(buffer_row) == 0
12887    }
12888
12889    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12890        let buffer_and_selection = maybe!({
12891            let selection = self.selections.newest::<Point>(cx);
12892            let selection_range = selection.range();
12893
12894            let multi_buffer = self.buffer().read(cx);
12895            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12896            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12897
12898            let (buffer, range, _) = if selection.reversed {
12899                buffer_ranges.first()
12900            } else {
12901                buffer_ranges.last()
12902            }?;
12903
12904            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12905                ..text::ToPoint::to_point(&range.end, &buffer).row;
12906            Some((
12907                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12908                selection,
12909            ))
12910        });
12911
12912        let Some((buffer, selection)) = buffer_and_selection else {
12913            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12914        };
12915
12916        let Some(project) = self.project.as_ref() else {
12917            return Task::ready(Err(anyhow!("editor does not have project")));
12918        };
12919
12920        project.update(cx, |project, cx| {
12921            project.get_permalink_to_line(&buffer, selection, cx)
12922        })
12923    }
12924
12925    pub fn copy_permalink_to_line(
12926        &mut self,
12927        _: &CopyPermalinkToLine,
12928        window: &mut Window,
12929        cx: &mut Context<Self>,
12930    ) {
12931        let permalink_task = self.get_permalink_to_line(cx);
12932        let workspace = self.workspace();
12933
12934        cx.spawn_in(window, |_, mut cx| async move {
12935            match permalink_task.await {
12936                Ok(permalink) => {
12937                    cx.update(|_, cx| {
12938                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12939                    })
12940                    .ok();
12941                }
12942                Err(err) => {
12943                    let message = format!("Failed to copy permalink: {err}");
12944
12945                    Err::<(), anyhow::Error>(err).log_err();
12946
12947                    if let Some(workspace) = workspace {
12948                        workspace
12949                            .update_in(&mut cx, |workspace, _, cx| {
12950                                struct CopyPermalinkToLine;
12951
12952                                workspace.show_toast(
12953                                    Toast::new(
12954                                        NotificationId::unique::<CopyPermalinkToLine>(),
12955                                        message,
12956                                    ),
12957                                    cx,
12958                                )
12959                            })
12960                            .ok();
12961                    }
12962                }
12963            }
12964        })
12965        .detach();
12966    }
12967
12968    pub fn copy_file_location(
12969        &mut self,
12970        _: &CopyFileLocation,
12971        _: &mut Window,
12972        cx: &mut Context<Self>,
12973    ) {
12974        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12975        if let Some(file) = self.target_file(cx) {
12976            if let Some(path) = file.path().to_str() {
12977                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12978            }
12979        }
12980    }
12981
12982    pub fn open_permalink_to_line(
12983        &mut self,
12984        _: &OpenPermalinkToLine,
12985        window: &mut Window,
12986        cx: &mut Context<Self>,
12987    ) {
12988        let permalink_task = self.get_permalink_to_line(cx);
12989        let workspace = self.workspace();
12990
12991        cx.spawn_in(window, |_, mut cx| async move {
12992            match permalink_task.await {
12993                Ok(permalink) => {
12994                    cx.update(|_, cx| {
12995                        cx.open_url(permalink.as_ref());
12996                    })
12997                    .ok();
12998                }
12999                Err(err) => {
13000                    let message = format!("Failed to open permalink: {err}");
13001
13002                    Err::<(), anyhow::Error>(err).log_err();
13003
13004                    if let Some(workspace) = workspace {
13005                        workspace
13006                            .update(&mut cx, |workspace, cx| {
13007                                struct OpenPermalinkToLine;
13008
13009                                workspace.show_toast(
13010                                    Toast::new(
13011                                        NotificationId::unique::<OpenPermalinkToLine>(),
13012                                        message,
13013                                    ),
13014                                    cx,
13015                                )
13016                            })
13017                            .ok();
13018                    }
13019                }
13020            }
13021        })
13022        .detach();
13023    }
13024
13025    pub fn insert_uuid_v4(
13026        &mut self,
13027        _: &InsertUuidV4,
13028        window: &mut Window,
13029        cx: &mut Context<Self>,
13030    ) {
13031        self.insert_uuid(UuidVersion::V4, window, cx);
13032    }
13033
13034    pub fn insert_uuid_v7(
13035        &mut self,
13036        _: &InsertUuidV7,
13037        window: &mut Window,
13038        cx: &mut Context<Self>,
13039    ) {
13040        self.insert_uuid(UuidVersion::V7, window, cx);
13041    }
13042
13043    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13044        self.transact(window, cx, |this, window, cx| {
13045            let edits = this
13046                .selections
13047                .all::<Point>(cx)
13048                .into_iter()
13049                .map(|selection| {
13050                    let uuid = match version {
13051                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13052                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13053                    };
13054
13055                    (selection.range(), uuid.to_string())
13056                });
13057            this.edit(edits, cx);
13058            this.refresh_inline_completion(true, false, window, cx);
13059        });
13060    }
13061
13062    pub fn open_selections_in_multibuffer(
13063        &mut self,
13064        _: &OpenSelectionsInMultibuffer,
13065        window: &mut Window,
13066        cx: &mut Context<Self>,
13067    ) {
13068        let multibuffer = self.buffer.read(cx);
13069
13070        let Some(buffer) = multibuffer.as_singleton() else {
13071            return;
13072        };
13073
13074        let Some(workspace) = self.workspace() else {
13075            return;
13076        };
13077
13078        let locations = self
13079            .selections
13080            .disjoint_anchors()
13081            .iter()
13082            .map(|range| Location {
13083                buffer: buffer.clone(),
13084                range: range.start.text_anchor..range.end.text_anchor,
13085            })
13086            .collect::<Vec<_>>();
13087
13088        let title = multibuffer.title(cx).to_string();
13089
13090        cx.spawn_in(window, |_, mut cx| async move {
13091            workspace.update_in(&mut cx, |workspace, window, cx| {
13092                Self::open_locations_in_multibuffer(
13093                    workspace,
13094                    locations,
13095                    format!("Selections for '{title}'"),
13096                    false,
13097                    MultibufferSelectionMode::All,
13098                    window,
13099                    cx,
13100                );
13101            })
13102        })
13103        .detach();
13104    }
13105
13106    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13107    /// last highlight added will be used.
13108    ///
13109    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13110    pub fn highlight_rows<T: 'static>(
13111        &mut self,
13112        range: Range<Anchor>,
13113        color: Hsla,
13114        should_autoscroll: bool,
13115        cx: &mut Context<Self>,
13116    ) {
13117        let snapshot = self.buffer().read(cx).snapshot(cx);
13118        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13119        let ix = row_highlights.binary_search_by(|highlight| {
13120            Ordering::Equal
13121                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13122                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13123        });
13124
13125        if let Err(mut ix) = ix {
13126            let index = post_inc(&mut self.highlight_order);
13127
13128            // If this range intersects with the preceding highlight, then merge it with
13129            // the preceding highlight. Otherwise insert a new highlight.
13130            let mut merged = false;
13131            if ix > 0 {
13132                let prev_highlight = &mut row_highlights[ix - 1];
13133                if prev_highlight
13134                    .range
13135                    .end
13136                    .cmp(&range.start, &snapshot)
13137                    .is_ge()
13138                {
13139                    ix -= 1;
13140                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13141                        prev_highlight.range.end = range.end;
13142                    }
13143                    merged = true;
13144                    prev_highlight.index = index;
13145                    prev_highlight.color = color;
13146                    prev_highlight.should_autoscroll = should_autoscroll;
13147                }
13148            }
13149
13150            if !merged {
13151                row_highlights.insert(
13152                    ix,
13153                    RowHighlight {
13154                        range: range.clone(),
13155                        index,
13156                        color,
13157                        should_autoscroll,
13158                    },
13159                );
13160            }
13161
13162            // If any of the following highlights intersect with this one, merge them.
13163            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13164                let highlight = &row_highlights[ix];
13165                if next_highlight
13166                    .range
13167                    .start
13168                    .cmp(&highlight.range.end, &snapshot)
13169                    .is_le()
13170                {
13171                    if next_highlight
13172                        .range
13173                        .end
13174                        .cmp(&highlight.range.end, &snapshot)
13175                        .is_gt()
13176                    {
13177                        row_highlights[ix].range.end = next_highlight.range.end;
13178                    }
13179                    row_highlights.remove(ix + 1);
13180                } else {
13181                    break;
13182                }
13183            }
13184        }
13185    }
13186
13187    /// Remove any highlighted row ranges of the given type that intersect the
13188    /// given ranges.
13189    pub fn remove_highlighted_rows<T: 'static>(
13190        &mut self,
13191        ranges_to_remove: Vec<Range<Anchor>>,
13192        cx: &mut Context<Self>,
13193    ) {
13194        let snapshot = self.buffer().read(cx).snapshot(cx);
13195        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13196        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13197        row_highlights.retain(|highlight| {
13198            while let Some(range_to_remove) = ranges_to_remove.peek() {
13199                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13200                    Ordering::Less | Ordering::Equal => {
13201                        ranges_to_remove.next();
13202                    }
13203                    Ordering::Greater => {
13204                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13205                            Ordering::Less | Ordering::Equal => {
13206                                return false;
13207                            }
13208                            Ordering::Greater => break,
13209                        }
13210                    }
13211                }
13212            }
13213
13214            true
13215        })
13216    }
13217
13218    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13219    pub fn clear_row_highlights<T: 'static>(&mut self) {
13220        self.highlighted_rows.remove(&TypeId::of::<T>());
13221    }
13222
13223    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13224    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13225        self.highlighted_rows
13226            .get(&TypeId::of::<T>())
13227            .map_or(&[] as &[_], |vec| vec.as_slice())
13228            .iter()
13229            .map(|highlight| (highlight.range.clone(), highlight.color))
13230    }
13231
13232    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13233    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13234    /// Allows to ignore certain kinds of highlights.
13235    pub fn highlighted_display_rows(
13236        &self,
13237        window: &mut Window,
13238        cx: &mut App,
13239    ) -> BTreeMap<DisplayRow, Hsla> {
13240        let snapshot = self.snapshot(window, cx);
13241        let mut used_highlight_orders = HashMap::default();
13242        self.highlighted_rows
13243            .iter()
13244            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13245            .fold(
13246                BTreeMap::<DisplayRow, Hsla>::new(),
13247                |mut unique_rows, highlight| {
13248                    let start = highlight.range.start.to_display_point(&snapshot);
13249                    let end = highlight.range.end.to_display_point(&snapshot);
13250                    let start_row = start.row().0;
13251                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13252                        && end.column() == 0
13253                    {
13254                        end.row().0.saturating_sub(1)
13255                    } else {
13256                        end.row().0
13257                    };
13258                    for row in start_row..=end_row {
13259                        let used_index =
13260                            used_highlight_orders.entry(row).or_insert(highlight.index);
13261                        if highlight.index >= *used_index {
13262                            *used_index = highlight.index;
13263                            unique_rows.insert(DisplayRow(row), highlight.color);
13264                        }
13265                    }
13266                    unique_rows
13267                },
13268            )
13269    }
13270
13271    pub fn highlighted_display_row_for_autoscroll(
13272        &self,
13273        snapshot: &DisplaySnapshot,
13274    ) -> Option<DisplayRow> {
13275        self.highlighted_rows
13276            .values()
13277            .flat_map(|highlighted_rows| highlighted_rows.iter())
13278            .filter_map(|highlight| {
13279                if highlight.should_autoscroll {
13280                    Some(highlight.range.start.to_display_point(snapshot).row())
13281                } else {
13282                    None
13283                }
13284            })
13285            .min()
13286    }
13287
13288    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13289        self.highlight_background::<SearchWithinRange>(
13290            ranges,
13291            |colors| colors.editor_document_highlight_read_background,
13292            cx,
13293        )
13294    }
13295
13296    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13297        self.breadcrumb_header = Some(new_header);
13298    }
13299
13300    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13301        self.clear_background_highlights::<SearchWithinRange>(cx);
13302    }
13303
13304    pub fn highlight_background<T: 'static>(
13305        &mut self,
13306        ranges: &[Range<Anchor>],
13307        color_fetcher: fn(&ThemeColors) -> Hsla,
13308        cx: &mut Context<Self>,
13309    ) {
13310        self.background_highlights
13311            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13312        self.scrollbar_marker_state.dirty = true;
13313        cx.notify();
13314    }
13315
13316    pub fn clear_background_highlights<T: 'static>(
13317        &mut self,
13318        cx: &mut Context<Self>,
13319    ) -> Option<BackgroundHighlight> {
13320        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13321        if !text_highlights.1.is_empty() {
13322            self.scrollbar_marker_state.dirty = true;
13323            cx.notify();
13324        }
13325        Some(text_highlights)
13326    }
13327
13328    pub fn highlight_gutter<T: 'static>(
13329        &mut self,
13330        ranges: &[Range<Anchor>],
13331        color_fetcher: fn(&App) -> Hsla,
13332        cx: &mut Context<Self>,
13333    ) {
13334        self.gutter_highlights
13335            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13336        cx.notify();
13337    }
13338
13339    pub fn clear_gutter_highlights<T: 'static>(
13340        &mut self,
13341        cx: &mut Context<Self>,
13342    ) -> Option<GutterHighlight> {
13343        cx.notify();
13344        self.gutter_highlights.remove(&TypeId::of::<T>())
13345    }
13346
13347    #[cfg(feature = "test-support")]
13348    pub fn all_text_background_highlights(
13349        &self,
13350        window: &mut Window,
13351        cx: &mut Context<Self>,
13352    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13353        let snapshot = self.snapshot(window, cx);
13354        let buffer = &snapshot.buffer_snapshot;
13355        let start = buffer.anchor_before(0);
13356        let end = buffer.anchor_after(buffer.len());
13357        let theme = cx.theme().colors();
13358        self.background_highlights_in_range(start..end, &snapshot, theme)
13359    }
13360
13361    #[cfg(feature = "test-support")]
13362    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13363        let snapshot = self.buffer().read(cx).snapshot(cx);
13364
13365        let highlights = self
13366            .background_highlights
13367            .get(&TypeId::of::<items::BufferSearchHighlights>());
13368
13369        if let Some((_color, ranges)) = highlights {
13370            ranges
13371                .iter()
13372                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13373                .collect_vec()
13374        } else {
13375            vec![]
13376        }
13377    }
13378
13379    fn document_highlights_for_position<'a>(
13380        &'a self,
13381        position: Anchor,
13382        buffer: &'a MultiBufferSnapshot,
13383    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13384        let read_highlights = self
13385            .background_highlights
13386            .get(&TypeId::of::<DocumentHighlightRead>())
13387            .map(|h| &h.1);
13388        let write_highlights = self
13389            .background_highlights
13390            .get(&TypeId::of::<DocumentHighlightWrite>())
13391            .map(|h| &h.1);
13392        let left_position = position.bias_left(buffer);
13393        let right_position = position.bias_right(buffer);
13394        read_highlights
13395            .into_iter()
13396            .chain(write_highlights)
13397            .flat_map(move |ranges| {
13398                let start_ix = match ranges.binary_search_by(|probe| {
13399                    let cmp = probe.end.cmp(&left_position, buffer);
13400                    if cmp.is_ge() {
13401                        Ordering::Greater
13402                    } else {
13403                        Ordering::Less
13404                    }
13405                }) {
13406                    Ok(i) | Err(i) => i,
13407                };
13408
13409                ranges[start_ix..]
13410                    .iter()
13411                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13412            })
13413    }
13414
13415    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13416        self.background_highlights
13417            .get(&TypeId::of::<T>())
13418            .map_or(false, |(_, highlights)| !highlights.is_empty())
13419    }
13420
13421    pub fn background_highlights_in_range(
13422        &self,
13423        search_range: Range<Anchor>,
13424        display_snapshot: &DisplaySnapshot,
13425        theme: &ThemeColors,
13426    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13427        let mut results = Vec::new();
13428        for (color_fetcher, ranges) in self.background_highlights.values() {
13429            let color = color_fetcher(theme);
13430            let start_ix = match ranges.binary_search_by(|probe| {
13431                let cmp = probe
13432                    .end
13433                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13434                if cmp.is_gt() {
13435                    Ordering::Greater
13436                } else {
13437                    Ordering::Less
13438                }
13439            }) {
13440                Ok(i) | Err(i) => i,
13441            };
13442            for range in &ranges[start_ix..] {
13443                if range
13444                    .start
13445                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13446                    .is_ge()
13447                {
13448                    break;
13449                }
13450
13451                let start = range.start.to_display_point(display_snapshot);
13452                let end = range.end.to_display_point(display_snapshot);
13453                results.push((start..end, color))
13454            }
13455        }
13456        results
13457    }
13458
13459    pub fn background_highlight_row_ranges<T: 'static>(
13460        &self,
13461        search_range: Range<Anchor>,
13462        display_snapshot: &DisplaySnapshot,
13463        count: usize,
13464    ) -> Vec<RangeInclusive<DisplayPoint>> {
13465        let mut results = Vec::new();
13466        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13467            return vec![];
13468        };
13469
13470        let start_ix = match ranges.binary_search_by(|probe| {
13471            let cmp = probe
13472                .end
13473                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13474            if cmp.is_gt() {
13475                Ordering::Greater
13476            } else {
13477                Ordering::Less
13478            }
13479        }) {
13480            Ok(i) | Err(i) => i,
13481        };
13482        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13483            if let (Some(start_display), Some(end_display)) = (start, end) {
13484                results.push(
13485                    start_display.to_display_point(display_snapshot)
13486                        ..=end_display.to_display_point(display_snapshot),
13487                );
13488            }
13489        };
13490        let mut start_row: Option<Point> = None;
13491        let mut end_row: Option<Point> = None;
13492        if ranges.len() > count {
13493            return Vec::new();
13494        }
13495        for range in &ranges[start_ix..] {
13496            if range
13497                .start
13498                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13499                .is_ge()
13500            {
13501                break;
13502            }
13503            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13504            if let Some(current_row) = &end_row {
13505                if end.row == current_row.row {
13506                    continue;
13507                }
13508            }
13509            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13510            if start_row.is_none() {
13511                assert_eq!(end_row, None);
13512                start_row = Some(start);
13513                end_row = Some(end);
13514                continue;
13515            }
13516            if let Some(current_end) = end_row.as_mut() {
13517                if start.row > current_end.row + 1 {
13518                    push_region(start_row, end_row);
13519                    start_row = Some(start);
13520                    end_row = Some(end);
13521                } else {
13522                    // Merge two hunks.
13523                    *current_end = end;
13524                }
13525            } else {
13526                unreachable!();
13527            }
13528        }
13529        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13530        push_region(start_row, end_row);
13531        results
13532    }
13533
13534    pub fn gutter_highlights_in_range(
13535        &self,
13536        search_range: Range<Anchor>,
13537        display_snapshot: &DisplaySnapshot,
13538        cx: &App,
13539    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13540        let mut results = Vec::new();
13541        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13542            let color = color_fetcher(cx);
13543            let start_ix = match ranges.binary_search_by(|probe| {
13544                let cmp = probe
13545                    .end
13546                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13547                if cmp.is_gt() {
13548                    Ordering::Greater
13549                } else {
13550                    Ordering::Less
13551                }
13552            }) {
13553                Ok(i) | Err(i) => i,
13554            };
13555            for range in &ranges[start_ix..] {
13556                if range
13557                    .start
13558                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13559                    .is_ge()
13560                {
13561                    break;
13562                }
13563
13564                let start = range.start.to_display_point(display_snapshot);
13565                let end = range.end.to_display_point(display_snapshot);
13566                results.push((start..end, color))
13567            }
13568        }
13569        results
13570    }
13571
13572    /// Get the text ranges corresponding to the redaction query
13573    pub fn redacted_ranges(
13574        &self,
13575        search_range: Range<Anchor>,
13576        display_snapshot: &DisplaySnapshot,
13577        cx: &App,
13578    ) -> Vec<Range<DisplayPoint>> {
13579        display_snapshot
13580            .buffer_snapshot
13581            .redacted_ranges(search_range, |file| {
13582                if let Some(file) = file {
13583                    file.is_private()
13584                        && EditorSettings::get(
13585                            Some(SettingsLocation {
13586                                worktree_id: file.worktree_id(cx),
13587                                path: file.path().as_ref(),
13588                            }),
13589                            cx,
13590                        )
13591                        .redact_private_values
13592                } else {
13593                    false
13594                }
13595            })
13596            .map(|range| {
13597                range.start.to_display_point(display_snapshot)
13598                    ..range.end.to_display_point(display_snapshot)
13599            })
13600            .collect()
13601    }
13602
13603    pub fn highlight_text<T: 'static>(
13604        &mut self,
13605        ranges: Vec<Range<Anchor>>,
13606        style: HighlightStyle,
13607        cx: &mut Context<Self>,
13608    ) {
13609        self.display_map.update(cx, |map, _| {
13610            map.highlight_text(TypeId::of::<T>(), ranges, style)
13611        });
13612        cx.notify();
13613    }
13614
13615    pub(crate) fn highlight_inlays<T: 'static>(
13616        &mut self,
13617        highlights: Vec<InlayHighlight>,
13618        style: HighlightStyle,
13619        cx: &mut Context<Self>,
13620    ) {
13621        self.display_map.update(cx, |map, _| {
13622            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13623        });
13624        cx.notify();
13625    }
13626
13627    pub fn text_highlights<'a, T: 'static>(
13628        &'a self,
13629        cx: &'a App,
13630    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13631        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13632    }
13633
13634    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13635        let cleared = self
13636            .display_map
13637            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13638        if cleared {
13639            cx.notify();
13640        }
13641    }
13642
13643    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13644        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13645            && self.focus_handle.is_focused(window)
13646    }
13647
13648    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13649        self.show_cursor_when_unfocused = is_enabled;
13650        cx.notify();
13651    }
13652
13653    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13654        self.project
13655            .as_ref()
13656            .map(|project| project.read(cx).lsp_store())
13657    }
13658
13659    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13660        cx.notify();
13661    }
13662
13663    fn on_buffer_event(
13664        &mut self,
13665        multibuffer: &Entity<MultiBuffer>,
13666        event: &multi_buffer::Event,
13667        window: &mut Window,
13668        cx: &mut Context<Self>,
13669    ) {
13670        match event {
13671            multi_buffer::Event::Edited {
13672                singleton_buffer_edited,
13673                edited_buffer: buffer_edited,
13674            } => {
13675                self.scrollbar_marker_state.dirty = true;
13676                self.active_indent_guides_state.dirty = true;
13677                self.refresh_active_diagnostics(cx);
13678                self.refresh_code_actions(window, cx);
13679                if self.has_active_inline_completion() {
13680                    self.update_visible_inline_completion(window, cx);
13681                }
13682                if let Some(buffer) = buffer_edited {
13683                    let buffer_id = buffer.read(cx).remote_id();
13684                    if !self.registered_buffers.contains_key(&buffer_id) {
13685                        if let Some(lsp_store) = self.lsp_store(cx) {
13686                            lsp_store.update(cx, |lsp_store, cx| {
13687                                self.registered_buffers.insert(
13688                                    buffer_id,
13689                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13690                                );
13691                            })
13692                        }
13693                    }
13694                }
13695                cx.emit(EditorEvent::BufferEdited);
13696                cx.emit(SearchEvent::MatchesInvalidated);
13697                if *singleton_buffer_edited {
13698                    if let Some(project) = &self.project {
13699                        let project = project.read(cx);
13700                        #[allow(clippy::mutable_key_type)]
13701                        let languages_affected = multibuffer
13702                            .read(cx)
13703                            .all_buffers()
13704                            .into_iter()
13705                            .filter_map(|buffer| {
13706                                let buffer = buffer.read(cx);
13707                                let language = buffer.language()?;
13708                                if project.is_local()
13709                                    && project
13710                                        .language_servers_for_local_buffer(buffer, cx)
13711                                        .count()
13712                                        == 0
13713                                {
13714                                    None
13715                                } else {
13716                                    Some(language)
13717                                }
13718                            })
13719                            .cloned()
13720                            .collect::<HashSet<_>>();
13721                        if !languages_affected.is_empty() {
13722                            self.refresh_inlay_hints(
13723                                InlayHintRefreshReason::BufferEdited(languages_affected),
13724                                cx,
13725                            );
13726                        }
13727                    }
13728                }
13729
13730                let Some(project) = &self.project else { return };
13731                let (telemetry, is_via_ssh) = {
13732                    let project = project.read(cx);
13733                    let telemetry = project.client().telemetry().clone();
13734                    let is_via_ssh = project.is_via_ssh();
13735                    (telemetry, is_via_ssh)
13736                };
13737                refresh_linked_ranges(self, window, cx);
13738                telemetry.log_edit_event("editor", is_via_ssh);
13739            }
13740            multi_buffer::Event::ExcerptsAdded {
13741                buffer,
13742                predecessor,
13743                excerpts,
13744            } => {
13745                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13746                let buffer_id = buffer.read(cx).remote_id();
13747                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13748                    if let Some(project) = &self.project {
13749                        get_uncommitted_changes_for_buffer(
13750                            project,
13751                            [buffer.clone()],
13752                            self.buffer.clone(),
13753                            cx,
13754                        );
13755                    }
13756                }
13757                cx.emit(EditorEvent::ExcerptsAdded {
13758                    buffer: buffer.clone(),
13759                    predecessor: *predecessor,
13760                    excerpts: excerpts.clone(),
13761                });
13762                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13763            }
13764            multi_buffer::Event::ExcerptsRemoved { ids } => {
13765                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13766                let buffer = self.buffer.read(cx);
13767                self.registered_buffers
13768                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13769                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13770            }
13771            multi_buffer::Event::ExcerptsEdited { ids } => {
13772                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13773            }
13774            multi_buffer::Event::ExcerptsExpanded { ids } => {
13775                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13776                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13777            }
13778            multi_buffer::Event::Reparsed(buffer_id) => {
13779                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13780
13781                cx.emit(EditorEvent::Reparsed(*buffer_id));
13782            }
13783            multi_buffer::Event::DiffHunksToggled => {
13784                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13785            }
13786            multi_buffer::Event::LanguageChanged(buffer_id) => {
13787                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13788                cx.emit(EditorEvent::Reparsed(*buffer_id));
13789                cx.notify();
13790            }
13791            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13792            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13793            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13794                cx.emit(EditorEvent::TitleChanged)
13795            }
13796            // multi_buffer::Event::DiffBaseChanged => {
13797            //     self.scrollbar_marker_state.dirty = true;
13798            //     cx.emit(EditorEvent::DiffBaseChanged);
13799            //     cx.notify();
13800            // }
13801            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13802            multi_buffer::Event::DiagnosticsUpdated => {
13803                self.refresh_active_diagnostics(cx);
13804                self.scrollbar_marker_state.dirty = true;
13805                cx.notify();
13806            }
13807            _ => {}
13808        };
13809    }
13810
13811    fn on_display_map_changed(
13812        &mut self,
13813        _: Entity<DisplayMap>,
13814        _: &mut Window,
13815        cx: &mut Context<Self>,
13816    ) {
13817        cx.notify();
13818    }
13819
13820    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13821        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13822        self.refresh_inline_completion(true, false, window, cx);
13823        self.refresh_inlay_hints(
13824            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13825                self.selections.newest_anchor().head(),
13826                &self.buffer.read(cx).snapshot(cx),
13827                cx,
13828            )),
13829            cx,
13830        );
13831
13832        let old_cursor_shape = self.cursor_shape;
13833
13834        {
13835            let editor_settings = EditorSettings::get_global(cx);
13836            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13837            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13838            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13839        }
13840
13841        if old_cursor_shape != self.cursor_shape {
13842            cx.emit(EditorEvent::CursorShapeChanged);
13843        }
13844
13845        let project_settings = ProjectSettings::get_global(cx);
13846        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13847
13848        if self.mode == EditorMode::Full {
13849            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13850            if self.git_blame_inline_enabled != inline_blame_enabled {
13851                self.toggle_git_blame_inline_internal(false, window, cx);
13852            }
13853        }
13854
13855        cx.notify();
13856    }
13857
13858    pub fn set_searchable(&mut self, searchable: bool) {
13859        self.searchable = searchable;
13860    }
13861
13862    pub fn searchable(&self) -> bool {
13863        self.searchable
13864    }
13865
13866    fn open_proposed_changes_editor(
13867        &mut self,
13868        _: &OpenProposedChangesEditor,
13869        window: &mut Window,
13870        cx: &mut Context<Self>,
13871    ) {
13872        let Some(workspace) = self.workspace() else {
13873            cx.propagate();
13874            return;
13875        };
13876
13877        let selections = self.selections.all::<usize>(cx);
13878        let multi_buffer = self.buffer.read(cx);
13879        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13880        let mut new_selections_by_buffer = HashMap::default();
13881        for selection in selections {
13882            for (buffer, range, _) in
13883                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13884            {
13885                let mut range = range.to_point(buffer);
13886                range.start.column = 0;
13887                range.end.column = buffer.line_len(range.end.row);
13888                new_selections_by_buffer
13889                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13890                    .or_insert(Vec::new())
13891                    .push(range)
13892            }
13893        }
13894
13895        let proposed_changes_buffers = new_selections_by_buffer
13896            .into_iter()
13897            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13898            .collect::<Vec<_>>();
13899        let proposed_changes_editor = cx.new(|cx| {
13900            ProposedChangesEditor::new(
13901                "Proposed changes",
13902                proposed_changes_buffers,
13903                self.project.clone(),
13904                window,
13905                cx,
13906            )
13907        });
13908
13909        window.defer(cx, move |window, cx| {
13910            workspace.update(cx, |workspace, cx| {
13911                workspace.active_pane().update(cx, |pane, cx| {
13912                    pane.add_item(
13913                        Box::new(proposed_changes_editor),
13914                        true,
13915                        true,
13916                        None,
13917                        window,
13918                        cx,
13919                    );
13920                });
13921            });
13922        });
13923    }
13924
13925    pub fn open_excerpts_in_split(
13926        &mut self,
13927        _: &OpenExcerptsSplit,
13928        window: &mut Window,
13929        cx: &mut Context<Self>,
13930    ) {
13931        self.open_excerpts_common(None, true, window, cx)
13932    }
13933
13934    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13935        self.open_excerpts_common(None, false, window, cx)
13936    }
13937
13938    fn open_excerpts_common(
13939        &mut self,
13940        jump_data: Option<JumpData>,
13941        split: bool,
13942        window: &mut Window,
13943        cx: &mut Context<Self>,
13944    ) {
13945        let Some(workspace) = self.workspace() else {
13946            cx.propagate();
13947            return;
13948        };
13949
13950        if self.buffer.read(cx).is_singleton() {
13951            cx.propagate();
13952            return;
13953        }
13954
13955        let mut new_selections_by_buffer = HashMap::default();
13956        match &jump_data {
13957            Some(JumpData::MultiBufferPoint {
13958                excerpt_id,
13959                position,
13960                anchor,
13961                line_offset_from_top,
13962            }) => {
13963                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13964                if let Some(buffer) = multi_buffer_snapshot
13965                    .buffer_id_for_excerpt(*excerpt_id)
13966                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13967                {
13968                    let buffer_snapshot = buffer.read(cx).snapshot();
13969                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13970                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13971                    } else {
13972                        buffer_snapshot.clip_point(*position, Bias::Left)
13973                    };
13974                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13975                    new_selections_by_buffer.insert(
13976                        buffer,
13977                        (
13978                            vec![jump_to_offset..jump_to_offset],
13979                            Some(*line_offset_from_top),
13980                        ),
13981                    );
13982                }
13983            }
13984            Some(JumpData::MultiBufferRow {
13985                row,
13986                line_offset_from_top,
13987            }) => {
13988                let point = MultiBufferPoint::new(row.0, 0);
13989                if let Some((buffer, buffer_point, _)) =
13990                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13991                {
13992                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13993                    new_selections_by_buffer
13994                        .entry(buffer)
13995                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13996                        .0
13997                        .push(buffer_offset..buffer_offset)
13998                }
13999            }
14000            None => {
14001                let selections = self.selections.all::<usize>(cx);
14002                let multi_buffer = self.buffer.read(cx);
14003                for selection in selections {
14004                    for (buffer, mut range, _) in multi_buffer
14005                        .snapshot(cx)
14006                        .range_to_buffer_ranges(selection.range())
14007                    {
14008                        // When editing branch buffers, jump to the corresponding location
14009                        // in their base buffer.
14010                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14011                        let buffer = buffer_handle.read(cx);
14012                        if let Some(base_buffer) = buffer.base_buffer() {
14013                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14014                            buffer_handle = base_buffer;
14015                        }
14016
14017                        if selection.reversed {
14018                            mem::swap(&mut range.start, &mut range.end);
14019                        }
14020                        new_selections_by_buffer
14021                            .entry(buffer_handle)
14022                            .or_insert((Vec::new(), None))
14023                            .0
14024                            .push(range)
14025                    }
14026                }
14027            }
14028        }
14029
14030        if new_selections_by_buffer.is_empty() {
14031            return;
14032        }
14033
14034        // We defer the pane interaction because we ourselves are a workspace item
14035        // and activating a new item causes the pane to call a method on us reentrantly,
14036        // which panics if we're on the stack.
14037        window.defer(cx, move |window, cx| {
14038            workspace.update(cx, |workspace, cx| {
14039                let pane = if split {
14040                    workspace.adjacent_pane(window, cx)
14041                } else {
14042                    workspace.active_pane().clone()
14043                };
14044
14045                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14046                    let editor = buffer
14047                        .read(cx)
14048                        .file()
14049                        .is_none()
14050                        .then(|| {
14051                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14052                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14053                            // Instead, we try to activate the existing editor in the pane first.
14054                            let (editor, pane_item_index) =
14055                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14056                                    let editor = item.downcast::<Editor>()?;
14057                                    let singleton_buffer =
14058                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14059                                    if singleton_buffer == buffer {
14060                                        Some((editor, i))
14061                                    } else {
14062                                        None
14063                                    }
14064                                })?;
14065                            pane.update(cx, |pane, cx| {
14066                                pane.activate_item(pane_item_index, true, true, window, cx)
14067                            });
14068                            Some(editor)
14069                        })
14070                        .flatten()
14071                        .unwrap_or_else(|| {
14072                            workspace.open_project_item::<Self>(
14073                                pane.clone(),
14074                                buffer,
14075                                true,
14076                                true,
14077                                window,
14078                                cx,
14079                            )
14080                        });
14081
14082                    editor.update(cx, |editor, cx| {
14083                        let autoscroll = match scroll_offset {
14084                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14085                            None => Autoscroll::newest(),
14086                        };
14087                        let nav_history = editor.nav_history.take();
14088                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14089                            s.select_ranges(ranges);
14090                        });
14091                        editor.nav_history = nav_history;
14092                    });
14093                }
14094            })
14095        });
14096    }
14097
14098    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14099        let snapshot = self.buffer.read(cx).read(cx);
14100        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14101        Some(
14102            ranges
14103                .iter()
14104                .map(move |range| {
14105                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14106                })
14107                .collect(),
14108        )
14109    }
14110
14111    fn selection_replacement_ranges(
14112        &self,
14113        range: Range<OffsetUtf16>,
14114        cx: &mut App,
14115    ) -> Vec<Range<OffsetUtf16>> {
14116        let selections = self.selections.all::<OffsetUtf16>(cx);
14117        let newest_selection = selections
14118            .iter()
14119            .max_by_key(|selection| selection.id)
14120            .unwrap();
14121        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14122        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14123        let snapshot = self.buffer.read(cx).read(cx);
14124        selections
14125            .into_iter()
14126            .map(|mut selection| {
14127                selection.start.0 =
14128                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14129                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14130                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14131                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14132            })
14133            .collect()
14134    }
14135
14136    fn report_editor_event(
14137        &self,
14138        event_type: &'static str,
14139        file_extension: Option<String>,
14140        cx: &App,
14141    ) {
14142        if cfg!(any(test, feature = "test-support")) {
14143            return;
14144        }
14145
14146        let Some(project) = &self.project else { return };
14147
14148        // If None, we are in a file without an extension
14149        let file = self
14150            .buffer
14151            .read(cx)
14152            .as_singleton()
14153            .and_then(|b| b.read(cx).file());
14154        let file_extension = file_extension.or(file
14155            .as_ref()
14156            .and_then(|file| Path::new(file.file_name(cx)).extension())
14157            .and_then(|e| e.to_str())
14158            .map(|a| a.to_string()));
14159
14160        let vim_mode = cx
14161            .global::<SettingsStore>()
14162            .raw_user_settings()
14163            .get("vim_mode")
14164            == Some(&serde_json::Value::Bool(true));
14165
14166        let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14167        let copilot_enabled = edit_predictions_provider
14168            == language::language_settings::InlineCompletionProvider::Copilot;
14169        let copilot_enabled_for_language = self
14170            .buffer
14171            .read(cx)
14172            .settings_at(0, cx)
14173            .show_inline_completions;
14174
14175        let project = project.read(cx);
14176        telemetry::event!(
14177            event_type,
14178            file_extension,
14179            vim_mode,
14180            copilot_enabled,
14181            copilot_enabled_for_language,
14182            edit_predictions_provider,
14183            is_via_ssh = project.is_via_ssh(),
14184        );
14185    }
14186
14187    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14188    /// with each line being an array of {text, highlight} objects.
14189    fn copy_highlight_json(
14190        &mut self,
14191        _: &CopyHighlightJson,
14192        window: &mut Window,
14193        cx: &mut Context<Self>,
14194    ) {
14195        #[derive(Serialize)]
14196        struct Chunk<'a> {
14197            text: String,
14198            highlight: Option<&'a str>,
14199        }
14200
14201        let snapshot = self.buffer.read(cx).snapshot(cx);
14202        let range = self
14203            .selected_text_range(false, window, cx)
14204            .and_then(|selection| {
14205                if selection.range.is_empty() {
14206                    None
14207                } else {
14208                    Some(selection.range)
14209                }
14210            })
14211            .unwrap_or_else(|| 0..snapshot.len());
14212
14213        let chunks = snapshot.chunks(range, true);
14214        let mut lines = Vec::new();
14215        let mut line: VecDeque<Chunk> = VecDeque::new();
14216
14217        let Some(style) = self.style.as_ref() else {
14218            return;
14219        };
14220
14221        for chunk in chunks {
14222            let highlight = chunk
14223                .syntax_highlight_id
14224                .and_then(|id| id.name(&style.syntax));
14225            let mut chunk_lines = chunk.text.split('\n').peekable();
14226            while let Some(text) = chunk_lines.next() {
14227                let mut merged_with_last_token = false;
14228                if let Some(last_token) = line.back_mut() {
14229                    if last_token.highlight == highlight {
14230                        last_token.text.push_str(text);
14231                        merged_with_last_token = true;
14232                    }
14233                }
14234
14235                if !merged_with_last_token {
14236                    line.push_back(Chunk {
14237                        text: text.into(),
14238                        highlight,
14239                    });
14240                }
14241
14242                if chunk_lines.peek().is_some() {
14243                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14244                        line.pop_front();
14245                    }
14246                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14247                        line.pop_back();
14248                    }
14249
14250                    lines.push(mem::take(&mut line));
14251                }
14252            }
14253        }
14254
14255        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14256            return;
14257        };
14258        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14259    }
14260
14261    pub fn open_context_menu(
14262        &mut self,
14263        _: &OpenContextMenu,
14264        window: &mut Window,
14265        cx: &mut Context<Self>,
14266    ) {
14267        self.request_autoscroll(Autoscroll::newest(), cx);
14268        let position = self.selections.newest_display(cx).start;
14269        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14270    }
14271
14272    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14273        &self.inlay_hint_cache
14274    }
14275
14276    pub fn replay_insert_event(
14277        &mut self,
14278        text: &str,
14279        relative_utf16_range: Option<Range<isize>>,
14280        window: &mut Window,
14281        cx: &mut Context<Self>,
14282    ) {
14283        if !self.input_enabled {
14284            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14285            return;
14286        }
14287        if let Some(relative_utf16_range) = relative_utf16_range {
14288            let selections = self.selections.all::<OffsetUtf16>(cx);
14289            self.change_selections(None, window, cx, |s| {
14290                let new_ranges = selections.into_iter().map(|range| {
14291                    let start = OffsetUtf16(
14292                        range
14293                            .head()
14294                            .0
14295                            .saturating_add_signed(relative_utf16_range.start),
14296                    );
14297                    let end = OffsetUtf16(
14298                        range
14299                            .head()
14300                            .0
14301                            .saturating_add_signed(relative_utf16_range.end),
14302                    );
14303                    start..end
14304                });
14305                s.select_ranges(new_ranges);
14306            });
14307        }
14308
14309        self.handle_input(text, window, cx);
14310    }
14311
14312    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14313        let Some(provider) = self.semantics_provider.as_ref() else {
14314            return false;
14315        };
14316
14317        let mut supports = false;
14318        self.buffer().read(cx).for_each_buffer(|buffer| {
14319            supports |= provider.supports_inlay_hints(buffer, cx);
14320        });
14321        supports
14322    }
14323    pub fn is_focused(&self, window: &mut Window) -> bool {
14324        self.focus_handle.is_focused(window)
14325    }
14326
14327    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14328        cx.emit(EditorEvent::Focused);
14329
14330        if let Some(descendant) = self
14331            .last_focused_descendant
14332            .take()
14333            .and_then(|descendant| descendant.upgrade())
14334        {
14335            window.focus(&descendant);
14336        } else {
14337            if let Some(blame) = self.blame.as_ref() {
14338                blame.update(cx, GitBlame::focus)
14339            }
14340
14341            self.blink_manager.update(cx, BlinkManager::enable);
14342            self.show_cursor_names(window, cx);
14343            self.buffer.update(cx, |buffer, cx| {
14344                buffer.finalize_last_transaction(cx);
14345                if self.leader_peer_id.is_none() {
14346                    buffer.set_active_selections(
14347                        &self.selections.disjoint_anchors(),
14348                        self.selections.line_mode,
14349                        self.cursor_shape,
14350                        cx,
14351                    );
14352                }
14353            });
14354        }
14355    }
14356
14357    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14358        cx.emit(EditorEvent::FocusedIn)
14359    }
14360
14361    fn handle_focus_out(
14362        &mut self,
14363        event: FocusOutEvent,
14364        _window: &mut Window,
14365        _cx: &mut Context<Self>,
14366    ) {
14367        if event.blurred != self.focus_handle {
14368            self.last_focused_descendant = Some(event.blurred);
14369        }
14370    }
14371
14372    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14373        self.blink_manager.update(cx, BlinkManager::disable);
14374        self.buffer
14375            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14376
14377        if let Some(blame) = self.blame.as_ref() {
14378            blame.update(cx, GitBlame::blur)
14379        }
14380        if !self.hover_state.focused(window, cx) {
14381            hide_hover(self, cx);
14382        }
14383
14384        self.hide_context_menu(window, cx);
14385        cx.emit(EditorEvent::Blurred);
14386        cx.notify();
14387    }
14388
14389    pub fn register_action<A: Action>(
14390        &mut self,
14391        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14392    ) -> Subscription {
14393        let id = self.next_editor_action_id.post_inc();
14394        let listener = Arc::new(listener);
14395        self.editor_actions.borrow_mut().insert(
14396            id,
14397            Box::new(move |window, _| {
14398                let listener = listener.clone();
14399                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14400                    let action = action.downcast_ref().unwrap();
14401                    if phase == DispatchPhase::Bubble {
14402                        listener(action, window, cx)
14403                    }
14404                })
14405            }),
14406        );
14407
14408        let editor_actions = self.editor_actions.clone();
14409        Subscription::new(move || {
14410            editor_actions.borrow_mut().remove(&id);
14411        })
14412    }
14413
14414    pub fn file_header_size(&self) -> u32 {
14415        FILE_HEADER_HEIGHT
14416    }
14417
14418    pub fn revert(
14419        &mut self,
14420        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14421        window: &mut Window,
14422        cx: &mut Context<Self>,
14423    ) {
14424        self.buffer().update(cx, |multi_buffer, cx| {
14425            for (buffer_id, changes) in revert_changes {
14426                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14427                    buffer.update(cx, |buffer, cx| {
14428                        buffer.edit(
14429                            changes.into_iter().map(|(range, text)| {
14430                                (range, text.to_string().map(Arc::<str>::from))
14431                            }),
14432                            None,
14433                            cx,
14434                        );
14435                    });
14436                }
14437            }
14438        });
14439        self.change_selections(None, window, cx, |selections| selections.refresh());
14440    }
14441
14442    pub fn to_pixel_point(
14443        &self,
14444        source: multi_buffer::Anchor,
14445        editor_snapshot: &EditorSnapshot,
14446        window: &mut Window,
14447    ) -> Option<gpui::Point<Pixels>> {
14448        let source_point = source.to_display_point(editor_snapshot);
14449        self.display_to_pixel_point(source_point, editor_snapshot, window)
14450    }
14451
14452    pub fn display_to_pixel_point(
14453        &self,
14454        source: DisplayPoint,
14455        editor_snapshot: &EditorSnapshot,
14456        window: &mut Window,
14457    ) -> Option<gpui::Point<Pixels>> {
14458        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14459        let text_layout_details = self.text_layout_details(window);
14460        let scroll_top = text_layout_details
14461            .scroll_anchor
14462            .scroll_position(editor_snapshot)
14463            .y;
14464
14465        if source.row().as_f32() < scroll_top.floor() {
14466            return None;
14467        }
14468        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14469        let source_y = line_height * (source.row().as_f32() - scroll_top);
14470        Some(gpui::Point::new(source_x, source_y))
14471    }
14472
14473    pub fn has_visible_completions_menu(&self) -> bool {
14474        !self.previewing_inline_completion
14475            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14476                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14477            })
14478    }
14479
14480    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14481        self.addons
14482            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14483    }
14484
14485    pub fn unregister_addon<T: Addon>(&mut self) {
14486        self.addons.remove(&std::any::TypeId::of::<T>());
14487    }
14488
14489    pub fn addon<T: Addon>(&self) -> Option<&T> {
14490        let type_id = std::any::TypeId::of::<T>();
14491        self.addons
14492            .get(&type_id)
14493            .and_then(|item| item.to_any().downcast_ref::<T>())
14494    }
14495
14496    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14497        let text_layout_details = self.text_layout_details(window);
14498        let style = &text_layout_details.editor_style;
14499        let font_id = window.text_system().resolve_font(&style.text.font());
14500        let font_size = style.text.font_size.to_pixels(window.rem_size());
14501        let line_height = style.text.line_height_in_pixels(window.rem_size());
14502        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14503
14504        gpui::Size::new(em_width, line_height)
14505    }
14506}
14507
14508fn get_uncommitted_changes_for_buffer(
14509    project: &Entity<Project>,
14510    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14511    buffer: Entity<MultiBuffer>,
14512    cx: &mut App,
14513) {
14514    let mut tasks = Vec::new();
14515    project.update(cx, |project, cx| {
14516        for buffer in buffers {
14517            tasks.push(project.open_uncommitted_changes(buffer.clone(), cx))
14518        }
14519    });
14520    cx.spawn(|mut cx| async move {
14521        let change_sets = futures::future::join_all(tasks).await;
14522        buffer
14523            .update(&mut cx, |buffer, cx| {
14524                for change_set in change_sets.into_iter().flatten() {
14525                    buffer.add_change_set(change_set, cx);
14526                }
14527            })
14528            .ok();
14529    })
14530    .detach();
14531}
14532
14533fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14534    let tab_size = tab_size.get() as usize;
14535    let mut width = offset;
14536
14537    for ch in text.chars() {
14538        width += if ch == '\t' {
14539            tab_size - (width % tab_size)
14540        } else {
14541            1
14542        };
14543    }
14544
14545    width - offset
14546}
14547
14548#[cfg(test)]
14549mod tests {
14550    use super::*;
14551
14552    #[test]
14553    fn test_string_size_with_expanded_tabs() {
14554        let nz = |val| NonZeroU32::new(val).unwrap();
14555        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14556        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14557        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14558        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14559        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14560        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14561        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14562        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14563    }
14564}
14565
14566/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14567struct WordBreakingTokenizer<'a> {
14568    input: &'a str,
14569}
14570
14571impl<'a> WordBreakingTokenizer<'a> {
14572    fn new(input: &'a str) -> Self {
14573        Self { input }
14574    }
14575}
14576
14577fn is_char_ideographic(ch: char) -> bool {
14578    use unicode_script::Script::*;
14579    use unicode_script::UnicodeScript;
14580    matches!(ch.script(), Han | Tangut | Yi)
14581}
14582
14583fn is_grapheme_ideographic(text: &str) -> bool {
14584    text.chars().any(is_char_ideographic)
14585}
14586
14587fn is_grapheme_whitespace(text: &str) -> bool {
14588    text.chars().any(|x| x.is_whitespace())
14589}
14590
14591fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14592    text.chars().next().map_or(false, |ch| {
14593        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14594    })
14595}
14596
14597#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14598struct WordBreakToken<'a> {
14599    token: &'a str,
14600    grapheme_len: usize,
14601    is_whitespace: bool,
14602}
14603
14604impl<'a> Iterator for WordBreakingTokenizer<'a> {
14605    /// Yields a span, the count of graphemes in the token, and whether it was
14606    /// whitespace. Note that it also breaks at word boundaries.
14607    type Item = WordBreakToken<'a>;
14608
14609    fn next(&mut self) -> Option<Self::Item> {
14610        use unicode_segmentation::UnicodeSegmentation;
14611        if self.input.is_empty() {
14612            return None;
14613        }
14614
14615        let mut iter = self.input.graphemes(true).peekable();
14616        let mut offset = 0;
14617        let mut graphemes = 0;
14618        if let Some(first_grapheme) = iter.next() {
14619            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14620            offset += first_grapheme.len();
14621            graphemes += 1;
14622            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14623                if let Some(grapheme) = iter.peek().copied() {
14624                    if should_stay_with_preceding_ideograph(grapheme) {
14625                        offset += grapheme.len();
14626                        graphemes += 1;
14627                    }
14628                }
14629            } else {
14630                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14631                let mut next_word_bound = words.peek().copied();
14632                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14633                    next_word_bound = words.next();
14634                }
14635                while let Some(grapheme) = iter.peek().copied() {
14636                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14637                        break;
14638                    };
14639                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14640                        break;
14641                    };
14642                    offset += grapheme.len();
14643                    graphemes += 1;
14644                    iter.next();
14645                }
14646            }
14647            let token = &self.input[..offset];
14648            self.input = &self.input[offset..];
14649            if is_whitespace {
14650                Some(WordBreakToken {
14651                    token: " ",
14652                    grapheme_len: 1,
14653                    is_whitespace: true,
14654                })
14655            } else {
14656                Some(WordBreakToken {
14657                    token,
14658                    grapheme_len: graphemes,
14659                    is_whitespace: false,
14660                })
14661            }
14662        } else {
14663            None
14664        }
14665    }
14666}
14667
14668#[test]
14669fn test_word_breaking_tokenizer() {
14670    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14671        ("", &[]),
14672        ("  ", &[(" ", 1, true)]),
14673        ("Ʒ", &[("Ʒ", 1, false)]),
14674        ("Ǽ", &[("Ǽ", 1, false)]),
14675        ("", &[("", 1, false)]),
14676        ("⋑⋑", &[("⋑⋑", 2, false)]),
14677        (
14678            "原理,进而",
14679            &[
14680                ("", 1, false),
14681                ("理,", 2, false),
14682                ("", 1, false),
14683                ("", 1, false),
14684            ],
14685        ),
14686        (
14687            "hello world",
14688            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14689        ),
14690        (
14691            "hello, world",
14692            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14693        ),
14694        (
14695            "  hello world",
14696            &[
14697                (" ", 1, true),
14698                ("hello", 5, false),
14699                (" ", 1, true),
14700                ("world", 5, false),
14701            ],
14702        ),
14703        (
14704            "这是什么 \n 钢笔",
14705            &[
14706                ("", 1, false),
14707                ("", 1, false),
14708                ("", 1, false),
14709                ("", 1, false),
14710                (" ", 1, true),
14711                ("", 1, false),
14712                ("", 1, false),
14713            ],
14714        ),
14715        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14716    ];
14717
14718    for (input, result) in tests {
14719        assert_eq!(
14720            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14721            result
14722                .iter()
14723                .copied()
14724                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14725                    token,
14726                    grapheme_len,
14727                    is_whitespace,
14728                })
14729                .collect::<Vec<_>>()
14730        );
14731    }
14732}
14733
14734fn wrap_with_prefix(
14735    line_prefix: String,
14736    unwrapped_text: String,
14737    wrap_column: usize,
14738    tab_size: NonZeroU32,
14739) -> String {
14740    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14741    let mut wrapped_text = String::new();
14742    let mut current_line = line_prefix.clone();
14743
14744    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14745    let mut current_line_len = line_prefix_len;
14746    for WordBreakToken {
14747        token,
14748        grapheme_len,
14749        is_whitespace,
14750    } in tokenizer
14751    {
14752        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14753            wrapped_text.push_str(current_line.trim_end());
14754            wrapped_text.push('\n');
14755            current_line.truncate(line_prefix.len());
14756            current_line_len = line_prefix_len;
14757            if !is_whitespace {
14758                current_line.push_str(token);
14759                current_line_len += grapheme_len;
14760            }
14761        } else if !is_whitespace {
14762            current_line.push_str(token);
14763            current_line_len += grapheme_len;
14764        } else if current_line_len != line_prefix_len {
14765            current_line.push(' ');
14766            current_line_len += 1;
14767        }
14768    }
14769
14770    if !current_line.is_empty() {
14771        wrapped_text.push_str(&current_line);
14772    }
14773    wrapped_text
14774}
14775
14776#[test]
14777fn test_wrap_with_prefix() {
14778    assert_eq!(
14779        wrap_with_prefix(
14780            "# ".to_string(),
14781            "abcdefg".to_string(),
14782            4,
14783            NonZeroU32::new(4).unwrap()
14784        ),
14785        "# abcdefg"
14786    );
14787    assert_eq!(
14788        wrap_with_prefix(
14789            "".to_string(),
14790            "\thello world".to_string(),
14791            8,
14792            NonZeroU32::new(4).unwrap()
14793        ),
14794        "hello\nworld"
14795    );
14796    assert_eq!(
14797        wrap_with_prefix(
14798            "// ".to_string(),
14799            "xx \nyy zz aa bb cc".to_string(),
14800            12,
14801            NonZeroU32::new(4).unwrap()
14802        ),
14803        "// xx yy zz\n// aa bb cc"
14804    );
14805    assert_eq!(
14806        wrap_with_prefix(
14807            String::new(),
14808            "这是什么 \n 钢笔".to_string(),
14809            3,
14810            NonZeroU32::new(4).unwrap()
14811        ),
14812        "这是什\n么 钢\n"
14813    );
14814}
14815
14816pub trait CollaborationHub {
14817    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14818    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14819    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14820}
14821
14822impl CollaborationHub for Entity<Project> {
14823    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14824        self.read(cx).collaborators()
14825    }
14826
14827    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14828        self.read(cx).user_store().read(cx).participant_indices()
14829    }
14830
14831    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14832        let this = self.read(cx);
14833        let user_ids = this.collaborators().values().map(|c| c.user_id);
14834        this.user_store().read_with(cx, |user_store, cx| {
14835            user_store.participant_names(user_ids, cx)
14836        })
14837    }
14838}
14839
14840pub trait SemanticsProvider {
14841    fn hover(
14842        &self,
14843        buffer: &Entity<Buffer>,
14844        position: text::Anchor,
14845        cx: &mut App,
14846    ) -> Option<Task<Vec<project::Hover>>>;
14847
14848    fn inlay_hints(
14849        &self,
14850        buffer_handle: Entity<Buffer>,
14851        range: Range<text::Anchor>,
14852        cx: &mut App,
14853    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14854
14855    fn resolve_inlay_hint(
14856        &self,
14857        hint: InlayHint,
14858        buffer_handle: Entity<Buffer>,
14859        server_id: LanguageServerId,
14860        cx: &mut App,
14861    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14862
14863    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14864
14865    fn document_highlights(
14866        &self,
14867        buffer: &Entity<Buffer>,
14868        position: text::Anchor,
14869        cx: &mut App,
14870    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14871
14872    fn definitions(
14873        &self,
14874        buffer: &Entity<Buffer>,
14875        position: text::Anchor,
14876        kind: GotoDefinitionKind,
14877        cx: &mut App,
14878    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14879
14880    fn range_for_rename(
14881        &self,
14882        buffer: &Entity<Buffer>,
14883        position: text::Anchor,
14884        cx: &mut App,
14885    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14886
14887    fn perform_rename(
14888        &self,
14889        buffer: &Entity<Buffer>,
14890        position: text::Anchor,
14891        new_name: String,
14892        cx: &mut App,
14893    ) -> Option<Task<Result<ProjectTransaction>>>;
14894}
14895
14896pub trait CompletionProvider {
14897    fn completions(
14898        &self,
14899        buffer: &Entity<Buffer>,
14900        buffer_position: text::Anchor,
14901        trigger: CompletionContext,
14902        window: &mut Window,
14903        cx: &mut Context<Editor>,
14904    ) -> Task<Result<Vec<Completion>>>;
14905
14906    fn resolve_completions(
14907        &self,
14908        buffer: Entity<Buffer>,
14909        completion_indices: Vec<usize>,
14910        completions: Rc<RefCell<Box<[Completion]>>>,
14911        cx: &mut Context<Editor>,
14912    ) -> Task<Result<bool>>;
14913
14914    fn apply_additional_edits_for_completion(
14915        &self,
14916        _buffer: Entity<Buffer>,
14917        _completions: Rc<RefCell<Box<[Completion]>>>,
14918        _completion_index: usize,
14919        _push_to_history: bool,
14920        _cx: &mut Context<Editor>,
14921    ) -> Task<Result<Option<language::Transaction>>> {
14922        Task::ready(Ok(None))
14923    }
14924
14925    fn is_completion_trigger(
14926        &self,
14927        buffer: &Entity<Buffer>,
14928        position: language::Anchor,
14929        text: &str,
14930        trigger_in_words: bool,
14931        cx: &mut Context<Editor>,
14932    ) -> bool;
14933
14934    fn sort_completions(&self) -> bool {
14935        true
14936    }
14937}
14938
14939pub trait CodeActionProvider {
14940    fn id(&self) -> Arc<str>;
14941
14942    fn code_actions(
14943        &self,
14944        buffer: &Entity<Buffer>,
14945        range: Range<text::Anchor>,
14946        window: &mut Window,
14947        cx: &mut App,
14948    ) -> Task<Result<Vec<CodeAction>>>;
14949
14950    fn apply_code_action(
14951        &self,
14952        buffer_handle: Entity<Buffer>,
14953        action: CodeAction,
14954        excerpt_id: ExcerptId,
14955        push_to_history: bool,
14956        window: &mut Window,
14957        cx: &mut App,
14958    ) -> Task<Result<ProjectTransaction>>;
14959}
14960
14961impl CodeActionProvider for Entity<Project> {
14962    fn id(&self) -> Arc<str> {
14963        "project".into()
14964    }
14965
14966    fn code_actions(
14967        &self,
14968        buffer: &Entity<Buffer>,
14969        range: Range<text::Anchor>,
14970        _window: &mut Window,
14971        cx: &mut App,
14972    ) -> Task<Result<Vec<CodeAction>>> {
14973        self.update(cx, |project, cx| {
14974            project.code_actions(buffer, range, None, cx)
14975        })
14976    }
14977
14978    fn apply_code_action(
14979        &self,
14980        buffer_handle: Entity<Buffer>,
14981        action: CodeAction,
14982        _excerpt_id: ExcerptId,
14983        push_to_history: bool,
14984        _window: &mut Window,
14985        cx: &mut App,
14986    ) -> Task<Result<ProjectTransaction>> {
14987        self.update(cx, |project, cx| {
14988            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14989        })
14990    }
14991}
14992
14993fn snippet_completions(
14994    project: &Project,
14995    buffer: &Entity<Buffer>,
14996    buffer_position: text::Anchor,
14997    cx: &mut App,
14998) -> Task<Result<Vec<Completion>>> {
14999    let language = buffer.read(cx).language_at(buffer_position);
15000    let language_name = language.as_ref().map(|language| language.lsp_id());
15001    let snippet_store = project.snippets().read(cx);
15002    let snippets = snippet_store.snippets_for(language_name, cx);
15003
15004    if snippets.is_empty() {
15005        return Task::ready(Ok(vec![]));
15006    }
15007    let snapshot = buffer.read(cx).text_snapshot();
15008    let chars: String = snapshot
15009        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15010        .collect();
15011
15012    let scope = language.map(|language| language.default_scope());
15013    let executor = cx.background_executor().clone();
15014
15015    cx.background_executor().spawn(async move {
15016        let classifier = CharClassifier::new(scope).for_completion(true);
15017        let mut last_word = chars
15018            .chars()
15019            .take_while(|c| classifier.is_word(*c))
15020            .collect::<String>();
15021        last_word = last_word.chars().rev().collect();
15022
15023        if last_word.is_empty() {
15024            return Ok(vec![]);
15025        }
15026
15027        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15028        let to_lsp = |point: &text::Anchor| {
15029            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15030            point_to_lsp(end)
15031        };
15032        let lsp_end = to_lsp(&buffer_position);
15033
15034        let candidates = snippets
15035            .iter()
15036            .enumerate()
15037            .flat_map(|(ix, snippet)| {
15038                snippet
15039                    .prefix
15040                    .iter()
15041                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15042            })
15043            .collect::<Vec<StringMatchCandidate>>();
15044
15045        let mut matches = fuzzy::match_strings(
15046            &candidates,
15047            &last_word,
15048            last_word.chars().any(|c| c.is_uppercase()),
15049            100,
15050            &Default::default(),
15051            executor,
15052        )
15053        .await;
15054
15055        // Remove all candidates where the query's start does not match the start of any word in the candidate
15056        if let Some(query_start) = last_word.chars().next() {
15057            matches.retain(|string_match| {
15058                split_words(&string_match.string).any(|word| {
15059                    // Check that the first codepoint of the word as lowercase matches the first
15060                    // codepoint of the query as lowercase
15061                    word.chars()
15062                        .flat_map(|codepoint| codepoint.to_lowercase())
15063                        .zip(query_start.to_lowercase())
15064                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15065                })
15066            });
15067        }
15068
15069        let matched_strings = matches
15070            .into_iter()
15071            .map(|m| m.string)
15072            .collect::<HashSet<_>>();
15073
15074        let result: Vec<Completion> = snippets
15075            .into_iter()
15076            .filter_map(|snippet| {
15077                let matching_prefix = snippet
15078                    .prefix
15079                    .iter()
15080                    .find(|prefix| matched_strings.contains(*prefix))?;
15081                let start = as_offset - last_word.len();
15082                let start = snapshot.anchor_before(start);
15083                let range = start..buffer_position;
15084                let lsp_start = to_lsp(&start);
15085                let lsp_range = lsp::Range {
15086                    start: lsp_start,
15087                    end: lsp_end,
15088                };
15089                Some(Completion {
15090                    old_range: range,
15091                    new_text: snippet.body.clone(),
15092                    resolved: false,
15093                    label: CodeLabel {
15094                        text: matching_prefix.clone(),
15095                        runs: vec![],
15096                        filter_range: 0..matching_prefix.len(),
15097                    },
15098                    server_id: LanguageServerId(usize::MAX),
15099                    documentation: snippet
15100                        .description
15101                        .clone()
15102                        .map(CompletionDocumentation::SingleLine),
15103                    lsp_completion: lsp::CompletionItem {
15104                        label: snippet.prefix.first().unwrap().clone(),
15105                        kind: Some(CompletionItemKind::SNIPPET),
15106                        label_details: snippet.description.as_ref().map(|description| {
15107                            lsp::CompletionItemLabelDetails {
15108                                detail: Some(description.clone()),
15109                                description: None,
15110                            }
15111                        }),
15112                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15113                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15114                            lsp::InsertReplaceEdit {
15115                                new_text: snippet.body.clone(),
15116                                insert: lsp_range,
15117                                replace: lsp_range,
15118                            },
15119                        )),
15120                        filter_text: Some(snippet.body.clone()),
15121                        sort_text: Some(char::MAX.to_string()),
15122                        ..Default::default()
15123                    },
15124                    confirm: None,
15125                })
15126            })
15127            .collect();
15128
15129        Ok(result)
15130    })
15131}
15132
15133impl CompletionProvider for Entity<Project> {
15134    fn completions(
15135        &self,
15136        buffer: &Entity<Buffer>,
15137        buffer_position: text::Anchor,
15138        options: CompletionContext,
15139        _window: &mut Window,
15140        cx: &mut Context<Editor>,
15141    ) -> Task<Result<Vec<Completion>>> {
15142        self.update(cx, |project, cx| {
15143            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15144            let project_completions = project.completions(buffer, buffer_position, options, cx);
15145            cx.background_executor().spawn(async move {
15146                let mut completions = project_completions.await?;
15147                let snippets_completions = snippets.await?;
15148                completions.extend(snippets_completions);
15149                Ok(completions)
15150            })
15151        })
15152    }
15153
15154    fn resolve_completions(
15155        &self,
15156        buffer: Entity<Buffer>,
15157        completion_indices: Vec<usize>,
15158        completions: Rc<RefCell<Box<[Completion]>>>,
15159        cx: &mut Context<Editor>,
15160    ) -> Task<Result<bool>> {
15161        self.update(cx, |project, cx| {
15162            project.lsp_store().update(cx, |lsp_store, cx| {
15163                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15164            })
15165        })
15166    }
15167
15168    fn apply_additional_edits_for_completion(
15169        &self,
15170        buffer: Entity<Buffer>,
15171        completions: Rc<RefCell<Box<[Completion]>>>,
15172        completion_index: usize,
15173        push_to_history: bool,
15174        cx: &mut Context<Editor>,
15175    ) -> Task<Result<Option<language::Transaction>>> {
15176        self.update(cx, |project, cx| {
15177            project.lsp_store().update(cx, |lsp_store, cx| {
15178                lsp_store.apply_additional_edits_for_completion(
15179                    buffer,
15180                    completions,
15181                    completion_index,
15182                    push_to_history,
15183                    cx,
15184                )
15185            })
15186        })
15187    }
15188
15189    fn is_completion_trigger(
15190        &self,
15191        buffer: &Entity<Buffer>,
15192        position: language::Anchor,
15193        text: &str,
15194        trigger_in_words: bool,
15195        cx: &mut Context<Editor>,
15196    ) -> bool {
15197        let mut chars = text.chars();
15198        let char = if let Some(char) = chars.next() {
15199            char
15200        } else {
15201            return false;
15202        };
15203        if chars.next().is_some() {
15204            return false;
15205        }
15206
15207        let buffer = buffer.read(cx);
15208        let snapshot = buffer.snapshot();
15209        if !snapshot.settings_at(position, cx).show_completions_on_input {
15210            return false;
15211        }
15212        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15213        if trigger_in_words && classifier.is_word(char) {
15214            return true;
15215        }
15216
15217        buffer.completion_triggers().contains(text)
15218    }
15219}
15220
15221impl SemanticsProvider for Entity<Project> {
15222    fn hover(
15223        &self,
15224        buffer: &Entity<Buffer>,
15225        position: text::Anchor,
15226        cx: &mut App,
15227    ) -> Option<Task<Vec<project::Hover>>> {
15228        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15229    }
15230
15231    fn document_highlights(
15232        &self,
15233        buffer: &Entity<Buffer>,
15234        position: text::Anchor,
15235        cx: &mut App,
15236    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15237        Some(self.update(cx, |project, cx| {
15238            project.document_highlights(buffer, position, cx)
15239        }))
15240    }
15241
15242    fn definitions(
15243        &self,
15244        buffer: &Entity<Buffer>,
15245        position: text::Anchor,
15246        kind: GotoDefinitionKind,
15247        cx: &mut App,
15248    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15249        Some(self.update(cx, |project, cx| match kind {
15250            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15251            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15252            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15253            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15254        }))
15255    }
15256
15257    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15258        // TODO: make this work for remote projects
15259        self.read(cx)
15260            .language_servers_for_local_buffer(buffer.read(cx), cx)
15261            .any(
15262                |(_, server)| match server.capabilities().inlay_hint_provider {
15263                    Some(lsp::OneOf::Left(enabled)) => enabled,
15264                    Some(lsp::OneOf::Right(_)) => true,
15265                    None => false,
15266                },
15267            )
15268    }
15269
15270    fn inlay_hints(
15271        &self,
15272        buffer_handle: Entity<Buffer>,
15273        range: Range<text::Anchor>,
15274        cx: &mut App,
15275    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15276        Some(self.update(cx, |project, cx| {
15277            project.inlay_hints(buffer_handle, range, cx)
15278        }))
15279    }
15280
15281    fn resolve_inlay_hint(
15282        &self,
15283        hint: InlayHint,
15284        buffer_handle: Entity<Buffer>,
15285        server_id: LanguageServerId,
15286        cx: &mut App,
15287    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15288        Some(self.update(cx, |project, cx| {
15289            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15290        }))
15291    }
15292
15293    fn range_for_rename(
15294        &self,
15295        buffer: &Entity<Buffer>,
15296        position: text::Anchor,
15297        cx: &mut App,
15298    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15299        Some(self.update(cx, |project, cx| {
15300            let buffer = buffer.clone();
15301            let task = project.prepare_rename(buffer.clone(), position, cx);
15302            cx.spawn(|_, mut cx| async move {
15303                Ok(match task.await? {
15304                    PrepareRenameResponse::Success(range) => Some(range),
15305                    PrepareRenameResponse::InvalidPosition => None,
15306                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15307                        // Fallback on using TreeSitter info to determine identifier range
15308                        buffer.update(&mut cx, |buffer, _| {
15309                            let snapshot = buffer.snapshot();
15310                            let (range, kind) = snapshot.surrounding_word(position);
15311                            if kind != Some(CharKind::Word) {
15312                                return None;
15313                            }
15314                            Some(
15315                                snapshot.anchor_before(range.start)
15316                                    ..snapshot.anchor_after(range.end),
15317                            )
15318                        })?
15319                    }
15320                })
15321            })
15322        }))
15323    }
15324
15325    fn perform_rename(
15326        &self,
15327        buffer: &Entity<Buffer>,
15328        position: text::Anchor,
15329        new_name: String,
15330        cx: &mut App,
15331    ) -> Option<Task<Result<ProjectTransaction>>> {
15332        Some(self.update(cx, |project, cx| {
15333            project.perform_rename(buffer.clone(), position, new_name, cx)
15334        }))
15335    }
15336}
15337
15338fn inlay_hint_settings(
15339    location: Anchor,
15340    snapshot: &MultiBufferSnapshot,
15341    cx: &mut Context<Editor>,
15342) -> InlayHintSettings {
15343    let file = snapshot.file_at(location);
15344    let language = snapshot.language_at(location).map(|l| l.name());
15345    language_settings(language, file, cx).inlay_hints
15346}
15347
15348fn consume_contiguous_rows(
15349    contiguous_row_selections: &mut Vec<Selection<Point>>,
15350    selection: &Selection<Point>,
15351    display_map: &DisplaySnapshot,
15352    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15353) -> (MultiBufferRow, MultiBufferRow) {
15354    contiguous_row_selections.push(selection.clone());
15355    let start_row = MultiBufferRow(selection.start.row);
15356    let mut end_row = ending_row(selection, display_map);
15357
15358    while let Some(next_selection) = selections.peek() {
15359        if next_selection.start.row <= end_row.0 {
15360            end_row = ending_row(next_selection, display_map);
15361            contiguous_row_selections.push(selections.next().unwrap().clone());
15362        } else {
15363            break;
15364        }
15365    }
15366    (start_row, end_row)
15367}
15368
15369fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15370    if next_selection.end.column > 0 || next_selection.is_empty() {
15371        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15372    } else {
15373        MultiBufferRow(next_selection.end.row)
15374    }
15375}
15376
15377impl EditorSnapshot {
15378    pub fn remote_selections_in_range<'a>(
15379        &'a self,
15380        range: &'a Range<Anchor>,
15381        collaboration_hub: &dyn CollaborationHub,
15382        cx: &'a App,
15383    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15384        let participant_names = collaboration_hub.user_names(cx);
15385        let participant_indices = collaboration_hub.user_participant_indices(cx);
15386        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15387        let collaborators_by_replica_id = collaborators_by_peer_id
15388            .iter()
15389            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15390            .collect::<HashMap<_, _>>();
15391        self.buffer_snapshot
15392            .selections_in_range(range, false)
15393            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15394                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15395                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15396                let user_name = participant_names.get(&collaborator.user_id).cloned();
15397                Some(RemoteSelection {
15398                    replica_id,
15399                    selection,
15400                    cursor_shape,
15401                    line_mode,
15402                    participant_index,
15403                    peer_id: collaborator.peer_id,
15404                    user_name,
15405                })
15406            })
15407    }
15408
15409    pub fn hunks_for_ranges(
15410        &self,
15411        ranges: impl Iterator<Item = Range<Point>>,
15412    ) -> Vec<MultiBufferDiffHunk> {
15413        let mut hunks = Vec::new();
15414        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15415            HashMap::default();
15416        for query_range in ranges {
15417            let query_rows =
15418                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15419            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15420                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15421            ) {
15422                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15423                // when the caret is just above or just below the deleted hunk.
15424                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15425                let related_to_selection = if allow_adjacent {
15426                    hunk.row_range.overlaps(&query_rows)
15427                        || hunk.row_range.start == query_rows.end
15428                        || hunk.row_range.end == query_rows.start
15429                } else {
15430                    hunk.row_range.overlaps(&query_rows)
15431                };
15432                if related_to_selection {
15433                    if !processed_buffer_rows
15434                        .entry(hunk.buffer_id)
15435                        .or_default()
15436                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15437                    {
15438                        continue;
15439                    }
15440                    hunks.push(hunk);
15441                }
15442            }
15443        }
15444
15445        hunks
15446    }
15447
15448    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15449        self.display_snapshot.buffer_snapshot.language_at(position)
15450    }
15451
15452    pub fn is_focused(&self) -> bool {
15453        self.is_focused
15454    }
15455
15456    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15457        self.placeholder_text.as_ref()
15458    }
15459
15460    pub fn scroll_position(&self) -> gpui::Point<f32> {
15461        self.scroll_anchor.scroll_position(&self.display_snapshot)
15462    }
15463
15464    fn gutter_dimensions(
15465        &self,
15466        font_id: FontId,
15467        font_size: Pixels,
15468        max_line_number_width: Pixels,
15469        cx: &App,
15470    ) -> Option<GutterDimensions> {
15471        if !self.show_gutter {
15472            return None;
15473        }
15474
15475        let descent = cx.text_system().descent(font_id, font_size);
15476        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15477        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15478
15479        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15480            matches!(
15481                ProjectSettings::get_global(cx).git.git_gutter,
15482                Some(GitGutterSetting::TrackedFiles)
15483            )
15484        });
15485        let gutter_settings = EditorSettings::get_global(cx).gutter;
15486        let show_line_numbers = self
15487            .show_line_numbers
15488            .unwrap_or(gutter_settings.line_numbers);
15489        let line_gutter_width = if show_line_numbers {
15490            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15491            let min_width_for_number_on_gutter = em_advance * 4.0;
15492            max_line_number_width.max(min_width_for_number_on_gutter)
15493        } else {
15494            0.0.into()
15495        };
15496
15497        let show_code_actions = self
15498            .show_code_actions
15499            .unwrap_or(gutter_settings.code_actions);
15500
15501        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15502
15503        let git_blame_entries_width =
15504            self.git_blame_gutter_max_author_length
15505                .map(|max_author_length| {
15506                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15507
15508                    /// The number of characters to dedicate to gaps and margins.
15509                    const SPACING_WIDTH: usize = 4;
15510
15511                    let max_char_count = max_author_length
15512                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15513                        + ::git::SHORT_SHA_LENGTH
15514                        + MAX_RELATIVE_TIMESTAMP.len()
15515                        + SPACING_WIDTH;
15516
15517                    em_advance * max_char_count
15518                });
15519
15520        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15521        left_padding += if show_code_actions || show_runnables {
15522            em_width * 3.0
15523        } else if show_git_gutter && show_line_numbers {
15524            em_width * 2.0
15525        } else if show_git_gutter || show_line_numbers {
15526            em_width
15527        } else {
15528            px(0.)
15529        };
15530
15531        let right_padding = if gutter_settings.folds && show_line_numbers {
15532            em_width * 4.0
15533        } else if gutter_settings.folds {
15534            em_width * 3.0
15535        } else if show_line_numbers {
15536            em_width
15537        } else {
15538            px(0.)
15539        };
15540
15541        Some(GutterDimensions {
15542            left_padding,
15543            right_padding,
15544            width: line_gutter_width + left_padding + right_padding,
15545            margin: -descent,
15546            git_blame_entries_width,
15547        })
15548    }
15549
15550    pub fn render_crease_toggle(
15551        &self,
15552        buffer_row: MultiBufferRow,
15553        row_contains_cursor: bool,
15554        editor: Entity<Editor>,
15555        window: &mut Window,
15556        cx: &mut App,
15557    ) -> Option<AnyElement> {
15558        let folded = self.is_line_folded(buffer_row);
15559        let mut is_foldable = false;
15560
15561        if let Some(crease) = self
15562            .crease_snapshot
15563            .query_row(buffer_row, &self.buffer_snapshot)
15564        {
15565            is_foldable = true;
15566            match crease {
15567                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15568                    if let Some(render_toggle) = render_toggle {
15569                        let toggle_callback =
15570                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15571                                if folded {
15572                                    editor.update(cx, |editor, cx| {
15573                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15574                                    });
15575                                } else {
15576                                    editor.update(cx, |editor, cx| {
15577                                        editor.unfold_at(
15578                                            &crate::UnfoldAt { buffer_row },
15579                                            window,
15580                                            cx,
15581                                        )
15582                                    });
15583                                }
15584                            });
15585                        return Some((render_toggle)(
15586                            buffer_row,
15587                            folded,
15588                            toggle_callback,
15589                            window,
15590                            cx,
15591                        ));
15592                    }
15593                }
15594            }
15595        }
15596
15597        is_foldable |= self.starts_indent(buffer_row);
15598
15599        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15600            Some(
15601                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15602                    .toggle_state(folded)
15603                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15604                        if folded {
15605                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15606                        } else {
15607                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15608                        }
15609                    }))
15610                    .into_any_element(),
15611            )
15612        } else {
15613            None
15614        }
15615    }
15616
15617    pub fn render_crease_trailer(
15618        &self,
15619        buffer_row: MultiBufferRow,
15620        window: &mut Window,
15621        cx: &mut App,
15622    ) -> Option<AnyElement> {
15623        let folded = self.is_line_folded(buffer_row);
15624        if let Crease::Inline { render_trailer, .. } = self
15625            .crease_snapshot
15626            .query_row(buffer_row, &self.buffer_snapshot)?
15627        {
15628            let render_trailer = render_trailer.as_ref()?;
15629            Some(render_trailer(buffer_row, folded, window, cx))
15630        } else {
15631            None
15632        }
15633    }
15634}
15635
15636impl Deref for EditorSnapshot {
15637    type Target = DisplaySnapshot;
15638
15639    fn deref(&self) -> &Self::Target {
15640        &self.display_snapshot
15641    }
15642}
15643
15644#[derive(Clone, Debug, PartialEq, Eq)]
15645pub enum EditorEvent {
15646    InputIgnored {
15647        text: Arc<str>,
15648    },
15649    InputHandled {
15650        utf16_range_to_replace: Option<Range<isize>>,
15651        text: Arc<str>,
15652    },
15653    ExcerptsAdded {
15654        buffer: Entity<Buffer>,
15655        predecessor: ExcerptId,
15656        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15657    },
15658    ExcerptsRemoved {
15659        ids: Vec<ExcerptId>,
15660    },
15661    BufferFoldToggled {
15662        ids: Vec<ExcerptId>,
15663        folded: bool,
15664    },
15665    ExcerptsEdited {
15666        ids: Vec<ExcerptId>,
15667    },
15668    ExcerptsExpanded {
15669        ids: Vec<ExcerptId>,
15670    },
15671    BufferEdited,
15672    Edited {
15673        transaction_id: clock::Lamport,
15674    },
15675    Reparsed(BufferId),
15676    Focused,
15677    FocusedIn,
15678    Blurred,
15679    DirtyChanged,
15680    Saved,
15681    TitleChanged,
15682    DiffBaseChanged,
15683    SelectionsChanged {
15684        local: bool,
15685    },
15686    ScrollPositionChanged {
15687        local: bool,
15688        autoscroll: bool,
15689    },
15690    Closed,
15691    TransactionUndone {
15692        transaction_id: clock::Lamport,
15693    },
15694    TransactionBegun {
15695        transaction_id: clock::Lamport,
15696    },
15697    Reloaded,
15698    CursorShapeChanged,
15699}
15700
15701impl EventEmitter<EditorEvent> for Editor {}
15702
15703impl Focusable for Editor {
15704    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15705        self.focus_handle.clone()
15706    }
15707}
15708
15709impl Render for Editor {
15710    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15711        let settings = ThemeSettings::get_global(cx);
15712
15713        let mut text_style = match self.mode {
15714            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15715                color: cx.theme().colors().editor_foreground,
15716                font_family: settings.ui_font.family.clone(),
15717                font_features: settings.ui_font.features.clone(),
15718                font_fallbacks: settings.ui_font.fallbacks.clone(),
15719                font_size: rems(0.875).into(),
15720                font_weight: settings.ui_font.weight,
15721                line_height: relative(settings.buffer_line_height.value()),
15722                ..Default::default()
15723            },
15724            EditorMode::Full => TextStyle {
15725                color: cx.theme().colors().editor_foreground,
15726                font_family: settings.buffer_font.family.clone(),
15727                font_features: settings.buffer_font.features.clone(),
15728                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15729                font_size: settings.buffer_font_size().into(),
15730                font_weight: settings.buffer_font.weight,
15731                line_height: relative(settings.buffer_line_height.value()),
15732                ..Default::default()
15733            },
15734        };
15735        if let Some(text_style_refinement) = &self.text_style_refinement {
15736            text_style.refine(text_style_refinement)
15737        }
15738
15739        let background = match self.mode {
15740            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15741            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15742            EditorMode::Full => cx.theme().colors().editor_background,
15743        };
15744
15745        EditorElement::new(
15746            &cx.entity(),
15747            EditorStyle {
15748                background,
15749                local_player: cx.theme().players().local(),
15750                text: text_style,
15751                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15752                syntax: cx.theme().syntax().clone(),
15753                status: cx.theme().status().clone(),
15754                inlay_hints_style: make_inlay_hints_style(cx),
15755                inline_completion_styles: make_suggestion_styles(cx),
15756                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15757            },
15758        )
15759    }
15760}
15761
15762impl EntityInputHandler for Editor {
15763    fn text_for_range(
15764        &mut self,
15765        range_utf16: Range<usize>,
15766        adjusted_range: &mut Option<Range<usize>>,
15767        _: &mut Window,
15768        cx: &mut Context<Self>,
15769    ) -> Option<String> {
15770        let snapshot = self.buffer.read(cx).read(cx);
15771        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15772        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15773        if (start.0..end.0) != range_utf16 {
15774            adjusted_range.replace(start.0..end.0);
15775        }
15776        Some(snapshot.text_for_range(start..end).collect())
15777    }
15778
15779    fn selected_text_range(
15780        &mut self,
15781        ignore_disabled_input: bool,
15782        _: &mut Window,
15783        cx: &mut Context<Self>,
15784    ) -> Option<UTF16Selection> {
15785        // Prevent the IME menu from appearing when holding down an alphabetic key
15786        // while input is disabled.
15787        if !ignore_disabled_input && !self.input_enabled {
15788            return None;
15789        }
15790
15791        let selection = self.selections.newest::<OffsetUtf16>(cx);
15792        let range = selection.range();
15793
15794        Some(UTF16Selection {
15795            range: range.start.0..range.end.0,
15796            reversed: selection.reversed,
15797        })
15798    }
15799
15800    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15801        let snapshot = self.buffer.read(cx).read(cx);
15802        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15803        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15804    }
15805
15806    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15807        self.clear_highlights::<InputComposition>(cx);
15808        self.ime_transaction.take();
15809    }
15810
15811    fn replace_text_in_range(
15812        &mut self,
15813        range_utf16: Option<Range<usize>>,
15814        text: &str,
15815        window: &mut Window,
15816        cx: &mut Context<Self>,
15817    ) {
15818        if !self.input_enabled {
15819            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15820            return;
15821        }
15822
15823        self.transact(window, cx, |this, window, cx| {
15824            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15825                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15826                Some(this.selection_replacement_ranges(range_utf16, cx))
15827            } else {
15828                this.marked_text_ranges(cx)
15829            };
15830
15831            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15832                let newest_selection_id = this.selections.newest_anchor().id;
15833                this.selections
15834                    .all::<OffsetUtf16>(cx)
15835                    .iter()
15836                    .zip(ranges_to_replace.iter())
15837                    .find_map(|(selection, range)| {
15838                        if selection.id == newest_selection_id {
15839                            Some(
15840                                (range.start.0 as isize - selection.head().0 as isize)
15841                                    ..(range.end.0 as isize - selection.head().0 as isize),
15842                            )
15843                        } else {
15844                            None
15845                        }
15846                    })
15847            });
15848
15849            cx.emit(EditorEvent::InputHandled {
15850                utf16_range_to_replace: range_to_replace,
15851                text: text.into(),
15852            });
15853
15854            if let Some(new_selected_ranges) = new_selected_ranges {
15855                this.change_selections(None, window, cx, |selections| {
15856                    selections.select_ranges(new_selected_ranges)
15857                });
15858                this.backspace(&Default::default(), window, cx);
15859            }
15860
15861            this.handle_input(text, window, cx);
15862        });
15863
15864        if let Some(transaction) = self.ime_transaction {
15865            self.buffer.update(cx, |buffer, cx| {
15866                buffer.group_until_transaction(transaction, cx);
15867            });
15868        }
15869
15870        self.unmark_text(window, cx);
15871    }
15872
15873    fn replace_and_mark_text_in_range(
15874        &mut self,
15875        range_utf16: Option<Range<usize>>,
15876        text: &str,
15877        new_selected_range_utf16: Option<Range<usize>>,
15878        window: &mut Window,
15879        cx: &mut Context<Self>,
15880    ) {
15881        if !self.input_enabled {
15882            return;
15883        }
15884
15885        let transaction = self.transact(window, cx, |this, window, cx| {
15886            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15887                let snapshot = this.buffer.read(cx).read(cx);
15888                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15889                    for marked_range in &mut marked_ranges {
15890                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15891                        marked_range.start.0 += relative_range_utf16.start;
15892                        marked_range.start =
15893                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15894                        marked_range.end =
15895                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15896                    }
15897                }
15898                Some(marked_ranges)
15899            } else if let Some(range_utf16) = range_utf16 {
15900                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15901                Some(this.selection_replacement_ranges(range_utf16, cx))
15902            } else {
15903                None
15904            };
15905
15906            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15907                let newest_selection_id = this.selections.newest_anchor().id;
15908                this.selections
15909                    .all::<OffsetUtf16>(cx)
15910                    .iter()
15911                    .zip(ranges_to_replace.iter())
15912                    .find_map(|(selection, range)| {
15913                        if selection.id == newest_selection_id {
15914                            Some(
15915                                (range.start.0 as isize - selection.head().0 as isize)
15916                                    ..(range.end.0 as isize - selection.head().0 as isize),
15917                            )
15918                        } else {
15919                            None
15920                        }
15921                    })
15922            });
15923
15924            cx.emit(EditorEvent::InputHandled {
15925                utf16_range_to_replace: range_to_replace,
15926                text: text.into(),
15927            });
15928
15929            if let Some(ranges) = ranges_to_replace {
15930                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15931            }
15932
15933            let marked_ranges = {
15934                let snapshot = this.buffer.read(cx).read(cx);
15935                this.selections
15936                    .disjoint_anchors()
15937                    .iter()
15938                    .map(|selection| {
15939                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15940                    })
15941                    .collect::<Vec<_>>()
15942            };
15943
15944            if text.is_empty() {
15945                this.unmark_text(window, cx);
15946            } else {
15947                this.highlight_text::<InputComposition>(
15948                    marked_ranges.clone(),
15949                    HighlightStyle {
15950                        underline: Some(UnderlineStyle {
15951                            thickness: px(1.),
15952                            color: None,
15953                            wavy: false,
15954                        }),
15955                        ..Default::default()
15956                    },
15957                    cx,
15958                );
15959            }
15960
15961            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15962            let use_autoclose = this.use_autoclose;
15963            let use_auto_surround = this.use_auto_surround;
15964            this.set_use_autoclose(false);
15965            this.set_use_auto_surround(false);
15966            this.handle_input(text, window, cx);
15967            this.set_use_autoclose(use_autoclose);
15968            this.set_use_auto_surround(use_auto_surround);
15969
15970            if let Some(new_selected_range) = new_selected_range_utf16 {
15971                let snapshot = this.buffer.read(cx).read(cx);
15972                let new_selected_ranges = marked_ranges
15973                    .into_iter()
15974                    .map(|marked_range| {
15975                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15976                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15977                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15978                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15979                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15980                    })
15981                    .collect::<Vec<_>>();
15982
15983                drop(snapshot);
15984                this.change_selections(None, window, cx, |selections| {
15985                    selections.select_ranges(new_selected_ranges)
15986                });
15987            }
15988        });
15989
15990        self.ime_transaction = self.ime_transaction.or(transaction);
15991        if let Some(transaction) = self.ime_transaction {
15992            self.buffer.update(cx, |buffer, cx| {
15993                buffer.group_until_transaction(transaction, cx);
15994            });
15995        }
15996
15997        if self.text_highlights::<InputComposition>(cx).is_none() {
15998            self.ime_transaction.take();
15999        }
16000    }
16001
16002    fn bounds_for_range(
16003        &mut self,
16004        range_utf16: Range<usize>,
16005        element_bounds: gpui::Bounds<Pixels>,
16006        window: &mut Window,
16007        cx: &mut Context<Self>,
16008    ) -> Option<gpui::Bounds<Pixels>> {
16009        let text_layout_details = self.text_layout_details(window);
16010        let gpui::Size {
16011            width: em_width,
16012            height: line_height,
16013        } = self.character_size(window);
16014
16015        let snapshot = self.snapshot(window, cx);
16016        let scroll_position = snapshot.scroll_position();
16017        let scroll_left = scroll_position.x * em_width;
16018
16019        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16020        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16021            + self.gutter_dimensions.width
16022            + self.gutter_dimensions.margin;
16023        let y = line_height * (start.row().as_f32() - scroll_position.y);
16024
16025        Some(Bounds {
16026            origin: element_bounds.origin + point(x, y),
16027            size: size(em_width, line_height),
16028        })
16029    }
16030
16031    fn character_index_for_point(
16032        &mut self,
16033        point: gpui::Point<Pixels>,
16034        _window: &mut Window,
16035        _cx: &mut Context<Self>,
16036    ) -> Option<usize> {
16037        let position_map = self.last_position_map.as_ref()?;
16038        if !position_map.text_hitbox.contains(&point) {
16039            return None;
16040        }
16041        let display_point = position_map.point_for_position(point).previous_valid;
16042        let anchor = position_map
16043            .snapshot
16044            .display_point_to_anchor(display_point, Bias::Left);
16045        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16046        Some(utf16_offset.0)
16047    }
16048}
16049
16050trait SelectionExt {
16051    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16052    fn spanned_rows(
16053        &self,
16054        include_end_if_at_line_start: bool,
16055        map: &DisplaySnapshot,
16056    ) -> Range<MultiBufferRow>;
16057}
16058
16059impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16060    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16061        let start = self
16062            .start
16063            .to_point(&map.buffer_snapshot)
16064            .to_display_point(map);
16065        let end = self
16066            .end
16067            .to_point(&map.buffer_snapshot)
16068            .to_display_point(map);
16069        if self.reversed {
16070            end..start
16071        } else {
16072            start..end
16073        }
16074    }
16075
16076    fn spanned_rows(
16077        &self,
16078        include_end_if_at_line_start: bool,
16079        map: &DisplaySnapshot,
16080    ) -> Range<MultiBufferRow> {
16081        let start = self.start.to_point(&map.buffer_snapshot);
16082        let mut end = self.end.to_point(&map.buffer_snapshot);
16083        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16084            end.row -= 1;
16085        }
16086
16087        let buffer_start = map.prev_line_boundary(start).0;
16088        let buffer_end = map.next_line_boundary(end).0;
16089        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16090    }
16091}
16092
16093impl<T: InvalidationRegion> InvalidationStack<T> {
16094    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16095    where
16096        S: Clone + ToOffset,
16097    {
16098        while let Some(region) = self.last() {
16099            let all_selections_inside_invalidation_ranges =
16100                if selections.len() == region.ranges().len() {
16101                    selections
16102                        .iter()
16103                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16104                        .all(|(selection, invalidation_range)| {
16105                            let head = selection.head().to_offset(buffer);
16106                            invalidation_range.start <= head && invalidation_range.end >= head
16107                        })
16108                } else {
16109                    false
16110                };
16111
16112            if all_selections_inside_invalidation_ranges {
16113                break;
16114            } else {
16115                self.pop();
16116            }
16117        }
16118    }
16119}
16120
16121impl<T> Default for InvalidationStack<T> {
16122    fn default() -> Self {
16123        Self(Default::default())
16124    }
16125}
16126
16127impl<T> Deref for InvalidationStack<T> {
16128    type Target = Vec<T>;
16129
16130    fn deref(&self) -> &Self::Target {
16131        &self.0
16132    }
16133}
16134
16135impl<T> DerefMut for InvalidationStack<T> {
16136    fn deref_mut(&mut self) -> &mut Self::Target {
16137        &mut self.0
16138    }
16139}
16140
16141impl InvalidationRegion for SnippetState {
16142    fn ranges(&self) -> &[Range<Anchor>] {
16143        &self.ranges[self.active_index]
16144    }
16145}
16146
16147pub fn diagnostic_block_renderer(
16148    diagnostic: Diagnostic,
16149    max_message_rows: Option<u8>,
16150    allow_closing: bool,
16151    _is_valid: bool,
16152) -> RenderBlock {
16153    let (text_without_backticks, code_ranges) =
16154        highlight_diagnostic_message(&diagnostic, max_message_rows);
16155
16156    Arc::new(move |cx: &mut BlockContext| {
16157        let group_id: SharedString = cx.block_id.to_string().into();
16158
16159        let mut text_style = cx.window.text_style().clone();
16160        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16161        let theme_settings = ThemeSettings::get_global(cx);
16162        text_style.font_family = theme_settings.buffer_font.family.clone();
16163        text_style.font_style = theme_settings.buffer_font.style;
16164        text_style.font_features = theme_settings.buffer_font.features.clone();
16165        text_style.font_weight = theme_settings.buffer_font.weight;
16166
16167        let multi_line_diagnostic = diagnostic.message.contains('\n');
16168
16169        let buttons = |diagnostic: &Diagnostic| {
16170            if multi_line_diagnostic {
16171                v_flex()
16172            } else {
16173                h_flex()
16174            }
16175            .when(allow_closing, |div| {
16176                div.children(diagnostic.is_primary.then(|| {
16177                    IconButton::new("close-block", IconName::XCircle)
16178                        .icon_color(Color::Muted)
16179                        .size(ButtonSize::Compact)
16180                        .style(ButtonStyle::Transparent)
16181                        .visible_on_hover(group_id.clone())
16182                        .on_click(move |_click, window, cx| {
16183                            window.dispatch_action(Box::new(Cancel), cx)
16184                        })
16185                        .tooltip(|window, cx| {
16186                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16187                        })
16188                }))
16189            })
16190            .child(
16191                IconButton::new("copy-block", IconName::Copy)
16192                    .icon_color(Color::Muted)
16193                    .size(ButtonSize::Compact)
16194                    .style(ButtonStyle::Transparent)
16195                    .visible_on_hover(group_id.clone())
16196                    .on_click({
16197                        let message = diagnostic.message.clone();
16198                        move |_click, _, cx| {
16199                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16200                        }
16201                    })
16202                    .tooltip(Tooltip::text("Copy diagnostic message")),
16203            )
16204        };
16205
16206        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16207            AvailableSpace::min_size(),
16208            cx.window,
16209            cx.app,
16210        );
16211
16212        h_flex()
16213            .id(cx.block_id)
16214            .group(group_id.clone())
16215            .relative()
16216            .size_full()
16217            .block_mouse_down()
16218            .pl(cx.gutter_dimensions.width)
16219            .w(cx.max_width - cx.gutter_dimensions.full_width())
16220            .child(
16221                div()
16222                    .flex()
16223                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16224                    .flex_shrink(),
16225            )
16226            .child(buttons(&diagnostic))
16227            .child(div().flex().flex_shrink_0().child(
16228                StyledText::new(text_without_backticks.clone()).with_highlights(
16229                    &text_style,
16230                    code_ranges.iter().map(|range| {
16231                        (
16232                            range.clone(),
16233                            HighlightStyle {
16234                                font_weight: Some(FontWeight::BOLD),
16235                                ..Default::default()
16236                            },
16237                        )
16238                    }),
16239                ),
16240            ))
16241            .into_any_element()
16242    })
16243}
16244
16245fn inline_completion_edit_text(
16246    current_snapshot: &BufferSnapshot,
16247    edits: &[(Range<Anchor>, String)],
16248    edit_preview: &EditPreview,
16249    include_deletions: bool,
16250    cx: &App,
16251) -> HighlightedText {
16252    let edits = edits
16253        .iter()
16254        .map(|(anchor, text)| {
16255            (
16256                anchor.start.text_anchor..anchor.end.text_anchor,
16257                text.clone(),
16258            )
16259        })
16260        .collect::<Vec<_>>();
16261
16262    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16263}
16264
16265pub fn highlight_diagnostic_message(
16266    diagnostic: &Diagnostic,
16267    mut max_message_rows: Option<u8>,
16268) -> (SharedString, Vec<Range<usize>>) {
16269    let mut text_without_backticks = String::new();
16270    let mut code_ranges = Vec::new();
16271
16272    if let Some(source) = &diagnostic.source {
16273        text_without_backticks.push_str(source);
16274        code_ranges.push(0..source.len());
16275        text_without_backticks.push_str(": ");
16276    }
16277
16278    let mut prev_offset = 0;
16279    let mut in_code_block = false;
16280    let has_row_limit = max_message_rows.is_some();
16281    let mut newline_indices = diagnostic
16282        .message
16283        .match_indices('\n')
16284        .filter(|_| has_row_limit)
16285        .map(|(ix, _)| ix)
16286        .fuse()
16287        .peekable();
16288
16289    for (quote_ix, _) in diagnostic
16290        .message
16291        .match_indices('`')
16292        .chain([(diagnostic.message.len(), "")])
16293    {
16294        let mut first_newline_ix = None;
16295        let mut last_newline_ix = None;
16296        while let Some(newline_ix) = newline_indices.peek() {
16297            if *newline_ix < quote_ix {
16298                if first_newline_ix.is_none() {
16299                    first_newline_ix = Some(*newline_ix);
16300                }
16301                last_newline_ix = Some(*newline_ix);
16302
16303                if let Some(rows_left) = &mut max_message_rows {
16304                    if *rows_left == 0 {
16305                        break;
16306                    } else {
16307                        *rows_left -= 1;
16308                    }
16309                }
16310                let _ = newline_indices.next();
16311            } else {
16312                break;
16313            }
16314        }
16315        let prev_len = text_without_backticks.len();
16316        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16317        text_without_backticks.push_str(new_text);
16318        if in_code_block {
16319            code_ranges.push(prev_len..text_without_backticks.len());
16320        }
16321        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16322        in_code_block = !in_code_block;
16323        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16324            text_without_backticks.push_str("...");
16325            break;
16326        }
16327    }
16328
16329    (text_without_backticks.into(), code_ranges)
16330}
16331
16332fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16333    match severity {
16334        DiagnosticSeverity::ERROR => colors.error,
16335        DiagnosticSeverity::WARNING => colors.warning,
16336        DiagnosticSeverity::INFORMATION => colors.info,
16337        DiagnosticSeverity::HINT => colors.info,
16338        _ => colors.ignored,
16339    }
16340}
16341
16342pub fn styled_runs_for_code_label<'a>(
16343    label: &'a CodeLabel,
16344    syntax_theme: &'a theme::SyntaxTheme,
16345) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16346    let fade_out = HighlightStyle {
16347        fade_out: Some(0.35),
16348        ..Default::default()
16349    };
16350
16351    let mut prev_end = label.filter_range.end;
16352    label
16353        .runs
16354        .iter()
16355        .enumerate()
16356        .flat_map(move |(ix, (range, highlight_id))| {
16357            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16358                style
16359            } else {
16360                return Default::default();
16361            };
16362            let mut muted_style = style;
16363            muted_style.highlight(fade_out);
16364
16365            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16366            if range.start >= label.filter_range.end {
16367                if range.start > prev_end {
16368                    runs.push((prev_end..range.start, fade_out));
16369                }
16370                runs.push((range.clone(), muted_style));
16371            } else if range.end <= label.filter_range.end {
16372                runs.push((range.clone(), style));
16373            } else {
16374                runs.push((range.start..label.filter_range.end, style));
16375                runs.push((label.filter_range.end..range.end, muted_style));
16376            }
16377            prev_end = cmp::max(prev_end, range.end);
16378
16379            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16380                runs.push((prev_end..label.text.len(), fade_out));
16381            }
16382
16383            runs
16384        })
16385}
16386
16387pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16388    let mut prev_index = 0;
16389    let mut prev_codepoint: Option<char> = None;
16390    text.char_indices()
16391        .chain([(text.len(), '\0')])
16392        .filter_map(move |(index, codepoint)| {
16393            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16394            let is_boundary = index == text.len()
16395                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16396                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16397            if is_boundary {
16398                let chunk = &text[prev_index..index];
16399                prev_index = index;
16400                Some(chunk)
16401            } else {
16402                None
16403            }
16404        })
16405}
16406
16407pub trait RangeToAnchorExt: Sized {
16408    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16409
16410    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16411        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16412        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16413    }
16414}
16415
16416impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16417    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16418        let start_offset = self.start.to_offset(snapshot);
16419        let end_offset = self.end.to_offset(snapshot);
16420        if start_offset == end_offset {
16421            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16422        } else {
16423            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16424        }
16425    }
16426}
16427
16428pub trait RowExt {
16429    fn as_f32(&self) -> f32;
16430
16431    fn next_row(&self) -> Self;
16432
16433    fn previous_row(&self) -> Self;
16434
16435    fn minus(&self, other: Self) -> u32;
16436}
16437
16438impl RowExt for DisplayRow {
16439    fn as_f32(&self) -> f32 {
16440        self.0 as f32
16441    }
16442
16443    fn next_row(&self) -> Self {
16444        Self(self.0 + 1)
16445    }
16446
16447    fn previous_row(&self) -> Self {
16448        Self(self.0.saturating_sub(1))
16449    }
16450
16451    fn minus(&self, other: Self) -> u32 {
16452        self.0 - other.0
16453    }
16454}
16455
16456impl RowExt for MultiBufferRow {
16457    fn as_f32(&self) -> f32 {
16458        self.0 as f32
16459    }
16460
16461    fn next_row(&self) -> Self {
16462        Self(self.0 + 1)
16463    }
16464
16465    fn previous_row(&self) -> Self {
16466        Self(self.0.saturating_sub(1))
16467    }
16468
16469    fn minus(&self, other: Self) -> u32 {
16470        self.0 - other.0
16471    }
16472}
16473
16474trait RowRangeExt {
16475    type Row;
16476
16477    fn len(&self) -> usize;
16478
16479    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16480}
16481
16482impl RowRangeExt for Range<MultiBufferRow> {
16483    type Row = MultiBufferRow;
16484
16485    fn len(&self) -> usize {
16486        (self.end.0 - self.start.0) as usize
16487    }
16488
16489    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16490        (self.start.0..self.end.0).map(MultiBufferRow)
16491    }
16492}
16493
16494impl RowRangeExt for Range<DisplayRow> {
16495    type Row = DisplayRow;
16496
16497    fn len(&self) -> usize {
16498        (self.end.0 - self.start.0) as usize
16499    }
16500
16501    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16502        (self.start.0..self.end.0).map(DisplayRow)
16503    }
16504}
16505
16506/// If select range has more than one line, we
16507/// just point the cursor to range.start.
16508fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16509    if range.start.row == range.end.row {
16510        range
16511    } else {
16512        range.start..range.start
16513    }
16514}
16515pub struct KillRing(ClipboardItem);
16516impl Global for KillRing {}
16517
16518const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16519
16520fn all_edits_insertions_or_deletions(
16521    edits: &Vec<(Range<Anchor>, String)>,
16522    snapshot: &MultiBufferSnapshot,
16523) -> bool {
16524    let mut all_insertions = true;
16525    let mut all_deletions = true;
16526
16527    for (range, new_text) in edits.iter() {
16528        let range_is_empty = range.to_offset(&snapshot).is_empty();
16529        let text_is_empty = new_text.is_empty();
16530
16531        if range_is_empty != text_is_empty {
16532            if range_is_empty {
16533                all_deletions = false;
16534            } else {
16535                all_insertions = false;
16536            }
16537        } else {
16538            return false;
16539        }
16540
16541        if !all_insertions && !all_deletions {
16542            return false;
16543        }
16544    }
16545    all_insertions || all_deletions
16546}