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, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  101    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    inlay_hint_cache: InlayHintCache,
  697    next_inlay_id: usize,
  698    _subscriptions: Vec<Subscription>,
  699    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  700    gutter_dimensions: GutterDimensions,
  701    style: Option<EditorStyle>,
  702    text_style_refinement: Option<TextStyleRefinement>,
  703    next_editor_action_id: EditorActionId,
  704    editor_actions:
  705        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  706    use_autoclose: bool,
  707    use_auto_surround: bool,
  708    auto_replace_emoji_shortcode: bool,
  709    show_git_blame_gutter: bool,
  710    show_git_blame_inline: bool,
  711    show_git_blame_inline_delay_task: Option<Task<()>>,
  712    git_blame_inline_enabled: bool,
  713    serialize_dirty_buffers: bool,
  714    show_selection_menu: Option<bool>,
  715    blame: Option<Entity<GitBlame>>,
  716    blame_subscription: Option<Subscription>,
  717    custom_context_menu: Option<
  718        Box<
  719            dyn 'static
  720                + Fn(
  721                    &mut Self,
  722                    DisplayPoint,
  723                    &mut Window,
  724                    &mut Context<Self>,
  725                ) -> Option<Entity<ui::ContextMenu>>,
  726        >,
  727    >,
  728    last_bounds: Option<Bounds<Pixels>>,
  729    last_position_map: Option<Rc<PositionMap>>,
  730    expect_bounds_change: Option<Bounds<Pixels>>,
  731    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  732    tasks_update_task: Option<Task<()>>,
  733    in_project_search: bool,
  734    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  735    breadcrumb_header: Option<String>,
  736    focused_block: Option<FocusedBlock>,
  737    next_scroll_position: NextScrollCursorCenterTopBottom,
  738    addons: HashMap<TypeId, Box<dyn Addon>>,
  739    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  740    selection_mark_mode: bool,
  741    toggle_fold_multiple_buffers: Task<()>,
  742    _scroll_cursor_center_top_bottom_task: Task<()>,
  743}
  744
  745#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  746enum NextScrollCursorCenterTopBottom {
  747    #[default]
  748    Center,
  749    Top,
  750    Bottom,
  751}
  752
  753impl NextScrollCursorCenterTopBottom {
  754    fn next(&self) -> Self {
  755        match self {
  756            Self::Center => Self::Top,
  757            Self::Top => Self::Bottom,
  758            Self::Bottom => Self::Center,
  759        }
  760    }
  761}
  762
  763#[derive(Clone)]
  764pub struct EditorSnapshot {
  765    pub mode: EditorMode,
  766    show_gutter: bool,
  767    show_line_numbers: Option<bool>,
  768    show_git_diff_gutter: Option<bool>,
  769    show_code_actions: Option<bool>,
  770    show_runnables: Option<bool>,
  771    git_blame_gutter_max_author_length: Option<usize>,
  772    pub display_snapshot: DisplaySnapshot,
  773    pub placeholder_text: Option<Arc<str>>,
  774    is_focused: bool,
  775    scroll_anchor: ScrollAnchor,
  776    ongoing_scroll: OngoingScroll,
  777    current_line_highlight: CurrentLineHighlight,
  778    gutter_hovered: bool,
  779}
  780
  781const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  782
  783#[derive(Default, Debug, Clone, Copy)]
  784pub struct GutterDimensions {
  785    pub left_padding: Pixels,
  786    pub right_padding: Pixels,
  787    pub width: Pixels,
  788    pub margin: Pixels,
  789    pub git_blame_entries_width: Option<Pixels>,
  790}
  791
  792impl GutterDimensions {
  793    /// The full width of the space taken up by the gutter.
  794    pub fn full_width(&self) -> Pixels {
  795        self.margin + self.width
  796    }
  797
  798    /// The width of the space reserved for the fold indicators,
  799    /// use alongside 'justify_end' and `gutter_width` to
  800    /// right align content with the line numbers
  801    pub fn fold_area_width(&self) -> Pixels {
  802        self.margin + self.right_padding
  803    }
  804}
  805
  806#[derive(Debug)]
  807pub struct RemoteSelection {
  808    pub replica_id: ReplicaId,
  809    pub selection: Selection<Anchor>,
  810    pub cursor_shape: CursorShape,
  811    pub peer_id: PeerId,
  812    pub line_mode: bool,
  813    pub participant_index: Option<ParticipantIndex>,
  814    pub user_name: Option<SharedString>,
  815}
  816
  817#[derive(Clone, Debug)]
  818struct SelectionHistoryEntry {
  819    selections: Arc<[Selection<Anchor>]>,
  820    select_next_state: Option<SelectNextState>,
  821    select_prev_state: Option<SelectNextState>,
  822    add_selections_state: Option<AddSelectionsState>,
  823}
  824
  825enum SelectionHistoryMode {
  826    Normal,
  827    Undoing,
  828    Redoing,
  829}
  830
  831#[derive(Clone, PartialEq, Eq, Hash)]
  832struct HoveredCursor {
  833    replica_id: u16,
  834    selection_id: usize,
  835}
  836
  837impl Default for SelectionHistoryMode {
  838    fn default() -> Self {
  839        Self::Normal
  840    }
  841}
  842
  843#[derive(Default)]
  844struct SelectionHistory {
  845    #[allow(clippy::type_complexity)]
  846    selections_by_transaction:
  847        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  848    mode: SelectionHistoryMode,
  849    undo_stack: VecDeque<SelectionHistoryEntry>,
  850    redo_stack: VecDeque<SelectionHistoryEntry>,
  851}
  852
  853impl SelectionHistory {
  854    fn insert_transaction(
  855        &mut self,
  856        transaction_id: TransactionId,
  857        selections: Arc<[Selection<Anchor>]>,
  858    ) {
  859        self.selections_by_transaction
  860            .insert(transaction_id, (selections, None));
  861    }
  862
  863    #[allow(clippy::type_complexity)]
  864    fn transaction(
  865        &self,
  866        transaction_id: TransactionId,
  867    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  868        self.selections_by_transaction.get(&transaction_id)
  869    }
  870
  871    #[allow(clippy::type_complexity)]
  872    fn transaction_mut(
  873        &mut self,
  874        transaction_id: TransactionId,
  875    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  876        self.selections_by_transaction.get_mut(&transaction_id)
  877    }
  878
  879    fn push(&mut self, entry: SelectionHistoryEntry) {
  880        if !entry.selections.is_empty() {
  881            match self.mode {
  882                SelectionHistoryMode::Normal => {
  883                    self.push_undo(entry);
  884                    self.redo_stack.clear();
  885                }
  886                SelectionHistoryMode::Undoing => self.push_redo(entry),
  887                SelectionHistoryMode::Redoing => self.push_undo(entry),
  888            }
  889        }
  890    }
  891
  892    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  893        if self
  894            .undo_stack
  895            .back()
  896            .map_or(true, |e| e.selections != entry.selections)
  897        {
  898            self.undo_stack.push_back(entry);
  899            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  900                self.undo_stack.pop_front();
  901            }
  902        }
  903    }
  904
  905    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  906        if self
  907            .redo_stack
  908            .back()
  909            .map_or(true, |e| e.selections != entry.selections)
  910        {
  911            self.redo_stack.push_back(entry);
  912            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  913                self.redo_stack.pop_front();
  914            }
  915        }
  916    }
  917}
  918
  919struct RowHighlight {
  920    index: usize,
  921    range: Range<Anchor>,
  922    color: Hsla,
  923    should_autoscroll: bool,
  924}
  925
  926#[derive(Clone, Debug)]
  927struct AddSelectionsState {
  928    above: bool,
  929    stack: Vec<usize>,
  930}
  931
  932#[derive(Clone)]
  933struct SelectNextState {
  934    query: AhoCorasick,
  935    wordwise: bool,
  936    done: bool,
  937}
  938
  939impl std::fmt::Debug for SelectNextState {
  940    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  941        f.debug_struct(std::any::type_name::<Self>())
  942            .field("wordwise", &self.wordwise)
  943            .field("done", &self.done)
  944            .finish()
  945    }
  946}
  947
  948#[derive(Debug)]
  949struct AutocloseRegion {
  950    selection_id: usize,
  951    range: Range<Anchor>,
  952    pair: BracketPair,
  953}
  954
  955#[derive(Debug)]
  956struct SnippetState {
  957    ranges: Vec<Vec<Range<Anchor>>>,
  958    active_index: usize,
  959    choices: Vec<Option<Vec<String>>>,
  960}
  961
  962#[doc(hidden)]
  963pub struct RenameState {
  964    pub range: Range<Anchor>,
  965    pub old_name: Arc<str>,
  966    pub editor: Entity<Editor>,
  967    block_id: CustomBlockId,
  968}
  969
  970struct InvalidationStack<T>(Vec<T>);
  971
  972struct RegisteredInlineCompletionProvider {
  973    provider: Arc<dyn InlineCompletionProviderHandle>,
  974    _subscription: Subscription,
  975}
  976
  977#[derive(Debug)]
  978struct ActiveDiagnosticGroup {
  979    primary_range: Range<Anchor>,
  980    primary_message: String,
  981    group_id: usize,
  982    blocks: HashMap<CustomBlockId, Diagnostic>,
  983    is_valid: bool,
  984}
  985
  986#[derive(Serialize, Deserialize, Clone, Debug)]
  987pub struct ClipboardSelection {
  988    pub len: usize,
  989    pub is_entire_line: bool,
  990    pub first_line_indent: u32,
  991}
  992
  993#[derive(Debug)]
  994pub(crate) struct NavigationData {
  995    cursor_anchor: Anchor,
  996    cursor_position: Point,
  997    scroll_anchor: ScrollAnchor,
  998    scroll_top_row: u32,
  999}
 1000
 1001#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1002pub enum GotoDefinitionKind {
 1003    Symbol,
 1004    Declaration,
 1005    Type,
 1006    Implementation,
 1007}
 1008
 1009#[derive(Debug, Clone)]
 1010enum InlayHintRefreshReason {
 1011    Toggle(bool),
 1012    SettingsChange(InlayHintSettings),
 1013    NewLinesShown,
 1014    BufferEdited(HashSet<Arc<Language>>),
 1015    RefreshRequested,
 1016    ExcerptsRemoved(Vec<ExcerptId>),
 1017}
 1018
 1019impl InlayHintRefreshReason {
 1020    fn description(&self) -> &'static str {
 1021        match self {
 1022            Self::Toggle(_) => "toggle",
 1023            Self::SettingsChange(_) => "settings change",
 1024            Self::NewLinesShown => "new lines shown",
 1025            Self::BufferEdited(_) => "buffer edited",
 1026            Self::RefreshRequested => "refresh requested",
 1027            Self::ExcerptsRemoved(_) => "excerpts removed",
 1028        }
 1029    }
 1030}
 1031
 1032pub enum FormatTarget {
 1033    Buffers,
 1034    Ranges(Vec<Range<MultiBufferPoint>>),
 1035}
 1036
 1037pub(crate) struct FocusedBlock {
 1038    id: BlockId,
 1039    focus_handle: WeakFocusHandle,
 1040}
 1041
 1042#[derive(Clone)]
 1043enum JumpData {
 1044    MultiBufferRow {
 1045        row: MultiBufferRow,
 1046        line_offset_from_top: u32,
 1047    },
 1048    MultiBufferPoint {
 1049        excerpt_id: ExcerptId,
 1050        position: Point,
 1051        anchor: text::Anchor,
 1052        line_offset_from_top: u32,
 1053    },
 1054}
 1055
 1056pub enum MultibufferSelectionMode {
 1057    First,
 1058    All,
 1059}
 1060
 1061impl Editor {
 1062    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1063        let buffer = cx.new(|cx| Buffer::local("", cx));
 1064        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1065        Self::new(
 1066            EditorMode::SingleLine { auto_width: false },
 1067            buffer,
 1068            None,
 1069            false,
 1070            window,
 1071            cx,
 1072        )
 1073    }
 1074
 1075    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1076        let buffer = cx.new(|cx| Buffer::local("", cx));
 1077        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1078        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1079    }
 1080
 1081    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1082        let buffer = cx.new(|cx| Buffer::local("", cx));
 1083        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1084        Self::new(
 1085            EditorMode::SingleLine { auto_width: true },
 1086            buffer,
 1087            None,
 1088            false,
 1089            window,
 1090            cx,
 1091        )
 1092    }
 1093
 1094    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1095        let buffer = cx.new(|cx| Buffer::local("", cx));
 1096        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1097        Self::new(
 1098            EditorMode::AutoHeight { max_lines },
 1099            buffer,
 1100            None,
 1101            false,
 1102            window,
 1103            cx,
 1104        )
 1105    }
 1106
 1107    pub fn for_buffer(
 1108        buffer: Entity<Buffer>,
 1109        project: Option<Entity<Project>>,
 1110        window: &mut Window,
 1111        cx: &mut Context<Self>,
 1112    ) -> Self {
 1113        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1114        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1115    }
 1116
 1117    pub fn for_multibuffer(
 1118        buffer: Entity<MultiBuffer>,
 1119        project: Option<Entity<Project>>,
 1120        show_excerpt_controls: bool,
 1121        window: &mut Window,
 1122        cx: &mut Context<Self>,
 1123    ) -> Self {
 1124        Self::new(
 1125            EditorMode::Full,
 1126            buffer,
 1127            project,
 1128            show_excerpt_controls,
 1129            window,
 1130            cx,
 1131        )
 1132    }
 1133
 1134    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1135        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1136        let mut clone = Self::new(
 1137            self.mode,
 1138            self.buffer.clone(),
 1139            self.project.clone(),
 1140            show_excerpt_controls,
 1141            window,
 1142            cx,
 1143        );
 1144        self.display_map.update(cx, |display_map, cx| {
 1145            let snapshot = display_map.snapshot(cx);
 1146            clone.display_map.update(cx, |display_map, cx| {
 1147                display_map.set_state(&snapshot, cx);
 1148            });
 1149        });
 1150        clone.selections.clone_state(&self.selections);
 1151        clone.scroll_manager.clone_state(&self.scroll_manager);
 1152        clone.searchable = self.searchable;
 1153        clone
 1154    }
 1155
 1156    pub fn new(
 1157        mode: EditorMode,
 1158        buffer: Entity<MultiBuffer>,
 1159        project: Option<Entity<Project>>,
 1160        show_excerpt_controls: bool,
 1161        window: &mut Window,
 1162        cx: &mut Context<Self>,
 1163    ) -> Self {
 1164        let style = window.text_style();
 1165        let font_size = style.font_size.to_pixels(window.rem_size());
 1166        let editor = cx.entity().downgrade();
 1167        let fold_placeholder = FoldPlaceholder {
 1168            constrain_width: true,
 1169            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1170                let editor = editor.clone();
 1171                div()
 1172                    .id(fold_id)
 1173                    .bg(cx.theme().colors().ghost_element_background)
 1174                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1175                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1176                    .rounded_sm()
 1177                    .size_full()
 1178                    .cursor_pointer()
 1179                    .child("")
 1180                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1181                    .on_click(move |_, _window, cx| {
 1182                        editor
 1183                            .update(cx, |editor, cx| {
 1184                                editor.unfold_ranges(
 1185                                    &[fold_range.start..fold_range.end],
 1186                                    true,
 1187                                    false,
 1188                                    cx,
 1189                                );
 1190                                cx.stop_propagation();
 1191                            })
 1192                            .ok();
 1193                    })
 1194                    .into_any()
 1195            }),
 1196            merge_adjacent: true,
 1197            ..Default::default()
 1198        };
 1199        let display_map = cx.new(|cx| {
 1200            DisplayMap::new(
 1201                buffer.clone(),
 1202                style.font(),
 1203                font_size,
 1204                None,
 1205                show_excerpt_controls,
 1206                FILE_HEADER_HEIGHT,
 1207                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1208                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1209                fold_placeholder,
 1210                cx,
 1211            )
 1212        });
 1213
 1214        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1215
 1216        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1217
 1218        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1219            .then(|| language_settings::SoftWrap::None);
 1220
 1221        let mut project_subscriptions = Vec::new();
 1222        if mode == EditorMode::Full {
 1223            if let Some(project) = project.as_ref() {
 1224                if buffer.read(cx).is_singleton() {
 1225                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1226                        cx.emit(EditorEvent::TitleChanged);
 1227                    }));
 1228                }
 1229                project_subscriptions.push(cx.subscribe_in(
 1230                    project,
 1231                    window,
 1232                    |editor, _, event, window, cx| {
 1233                        if let project::Event::RefreshInlayHints = event {
 1234                            editor
 1235                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1236                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1237                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1238                                let focus_handle = editor.focus_handle(cx);
 1239                                if focus_handle.is_focused(window) {
 1240                                    let snapshot = buffer.read(cx).snapshot();
 1241                                    for (range, snippet) in snippet_edits {
 1242                                        let editor_range =
 1243                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1244                                        editor
 1245                                            .insert_snippet(
 1246                                                &[editor_range],
 1247                                                snippet.clone(),
 1248                                                window,
 1249                                                cx,
 1250                                            )
 1251                                            .ok();
 1252                                    }
 1253                                }
 1254                            }
 1255                        }
 1256                    },
 1257                ));
 1258                if let Some(task_inventory) = project
 1259                    .read(cx)
 1260                    .task_store()
 1261                    .read(cx)
 1262                    .task_inventory()
 1263                    .cloned()
 1264                {
 1265                    project_subscriptions.push(cx.observe_in(
 1266                        &task_inventory,
 1267                        window,
 1268                        |editor, _, window, cx| {
 1269                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1270                        },
 1271                    ));
 1272                }
 1273            }
 1274        }
 1275
 1276        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1277
 1278        let inlay_hint_settings =
 1279            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1280        let focus_handle = cx.focus_handle();
 1281        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1282            .detach();
 1283        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1284            .detach();
 1285        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1286            .detach();
 1287        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1288            .detach();
 1289
 1290        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1291            Some(false)
 1292        } else {
 1293            None
 1294        };
 1295
 1296        let mut code_action_providers = Vec::new();
 1297        if let Some(project) = project.clone() {
 1298            get_uncommitted_changes_for_buffer(
 1299                &project,
 1300                buffer.read(cx).all_buffers(),
 1301                buffer.clone(),
 1302                cx,
 1303            );
 1304            code_action_providers.push(Rc::new(project) as Rc<_>);
 1305        }
 1306
 1307        let mut this = Self {
 1308            focus_handle,
 1309            show_cursor_when_unfocused: false,
 1310            last_focused_descendant: None,
 1311            buffer: buffer.clone(),
 1312            display_map: display_map.clone(),
 1313            selections,
 1314            scroll_manager: ScrollManager::new(cx),
 1315            columnar_selection_tail: None,
 1316            add_selections_state: None,
 1317            select_next_state: None,
 1318            select_prev_state: None,
 1319            selection_history: Default::default(),
 1320            autoclose_regions: Default::default(),
 1321            snippet_stack: Default::default(),
 1322            select_larger_syntax_node_stack: Vec::new(),
 1323            ime_transaction: Default::default(),
 1324            active_diagnostics: None,
 1325            soft_wrap_mode_override,
 1326            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1327            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1328            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1329            project,
 1330            blink_manager: blink_manager.clone(),
 1331            show_local_selections: true,
 1332            show_scrollbars: true,
 1333            mode,
 1334            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1335            show_gutter: mode == EditorMode::Full,
 1336            show_line_numbers: None,
 1337            use_relative_line_numbers: None,
 1338            show_git_diff_gutter: None,
 1339            show_code_actions: None,
 1340            show_runnables: None,
 1341            show_wrap_guides: None,
 1342            show_indent_guides,
 1343            placeholder_text: None,
 1344            highlight_order: 0,
 1345            highlighted_rows: HashMap::default(),
 1346            background_highlights: Default::default(),
 1347            gutter_highlights: TreeMap::default(),
 1348            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1349            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1350            nav_history: None,
 1351            context_menu: RefCell::new(None),
 1352            mouse_context_menu: None,
 1353            completion_tasks: Default::default(),
 1354            signature_help_state: SignatureHelpState::default(),
 1355            auto_signature_help: None,
 1356            find_all_references_task_sources: Vec::new(),
 1357            next_completion_id: 0,
 1358            next_inlay_id: 0,
 1359            code_action_providers,
 1360            available_code_actions: Default::default(),
 1361            code_actions_task: Default::default(),
 1362            document_highlights_task: Default::default(),
 1363            linked_editing_range_task: Default::default(),
 1364            pending_rename: Default::default(),
 1365            searchable: true,
 1366            cursor_shape: EditorSettings::get_global(cx)
 1367                .cursor_shape
 1368                .unwrap_or_default(),
 1369            current_line_highlight: None,
 1370            autoindent_mode: Some(AutoindentMode::EachLine),
 1371            collapse_matches: false,
 1372            workspace: None,
 1373            input_enabled: true,
 1374            use_modal_editing: mode == EditorMode::Full,
 1375            read_only: false,
 1376            use_autoclose: true,
 1377            use_auto_surround: true,
 1378            auto_replace_emoji_shortcode: false,
 1379            leader_peer_id: None,
 1380            remote_id: None,
 1381            hover_state: Default::default(),
 1382            pending_mouse_down: None,
 1383            hovered_link_state: Default::default(),
 1384            inline_completion_provider: None,
 1385            active_inline_completion: None,
 1386            stale_inline_completion_in_menu: None,
 1387            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1388
 1389            gutter_hovered: false,
 1390            pixel_position_of_newest_cursor: None,
 1391            last_bounds: None,
 1392            last_position_map: None,
 1393            expect_bounds_change: None,
 1394            gutter_dimensions: GutterDimensions::default(),
 1395            style: None,
 1396            show_cursor_names: false,
 1397            hovered_cursors: Default::default(),
 1398            next_editor_action_id: EditorActionId::default(),
 1399            editor_actions: Rc::default(),
 1400            show_inline_completions_override: None,
 1401            show_inline_completions: true,
 1402            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1403            custom_context_menu: None,
 1404            show_git_blame_gutter: false,
 1405            show_git_blame_inline: false,
 1406            show_selection_menu: None,
 1407            show_git_blame_inline_delay_task: None,
 1408            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1409            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1410                .session
 1411                .restore_unsaved_buffers,
 1412            blame: None,
 1413            blame_subscription: None,
 1414            tasks: Default::default(),
 1415            _subscriptions: vec![
 1416                cx.observe(&buffer, Self::on_buffer_changed),
 1417                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1418                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1419                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1420                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1421                cx.observe_window_activation(window, |editor, window, cx| {
 1422                    let active = window.is_window_active();
 1423                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1424                        if active {
 1425                            blink_manager.enable(cx);
 1426                        } else {
 1427                            blink_manager.disable(cx);
 1428                        }
 1429                    });
 1430                }),
 1431            ],
 1432            tasks_update_task: None,
 1433            linked_edit_ranges: Default::default(),
 1434            in_project_search: false,
 1435            previous_search_ranges: None,
 1436            breadcrumb_header: None,
 1437            focused_block: None,
 1438            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1439            addons: HashMap::default(),
 1440            registered_buffers: HashMap::default(),
 1441            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1442            selection_mark_mode: false,
 1443            toggle_fold_multiple_buffers: Task::ready(()),
 1444            text_style_refinement: None,
 1445        };
 1446        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1447        this._subscriptions.extend(project_subscriptions);
 1448
 1449        this.end_selection(window, cx);
 1450        this.scroll_manager.show_scrollbar(window, cx);
 1451
 1452        if mode == EditorMode::Full {
 1453            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1454            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1455
 1456            if this.git_blame_inline_enabled {
 1457                this.git_blame_inline_enabled = true;
 1458                this.start_git_blame_inline(false, window, cx);
 1459            }
 1460
 1461            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1462                if let Some(project) = this.project.as_ref() {
 1463                    let lsp_store = project.read(cx).lsp_store();
 1464                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1465                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1466                    });
 1467                    this.registered_buffers
 1468                        .insert(buffer.read(cx).remote_id(), handle);
 1469                }
 1470            }
 1471        }
 1472
 1473        this.report_editor_event("Editor Opened", None, cx);
 1474        this
 1475    }
 1476
 1477    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1478        self.mouse_context_menu
 1479            .as_ref()
 1480            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1481    }
 1482
 1483    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1484        let mut key_context = KeyContext::new_with_defaults();
 1485        key_context.add("Editor");
 1486        let mode = match self.mode {
 1487            EditorMode::SingleLine { .. } => "single_line",
 1488            EditorMode::AutoHeight { .. } => "auto_height",
 1489            EditorMode::Full => "full",
 1490        };
 1491
 1492        if EditorSettings::jupyter_enabled(cx) {
 1493            key_context.add("jupyter");
 1494        }
 1495
 1496        key_context.set("mode", mode);
 1497        if self.pending_rename.is_some() {
 1498            key_context.add("renaming");
 1499        }
 1500        match self.context_menu.borrow().as_ref() {
 1501            Some(CodeContextMenu::Completions(_)) => {
 1502                key_context.add("menu");
 1503                key_context.add("showing_completions");
 1504            }
 1505            Some(CodeContextMenu::CodeActions(_)) => {
 1506                key_context.add("menu");
 1507                key_context.add("showing_code_actions")
 1508            }
 1509            None => {}
 1510        }
 1511
 1512        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1513        if !self.focus_handle(cx).contains_focused(window, cx)
 1514            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1515        {
 1516            for addon in self.addons.values() {
 1517                addon.extend_key_context(&mut key_context, cx)
 1518            }
 1519        }
 1520
 1521        if let Some(extension) = self
 1522            .buffer
 1523            .read(cx)
 1524            .as_singleton()
 1525            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1526        {
 1527            key_context.set("extension", extension.to_string());
 1528        }
 1529
 1530        if self.has_active_inline_completion() {
 1531            key_context.add("copilot_suggestion");
 1532            key_context.add("inline_completion");
 1533        }
 1534
 1535        if self.selection_mark_mode {
 1536            key_context.add("selection_mode");
 1537        }
 1538
 1539        key_context
 1540    }
 1541
 1542    pub fn new_file(
 1543        workspace: &mut Workspace,
 1544        _: &workspace::NewFile,
 1545        window: &mut Window,
 1546        cx: &mut Context<Workspace>,
 1547    ) {
 1548        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1549            "Failed to create buffer",
 1550            window,
 1551            cx,
 1552            |e, _, _| match e.error_code() {
 1553                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1554                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1555                e.error_tag("required").unwrap_or("the latest version")
 1556            )),
 1557                _ => None,
 1558            },
 1559        );
 1560    }
 1561
 1562    pub fn new_in_workspace(
 1563        workspace: &mut Workspace,
 1564        window: &mut Window,
 1565        cx: &mut Context<Workspace>,
 1566    ) -> Task<Result<Entity<Editor>>> {
 1567        let project = workspace.project().clone();
 1568        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1569
 1570        cx.spawn_in(window, |workspace, mut cx| async move {
 1571            let buffer = create.await?;
 1572            workspace.update_in(&mut cx, |workspace, window, cx| {
 1573                let editor =
 1574                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1575                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1576                editor
 1577            })
 1578        })
 1579    }
 1580
 1581    fn new_file_vertical(
 1582        workspace: &mut Workspace,
 1583        _: &workspace::NewFileSplitVertical,
 1584        window: &mut Window,
 1585        cx: &mut Context<Workspace>,
 1586    ) {
 1587        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1588    }
 1589
 1590    fn new_file_horizontal(
 1591        workspace: &mut Workspace,
 1592        _: &workspace::NewFileSplitHorizontal,
 1593        window: &mut Window,
 1594        cx: &mut Context<Workspace>,
 1595    ) {
 1596        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1597    }
 1598
 1599    fn new_file_in_direction(
 1600        workspace: &mut Workspace,
 1601        direction: SplitDirection,
 1602        window: &mut Window,
 1603        cx: &mut Context<Workspace>,
 1604    ) {
 1605        let project = workspace.project().clone();
 1606        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1607
 1608        cx.spawn_in(window, |workspace, mut cx| async move {
 1609            let buffer = create.await?;
 1610            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1611                workspace.split_item(
 1612                    direction,
 1613                    Box::new(
 1614                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1615                    ),
 1616                    window,
 1617                    cx,
 1618                )
 1619            })?;
 1620            anyhow::Ok(())
 1621        })
 1622        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1623            match e.error_code() {
 1624                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1625                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1626                e.error_tag("required").unwrap_or("the latest version")
 1627            )),
 1628                _ => None,
 1629            }
 1630        });
 1631    }
 1632
 1633    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1634        self.leader_peer_id
 1635    }
 1636
 1637    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1638        &self.buffer
 1639    }
 1640
 1641    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1642        self.workspace.as_ref()?.0.upgrade()
 1643    }
 1644
 1645    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1646        self.buffer().read(cx).title(cx)
 1647    }
 1648
 1649    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1650        let git_blame_gutter_max_author_length = self
 1651            .render_git_blame_gutter(cx)
 1652            .then(|| {
 1653                if let Some(blame) = self.blame.as_ref() {
 1654                    let max_author_length =
 1655                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1656                    Some(max_author_length)
 1657                } else {
 1658                    None
 1659                }
 1660            })
 1661            .flatten();
 1662
 1663        EditorSnapshot {
 1664            mode: self.mode,
 1665            show_gutter: self.show_gutter,
 1666            show_line_numbers: self.show_line_numbers,
 1667            show_git_diff_gutter: self.show_git_diff_gutter,
 1668            show_code_actions: self.show_code_actions,
 1669            show_runnables: self.show_runnables,
 1670            git_blame_gutter_max_author_length,
 1671            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1672            scroll_anchor: self.scroll_manager.anchor(),
 1673            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1674            placeholder_text: self.placeholder_text.clone(),
 1675            is_focused: self.focus_handle.is_focused(window),
 1676            current_line_highlight: self
 1677                .current_line_highlight
 1678                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1679            gutter_hovered: self.gutter_hovered,
 1680        }
 1681    }
 1682
 1683    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1684        self.buffer.read(cx).language_at(point, cx)
 1685    }
 1686
 1687    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1688        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1689    }
 1690
 1691    pub fn active_excerpt(
 1692        &self,
 1693        cx: &App,
 1694    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1695        self.buffer
 1696            .read(cx)
 1697            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1698    }
 1699
 1700    pub fn mode(&self) -> EditorMode {
 1701        self.mode
 1702    }
 1703
 1704    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1705        self.collaboration_hub.as_deref()
 1706    }
 1707
 1708    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1709        self.collaboration_hub = Some(hub);
 1710    }
 1711
 1712    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1713        self.in_project_search = in_project_search;
 1714    }
 1715
 1716    pub fn set_custom_context_menu(
 1717        &mut self,
 1718        f: impl 'static
 1719            + Fn(
 1720                &mut Self,
 1721                DisplayPoint,
 1722                &mut Window,
 1723                &mut Context<Self>,
 1724            ) -> Option<Entity<ui::ContextMenu>>,
 1725    ) {
 1726        self.custom_context_menu = Some(Box::new(f))
 1727    }
 1728
 1729    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1730        self.completion_provider = provider;
 1731    }
 1732
 1733    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1734        self.semantics_provider.clone()
 1735    }
 1736
 1737    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1738        self.semantics_provider = provider;
 1739    }
 1740
 1741    pub fn set_inline_completion_provider<T>(
 1742        &mut self,
 1743        provider: Option<Entity<T>>,
 1744        window: &mut Window,
 1745        cx: &mut Context<Self>,
 1746    ) where
 1747        T: InlineCompletionProvider,
 1748    {
 1749        self.inline_completion_provider =
 1750            provider.map(|provider| RegisteredInlineCompletionProvider {
 1751                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1752                    if this.focus_handle.is_focused(window) {
 1753                        this.update_visible_inline_completion(window, cx);
 1754                    }
 1755                }),
 1756                provider: Arc::new(provider),
 1757            });
 1758        self.refresh_inline_completion(false, false, window, cx);
 1759    }
 1760
 1761    pub fn placeholder_text(&self) -> Option<&str> {
 1762        self.placeholder_text.as_deref()
 1763    }
 1764
 1765    pub fn set_placeholder_text(
 1766        &mut self,
 1767        placeholder_text: impl Into<Arc<str>>,
 1768        cx: &mut Context<Self>,
 1769    ) {
 1770        let placeholder_text = Some(placeholder_text.into());
 1771        if self.placeholder_text != placeholder_text {
 1772            self.placeholder_text = placeholder_text;
 1773            cx.notify();
 1774        }
 1775    }
 1776
 1777    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1778        self.cursor_shape = cursor_shape;
 1779
 1780        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1781        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1782
 1783        cx.notify();
 1784    }
 1785
 1786    pub fn set_current_line_highlight(
 1787        &mut self,
 1788        current_line_highlight: Option<CurrentLineHighlight>,
 1789    ) {
 1790        self.current_line_highlight = current_line_highlight;
 1791    }
 1792
 1793    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1794        self.collapse_matches = collapse_matches;
 1795    }
 1796
 1797    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1798        let buffers = self.buffer.read(cx).all_buffers();
 1799        let Some(lsp_store) = self.lsp_store(cx) else {
 1800            return;
 1801        };
 1802        lsp_store.update(cx, |lsp_store, cx| {
 1803            for buffer in buffers {
 1804                self.registered_buffers
 1805                    .entry(buffer.read(cx).remote_id())
 1806                    .or_insert_with(|| {
 1807                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1808                    });
 1809            }
 1810        })
 1811    }
 1812
 1813    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1814        if self.collapse_matches {
 1815            return range.start..range.start;
 1816        }
 1817        range.clone()
 1818    }
 1819
 1820    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1821        if self.display_map.read(cx).clip_at_line_ends != clip {
 1822            self.display_map
 1823                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1824        }
 1825    }
 1826
 1827    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1828        self.input_enabled = input_enabled;
 1829    }
 1830
 1831    pub fn set_show_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1832        self.show_inline_completions = enabled;
 1833        if !self.show_inline_completions {
 1834            self.take_active_inline_completion(cx);
 1835            cx.notify();
 1836        }
 1837    }
 1838
 1839    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1840        self.menu_inline_completions_policy = value;
 1841    }
 1842
 1843    pub fn set_autoindent(&mut self, autoindent: bool) {
 1844        if autoindent {
 1845            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1846        } else {
 1847            self.autoindent_mode = None;
 1848        }
 1849    }
 1850
 1851    pub fn read_only(&self, cx: &App) -> bool {
 1852        self.read_only || self.buffer.read(cx).read_only()
 1853    }
 1854
 1855    pub fn set_read_only(&mut self, read_only: bool) {
 1856        self.read_only = read_only;
 1857    }
 1858
 1859    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1860        self.use_autoclose = autoclose;
 1861    }
 1862
 1863    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1864        self.use_auto_surround = auto_surround;
 1865    }
 1866
 1867    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1868        self.auto_replace_emoji_shortcode = auto_replace;
 1869    }
 1870
 1871    pub fn toggle_inline_completions(
 1872        &mut self,
 1873        _: &ToggleInlineCompletions,
 1874        window: &mut Window,
 1875        cx: &mut Context<Self>,
 1876    ) {
 1877        if self.show_inline_completions_override.is_some() {
 1878            self.set_show_inline_completions(None, window, cx);
 1879        } else {
 1880            let cursor = self.selections.newest_anchor().head();
 1881            if let Some((buffer, cursor_buffer_position)) =
 1882                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1883            {
 1884                let show_inline_completions = !self.should_show_inline_completions_in_buffer(
 1885                    &buffer,
 1886                    cursor_buffer_position,
 1887                    cx,
 1888                );
 1889                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1890            }
 1891        }
 1892    }
 1893
 1894    pub fn set_show_inline_completions(
 1895        &mut self,
 1896        show_inline_completions: Option<bool>,
 1897        window: &mut Window,
 1898        cx: &mut Context<Self>,
 1899    ) {
 1900        self.show_inline_completions_override = show_inline_completions;
 1901        self.refresh_inline_completion(false, true, window, cx);
 1902    }
 1903
 1904    fn inline_completions_disabled_in_scope(
 1905        &self,
 1906        buffer: &Entity<Buffer>,
 1907        buffer_position: language::Anchor,
 1908        cx: &App,
 1909    ) -> bool {
 1910        let snapshot = buffer.read(cx).snapshot();
 1911        let settings = snapshot.settings_at(buffer_position, cx);
 1912
 1913        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1914            return false;
 1915        };
 1916
 1917        scope.override_name().map_or(false, |scope_name| {
 1918            settings
 1919                .inline_completions_disabled_in
 1920                .iter()
 1921                .any(|s| s == scope_name)
 1922        })
 1923    }
 1924
 1925    pub fn set_use_modal_editing(&mut self, to: bool) {
 1926        self.use_modal_editing = to;
 1927    }
 1928
 1929    pub fn use_modal_editing(&self) -> bool {
 1930        self.use_modal_editing
 1931    }
 1932
 1933    fn selections_did_change(
 1934        &mut self,
 1935        local: bool,
 1936        old_cursor_position: &Anchor,
 1937        show_completions: bool,
 1938        window: &mut Window,
 1939        cx: &mut Context<Self>,
 1940    ) {
 1941        window.invalidate_character_coordinates();
 1942
 1943        // Copy selections to primary selection buffer
 1944        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1945        if local {
 1946            let selections = self.selections.all::<usize>(cx);
 1947            let buffer_handle = self.buffer.read(cx).read(cx);
 1948
 1949            let mut text = String::new();
 1950            for (index, selection) in selections.iter().enumerate() {
 1951                let text_for_selection = buffer_handle
 1952                    .text_for_range(selection.start..selection.end)
 1953                    .collect::<String>();
 1954
 1955                text.push_str(&text_for_selection);
 1956                if index != selections.len() - 1 {
 1957                    text.push('\n');
 1958                }
 1959            }
 1960
 1961            if !text.is_empty() {
 1962                cx.write_to_primary(ClipboardItem::new_string(text));
 1963            }
 1964        }
 1965
 1966        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1967            self.buffer.update(cx, |buffer, cx| {
 1968                buffer.set_active_selections(
 1969                    &self.selections.disjoint_anchors(),
 1970                    self.selections.line_mode,
 1971                    self.cursor_shape,
 1972                    cx,
 1973                )
 1974            });
 1975        }
 1976        let display_map = self
 1977            .display_map
 1978            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1979        let buffer = &display_map.buffer_snapshot;
 1980        self.add_selections_state = None;
 1981        self.select_next_state = None;
 1982        self.select_prev_state = None;
 1983        self.select_larger_syntax_node_stack.clear();
 1984        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1985        self.snippet_stack
 1986            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1987        self.take_rename(false, window, cx);
 1988
 1989        let new_cursor_position = self.selections.newest_anchor().head();
 1990
 1991        self.push_to_nav_history(
 1992            *old_cursor_position,
 1993            Some(new_cursor_position.to_point(buffer)),
 1994            cx,
 1995        );
 1996
 1997        if local {
 1998            let new_cursor_position = self.selections.newest_anchor().head();
 1999            let mut context_menu = self.context_menu.borrow_mut();
 2000            let completion_menu = match context_menu.as_ref() {
 2001                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2002                _ => {
 2003                    *context_menu = None;
 2004                    None
 2005                }
 2006            };
 2007
 2008            if let Some(completion_menu) = completion_menu {
 2009                let cursor_position = new_cursor_position.to_offset(buffer);
 2010                let (word_range, kind) =
 2011                    buffer.surrounding_word(completion_menu.initial_position, true);
 2012                if kind == Some(CharKind::Word)
 2013                    && word_range.to_inclusive().contains(&cursor_position)
 2014                {
 2015                    let mut completion_menu = completion_menu.clone();
 2016                    drop(context_menu);
 2017
 2018                    let query = Self::completion_query(buffer, cursor_position);
 2019                    cx.spawn(move |this, mut cx| async move {
 2020                        completion_menu
 2021                            .filter(query.as_deref(), cx.background_executor().clone())
 2022                            .await;
 2023
 2024                        this.update(&mut cx, |this, cx| {
 2025                            let mut context_menu = this.context_menu.borrow_mut();
 2026                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2027                            else {
 2028                                return;
 2029                            };
 2030
 2031                            if menu.id > completion_menu.id {
 2032                                return;
 2033                            }
 2034
 2035                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2036                            drop(context_menu);
 2037                            cx.notify();
 2038                        })
 2039                    })
 2040                    .detach();
 2041
 2042                    if show_completions {
 2043                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2044                    }
 2045                } else {
 2046                    drop(context_menu);
 2047                    self.hide_context_menu(window, cx);
 2048                }
 2049            } else {
 2050                drop(context_menu);
 2051            }
 2052
 2053            hide_hover(self, cx);
 2054
 2055            if old_cursor_position.to_display_point(&display_map).row()
 2056                != new_cursor_position.to_display_point(&display_map).row()
 2057            {
 2058                self.available_code_actions.take();
 2059            }
 2060            self.refresh_code_actions(window, cx);
 2061            self.refresh_document_highlights(cx);
 2062            refresh_matching_bracket_highlights(self, window, cx);
 2063            self.update_visible_inline_completion(window, cx);
 2064            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2065            if self.git_blame_inline_enabled {
 2066                self.start_inline_blame_timer(window, cx);
 2067            }
 2068        }
 2069
 2070        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2071        cx.emit(EditorEvent::SelectionsChanged { local });
 2072
 2073        if self.selections.disjoint_anchors().len() == 1 {
 2074            cx.emit(SearchEvent::ActiveMatchChanged)
 2075        }
 2076        cx.notify();
 2077    }
 2078
 2079    pub fn change_selections<R>(
 2080        &mut self,
 2081        autoscroll: Option<Autoscroll>,
 2082        window: &mut Window,
 2083        cx: &mut Context<Self>,
 2084        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2085    ) -> R {
 2086        self.change_selections_inner(autoscroll, true, window, cx, change)
 2087    }
 2088
 2089    pub fn change_selections_inner<R>(
 2090        &mut self,
 2091        autoscroll: Option<Autoscroll>,
 2092        request_completions: bool,
 2093        window: &mut Window,
 2094        cx: &mut Context<Self>,
 2095        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2096    ) -> R {
 2097        let old_cursor_position = self.selections.newest_anchor().head();
 2098        self.push_to_selection_history();
 2099
 2100        let (changed, result) = self.selections.change_with(cx, change);
 2101
 2102        if changed {
 2103            if let Some(autoscroll) = autoscroll {
 2104                self.request_autoscroll(autoscroll, cx);
 2105            }
 2106            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2107
 2108            if self.should_open_signature_help_automatically(
 2109                &old_cursor_position,
 2110                self.signature_help_state.backspace_pressed(),
 2111                cx,
 2112            ) {
 2113                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2114            }
 2115            self.signature_help_state.set_backspace_pressed(false);
 2116        }
 2117
 2118        result
 2119    }
 2120
 2121    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2122    where
 2123        I: IntoIterator<Item = (Range<S>, T)>,
 2124        S: ToOffset,
 2125        T: Into<Arc<str>>,
 2126    {
 2127        if self.read_only(cx) {
 2128            return;
 2129        }
 2130
 2131        self.buffer
 2132            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2133    }
 2134
 2135    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2136    where
 2137        I: IntoIterator<Item = (Range<S>, T)>,
 2138        S: ToOffset,
 2139        T: Into<Arc<str>>,
 2140    {
 2141        if self.read_only(cx) {
 2142            return;
 2143        }
 2144
 2145        self.buffer.update(cx, |buffer, cx| {
 2146            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2147        });
 2148    }
 2149
 2150    pub fn edit_with_block_indent<I, S, T>(
 2151        &mut self,
 2152        edits: I,
 2153        original_indent_columns: Vec<u32>,
 2154        cx: &mut Context<Self>,
 2155    ) where
 2156        I: IntoIterator<Item = (Range<S>, T)>,
 2157        S: ToOffset,
 2158        T: Into<Arc<str>>,
 2159    {
 2160        if self.read_only(cx) {
 2161            return;
 2162        }
 2163
 2164        self.buffer.update(cx, |buffer, cx| {
 2165            buffer.edit(
 2166                edits,
 2167                Some(AutoindentMode::Block {
 2168                    original_indent_columns,
 2169                }),
 2170                cx,
 2171            )
 2172        });
 2173    }
 2174
 2175    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2176        self.hide_context_menu(window, cx);
 2177
 2178        match phase {
 2179            SelectPhase::Begin {
 2180                position,
 2181                add,
 2182                click_count,
 2183            } => self.begin_selection(position, add, click_count, window, cx),
 2184            SelectPhase::BeginColumnar {
 2185                position,
 2186                goal_column,
 2187                reset,
 2188            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2189            SelectPhase::Extend {
 2190                position,
 2191                click_count,
 2192            } => self.extend_selection(position, click_count, window, cx),
 2193            SelectPhase::Update {
 2194                position,
 2195                goal_column,
 2196                scroll_delta,
 2197            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2198            SelectPhase::End => self.end_selection(window, cx),
 2199        }
 2200    }
 2201
 2202    fn extend_selection(
 2203        &mut self,
 2204        position: DisplayPoint,
 2205        click_count: usize,
 2206        window: &mut Window,
 2207        cx: &mut Context<Self>,
 2208    ) {
 2209        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2210        let tail = self.selections.newest::<usize>(cx).tail();
 2211        self.begin_selection(position, false, click_count, window, cx);
 2212
 2213        let position = position.to_offset(&display_map, Bias::Left);
 2214        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2215
 2216        let mut pending_selection = self
 2217            .selections
 2218            .pending_anchor()
 2219            .expect("extend_selection not called with pending selection");
 2220        if position >= tail {
 2221            pending_selection.start = tail_anchor;
 2222        } else {
 2223            pending_selection.end = tail_anchor;
 2224            pending_selection.reversed = true;
 2225        }
 2226
 2227        let mut pending_mode = self.selections.pending_mode().unwrap();
 2228        match &mut pending_mode {
 2229            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2230            _ => {}
 2231        }
 2232
 2233        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2234            s.set_pending(pending_selection, pending_mode)
 2235        });
 2236    }
 2237
 2238    fn begin_selection(
 2239        &mut self,
 2240        position: DisplayPoint,
 2241        add: bool,
 2242        click_count: usize,
 2243        window: &mut Window,
 2244        cx: &mut Context<Self>,
 2245    ) {
 2246        if !self.focus_handle.is_focused(window) {
 2247            self.last_focused_descendant = None;
 2248            window.focus(&self.focus_handle);
 2249        }
 2250
 2251        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2252        let buffer = &display_map.buffer_snapshot;
 2253        let newest_selection = self.selections.newest_anchor().clone();
 2254        let position = display_map.clip_point(position, Bias::Left);
 2255
 2256        let start;
 2257        let end;
 2258        let mode;
 2259        let mut auto_scroll;
 2260        match click_count {
 2261            1 => {
 2262                start = buffer.anchor_before(position.to_point(&display_map));
 2263                end = start;
 2264                mode = SelectMode::Character;
 2265                auto_scroll = true;
 2266            }
 2267            2 => {
 2268                let range = movement::surrounding_word(&display_map, position);
 2269                start = buffer.anchor_before(range.start.to_point(&display_map));
 2270                end = buffer.anchor_before(range.end.to_point(&display_map));
 2271                mode = SelectMode::Word(start..end);
 2272                auto_scroll = true;
 2273            }
 2274            3 => {
 2275                let position = display_map
 2276                    .clip_point(position, Bias::Left)
 2277                    .to_point(&display_map);
 2278                let line_start = display_map.prev_line_boundary(position).0;
 2279                let next_line_start = buffer.clip_point(
 2280                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2281                    Bias::Left,
 2282                );
 2283                start = buffer.anchor_before(line_start);
 2284                end = buffer.anchor_before(next_line_start);
 2285                mode = SelectMode::Line(start..end);
 2286                auto_scroll = true;
 2287            }
 2288            _ => {
 2289                start = buffer.anchor_before(0);
 2290                end = buffer.anchor_before(buffer.len());
 2291                mode = SelectMode::All;
 2292                auto_scroll = false;
 2293            }
 2294        }
 2295        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2296
 2297        let point_to_delete: Option<usize> = {
 2298            let selected_points: Vec<Selection<Point>> =
 2299                self.selections.disjoint_in_range(start..end, cx);
 2300
 2301            if !add || click_count > 1 {
 2302                None
 2303            } else if !selected_points.is_empty() {
 2304                Some(selected_points[0].id)
 2305            } else {
 2306                let clicked_point_already_selected =
 2307                    self.selections.disjoint.iter().find(|selection| {
 2308                        selection.start.to_point(buffer) == start.to_point(buffer)
 2309                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2310                    });
 2311
 2312                clicked_point_already_selected.map(|selection| selection.id)
 2313            }
 2314        };
 2315
 2316        let selections_count = self.selections.count();
 2317
 2318        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2319            if let Some(point_to_delete) = point_to_delete {
 2320                s.delete(point_to_delete);
 2321
 2322                if selections_count == 1 {
 2323                    s.set_pending_anchor_range(start..end, mode);
 2324                }
 2325            } else {
 2326                if !add {
 2327                    s.clear_disjoint();
 2328                } else if click_count > 1 {
 2329                    s.delete(newest_selection.id)
 2330                }
 2331
 2332                s.set_pending_anchor_range(start..end, mode);
 2333            }
 2334        });
 2335    }
 2336
 2337    fn begin_columnar_selection(
 2338        &mut self,
 2339        position: DisplayPoint,
 2340        goal_column: u32,
 2341        reset: bool,
 2342        window: &mut Window,
 2343        cx: &mut Context<Self>,
 2344    ) {
 2345        if !self.focus_handle.is_focused(window) {
 2346            self.last_focused_descendant = None;
 2347            window.focus(&self.focus_handle);
 2348        }
 2349
 2350        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2351
 2352        if reset {
 2353            let pointer_position = display_map
 2354                .buffer_snapshot
 2355                .anchor_before(position.to_point(&display_map));
 2356
 2357            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2358                s.clear_disjoint();
 2359                s.set_pending_anchor_range(
 2360                    pointer_position..pointer_position,
 2361                    SelectMode::Character,
 2362                );
 2363            });
 2364        }
 2365
 2366        let tail = self.selections.newest::<Point>(cx).tail();
 2367        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2368
 2369        if !reset {
 2370            self.select_columns(
 2371                tail.to_display_point(&display_map),
 2372                position,
 2373                goal_column,
 2374                &display_map,
 2375                window,
 2376                cx,
 2377            );
 2378        }
 2379    }
 2380
 2381    fn update_selection(
 2382        &mut self,
 2383        position: DisplayPoint,
 2384        goal_column: u32,
 2385        scroll_delta: gpui::Point<f32>,
 2386        window: &mut Window,
 2387        cx: &mut Context<Self>,
 2388    ) {
 2389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2390
 2391        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2392            let tail = tail.to_display_point(&display_map);
 2393            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2394        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2395            let buffer = self.buffer.read(cx).snapshot(cx);
 2396            let head;
 2397            let tail;
 2398            let mode = self.selections.pending_mode().unwrap();
 2399            match &mode {
 2400                SelectMode::Character => {
 2401                    head = position.to_point(&display_map);
 2402                    tail = pending.tail().to_point(&buffer);
 2403                }
 2404                SelectMode::Word(original_range) => {
 2405                    let original_display_range = original_range.start.to_display_point(&display_map)
 2406                        ..original_range.end.to_display_point(&display_map);
 2407                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2408                        ..original_display_range.end.to_point(&display_map);
 2409                    if movement::is_inside_word(&display_map, position)
 2410                        || original_display_range.contains(&position)
 2411                    {
 2412                        let word_range = movement::surrounding_word(&display_map, position);
 2413                        if word_range.start < original_display_range.start {
 2414                            head = word_range.start.to_point(&display_map);
 2415                        } else {
 2416                            head = word_range.end.to_point(&display_map);
 2417                        }
 2418                    } else {
 2419                        head = position.to_point(&display_map);
 2420                    }
 2421
 2422                    if head <= original_buffer_range.start {
 2423                        tail = original_buffer_range.end;
 2424                    } else {
 2425                        tail = original_buffer_range.start;
 2426                    }
 2427                }
 2428                SelectMode::Line(original_range) => {
 2429                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2430
 2431                    let position = display_map
 2432                        .clip_point(position, Bias::Left)
 2433                        .to_point(&display_map);
 2434                    let line_start = display_map.prev_line_boundary(position).0;
 2435                    let next_line_start = buffer.clip_point(
 2436                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2437                        Bias::Left,
 2438                    );
 2439
 2440                    if line_start < original_range.start {
 2441                        head = line_start
 2442                    } else {
 2443                        head = next_line_start
 2444                    }
 2445
 2446                    if head <= original_range.start {
 2447                        tail = original_range.end;
 2448                    } else {
 2449                        tail = original_range.start;
 2450                    }
 2451                }
 2452                SelectMode::All => {
 2453                    return;
 2454                }
 2455            };
 2456
 2457            if head < tail {
 2458                pending.start = buffer.anchor_before(head);
 2459                pending.end = buffer.anchor_before(tail);
 2460                pending.reversed = true;
 2461            } else {
 2462                pending.start = buffer.anchor_before(tail);
 2463                pending.end = buffer.anchor_before(head);
 2464                pending.reversed = false;
 2465            }
 2466
 2467            self.change_selections(None, window, cx, |s| {
 2468                s.set_pending(pending, mode);
 2469            });
 2470        } else {
 2471            log::error!("update_selection dispatched with no pending selection");
 2472            return;
 2473        }
 2474
 2475        self.apply_scroll_delta(scroll_delta, window, cx);
 2476        cx.notify();
 2477    }
 2478
 2479    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2480        self.columnar_selection_tail.take();
 2481        if self.selections.pending_anchor().is_some() {
 2482            let selections = self.selections.all::<usize>(cx);
 2483            self.change_selections(None, window, cx, |s| {
 2484                s.select(selections);
 2485                s.clear_pending();
 2486            });
 2487        }
 2488    }
 2489
 2490    fn select_columns(
 2491        &mut self,
 2492        tail: DisplayPoint,
 2493        head: DisplayPoint,
 2494        goal_column: u32,
 2495        display_map: &DisplaySnapshot,
 2496        window: &mut Window,
 2497        cx: &mut Context<Self>,
 2498    ) {
 2499        let start_row = cmp::min(tail.row(), head.row());
 2500        let end_row = cmp::max(tail.row(), head.row());
 2501        let start_column = cmp::min(tail.column(), goal_column);
 2502        let end_column = cmp::max(tail.column(), goal_column);
 2503        let reversed = start_column < tail.column();
 2504
 2505        let selection_ranges = (start_row.0..=end_row.0)
 2506            .map(DisplayRow)
 2507            .filter_map(|row| {
 2508                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2509                    let start = display_map
 2510                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2511                        .to_point(display_map);
 2512                    let end = display_map
 2513                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2514                        .to_point(display_map);
 2515                    if reversed {
 2516                        Some(end..start)
 2517                    } else {
 2518                        Some(start..end)
 2519                    }
 2520                } else {
 2521                    None
 2522                }
 2523            })
 2524            .collect::<Vec<_>>();
 2525
 2526        self.change_selections(None, window, cx, |s| {
 2527            s.select_ranges(selection_ranges);
 2528        });
 2529        cx.notify();
 2530    }
 2531
 2532    pub fn has_pending_nonempty_selection(&self) -> bool {
 2533        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2534            Some(Selection { start, end, .. }) => start != end,
 2535            None => false,
 2536        };
 2537
 2538        pending_nonempty_selection
 2539            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2540    }
 2541
 2542    pub fn has_pending_selection(&self) -> bool {
 2543        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2544    }
 2545
 2546    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2547        self.selection_mark_mode = false;
 2548
 2549        if self.clear_expanded_diff_hunks(cx) {
 2550            cx.notify();
 2551            return;
 2552        }
 2553        if self.dismiss_menus_and_popups(true, window, cx) {
 2554            return;
 2555        }
 2556
 2557        if self.mode == EditorMode::Full
 2558            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2559        {
 2560            return;
 2561        }
 2562
 2563        cx.propagate();
 2564    }
 2565
 2566    pub fn dismiss_menus_and_popups(
 2567        &mut self,
 2568        should_report_inline_completion_event: bool,
 2569        window: &mut Window,
 2570        cx: &mut Context<Self>,
 2571    ) -> bool {
 2572        if self.take_rename(false, window, cx).is_some() {
 2573            return true;
 2574        }
 2575
 2576        if hide_hover(self, cx) {
 2577            return true;
 2578        }
 2579
 2580        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2581            return true;
 2582        }
 2583
 2584        if self.hide_context_menu(window, cx).is_some() {
 2585            return true;
 2586        }
 2587
 2588        if self.mouse_context_menu.take().is_some() {
 2589            return true;
 2590        }
 2591
 2592        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2593            return true;
 2594        }
 2595
 2596        if self.snippet_stack.pop().is_some() {
 2597            return true;
 2598        }
 2599
 2600        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2601            self.dismiss_diagnostics(cx);
 2602            return true;
 2603        }
 2604
 2605        false
 2606    }
 2607
 2608    fn linked_editing_ranges_for(
 2609        &self,
 2610        selection: Range<text::Anchor>,
 2611        cx: &App,
 2612    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2613        if self.linked_edit_ranges.is_empty() {
 2614            return None;
 2615        }
 2616        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2617            selection.end.buffer_id.and_then(|end_buffer_id| {
 2618                if selection.start.buffer_id != Some(end_buffer_id) {
 2619                    return None;
 2620                }
 2621                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2622                let snapshot = buffer.read(cx).snapshot();
 2623                self.linked_edit_ranges
 2624                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2625                    .map(|ranges| (ranges, snapshot, buffer))
 2626            })?;
 2627        use text::ToOffset as TO;
 2628        // find offset from the start of current range to current cursor position
 2629        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2630
 2631        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2632        let start_difference = start_offset - start_byte_offset;
 2633        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2634        let end_difference = end_offset - start_byte_offset;
 2635        // Current range has associated linked ranges.
 2636        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2637        for range in linked_ranges.iter() {
 2638            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2639            let end_offset = start_offset + end_difference;
 2640            let start_offset = start_offset + start_difference;
 2641            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2642                continue;
 2643            }
 2644            if self.selections.disjoint_anchor_ranges().any(|s| {
 2645                if s.start.buffer_id != selection.start.buffer_id
 2646                    || s.end.buffer_id != selection.end.buffer_id
 2647                {
 2648                    return false;
 2649                }
 2650                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2651                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2652            }) {
 2653                continue;
 2654            }
 2655            let start = buffer_snapshot.anchor_after(start_offset);
 2656            let end = buffer_snapshot.anchor_after(end_offset);
 2657            linked_edits
 2658                .entry(buffer.clone())
 2659                .or_default()
 2660                .push(start..end);
 2661        }
 2662        Some(linked_edits)
 2663    }
 2664
 2665    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2666        let text: Arc<str> = text.into();
 2667
 2668        if self.read_only(cx) {
 2669            return;
 2670        }
 2671
 2672        let selections = self.selections.all_adjusted(cx);
 2673        let mut bracket_inserted = false;
 2674        let mut edits = Vec::new();
 2675        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2676        let mut new_selections = Vec::with_capacity(selections.len());
 2677        let mut new_autoclose_regions = Vec::new();
 2678        let snapshot = self.buffer.read(cx).read(cx);
 2679
 2680        for (selection, autoclose_region) in
 2681            self.selections_with_autoclose_regions(selections, &snapshot)
 2682        {
 2683            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2684                // Determine if the inserted text matches the opening or closing
 2685                // bracket of any of this language's bracket pairs.
 2686                let mut bracket_pair = None;
 2687                let mut is_bracket_pair_start = false;
 2688                let mut is_bracket_pair_end = false;
 2689                if !text.is_empty() {
 2690                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2691                    //  and they are removing the character that triggered IME popup.
 2692                    for (pair, enabled) in scope.brackets() {
 2693                        if !pair.close && !pair.surround {
 2694                            continue;
 2695                        }
 2696
 2697                        if enabled && pair.start.ends_with(text.as_ref()) {
 2698                            let prefix_len = pair.start.len() - text.len();
 2699                            let preceding_text_matches_prefix = prefix_len == 0
 2700                                || (selection.start.column >= (prefix_len as u32)
 2701                                    && snapshot.contains_str_at(
 2702                                        Point::new(
 2703                                            selection.start.row,
 2704                                            selection.start.column - (prefix_len as u32),
 2705                                        ),
 2706                                        &pair.start[..prefix_len],
 2707                                    ));
 2708                            if preceding_text_matches_prefix {
 2709                                bracket_pair = Some(pair.clone());
 2710                                is_bracket_pair_start = true;
 2711                                break;
 2712                            }
 2713                        }
 2714                        if pair.end.as_str() == text.as_ref() {
 2715                            bracket_pair = Some(pair.clone());
 2716                            is_bracket_pair_end = true;
 2717                            break;
 2718                        }
 2719                    }
 2720                }
 2721
 2722                if let Some(bracket_pair) = bracket_pair {
 2723                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2724                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2725                    let auto_surround =
 2726                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2727                    if selection.is_empty() {
 2728                        if is_bracket_pair_start {
 2729                            // If the inserted text is a suffix of an opening bracket and the
 2730                            // selection is preceded by the rest of the opening bracket, then
 2731                            // insert the closing bracket.
 2732                            let following_text_allows_autoclose = snapshot
 2733                                .chars_at(selection.start)
 2734                                .next()
 2735                                .map_or(true, |c| scope.should_autoclose_before(c));
 2736
 2737                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2738                                && bracket_pair.start.len() == 1
 2739                            {
 2740                                let target = bracket_pair.start.chars().next().unwrap();
 2741                                let current_line_count = snapshot
 2742                                    .reversed_chars_at(selection.start)
 2743                                    .take_while(|&c| c != '\n')
 2744                                    .filter(|&c| c == target)
 2745                                    .count();
 2746                                current_line_count % 2 == 1
 2747                            } else {
 2748                                false
 2749                            };
 2750
 2751                            if autoclose
 2752                                && bracket_pair.close
 2753                                && following_text_allows_autoclose
 2754                                && !is_closing_quote
 2755                            {
 2756                                let anchor = snapshot.anchor_before(selection.end);
 2757                                new_selections.push((selection.map(|_| anchor), text.len()));
 2758                                new_autoclose_regions.push((
 2759                                    anchor,
 2760                                    text.len(),
 2761                                    selection.id,
 2762                                    bracket_pair.clone(),
 2763                                ));
 2764                                edits.push((
 2765                                    selection.range(),
 2766                                    format!("{}{}", text, bracket_pair.end).into(),
 2767                                ));
 2768                                bracket_inserted = true;
 2769                                continue;
 2770                            }
 2771                        }
 2772
 2773                        if let Some(region) = autoclose_region {
 2774                            // If the selection is followed by an auto-inserted closing bracket,
 2775                            // then don't insert that closing bracket again; just move the selection
 2776                            // past the closing bracket.
 2777                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2778                                && text.as_ref() == region.pair.end.as_str();
 2779                            if should_skip {
 2780                                let anchor = snapshot.anchor_after(selection.end);
 2781                                new_selections
 2782                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2783                                continue;
 2784                            }
 2785                        }
 2786
 2787                        let always_treat_brackets_as_autoclosed = snapshot
 2788                            .settings_at(selection.start, cx)
 2789                            .always_treat_brackets_as_autoclosed;
 2790                        if always_treat_brackets_as_autoclosed
 2791                            && is_bracket_pair_end
 2792                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2793                        {
 2794                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2795                            // and the inserted text is a closing bracket and the selection is followed
 2796                            // by the closing bracket then move the selection past the closing bracket.
 2797                            let anchor = snapshot.anchor_after(selection.end);
 2798                            new_selections.push((selection.map(|_| anchor), text.len()));
 2799                            continue;
 2800                        }
 2801                    }
 2802                    // If an opening bracket is 1 character long and is typed while
 2803                    // text is selected, then surround that text with the bracket pair.
 2804                    else if auto_surround
 2805                        && bracket_pair.surround
 2806                        && is_bracket_pair_start
 2807                        && bracket_pair.start.chars().count() == 1
 2808                    {
 2809                        edits.push((selection.start..selection.start, text.clone()));
 2810                        edits.push((
 2811                            selection.end..selection.end,
 2812                            bracket_pair.end.as_str().into(),
 2813                        ));
 2814                        bracket_inserted = true;
 2815                        new_selections.push((
 2816                            Selection {
 2817                                id: selection.id,
 2818                                start: snapshot.anchor_after(selection.start),
 2819                                end: snapshot.anchor_before(selection.end),
 2820                                reversed: selection.reversed,
 2821                                goal: selection.goal,
 2822                            },
 2823                            0,
 2824                        ));
 2825                        continue;
 2826                    }
 2827                }
 2828            }
 2829
 2830            if self.auto_replace_emoji_shortcode
 2831                && selection.is_empty()
 2832                && text.as_ref().ends_with(':')
 2833            {
 2834                if let Some(possible_emoji_short_code) =
 2835                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2836                {
 2837                    if !possible_emoji_short_code.is_empty() {
 2838                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2839                            let emoji_shortcode_start = Point::new(
 2840                                selection.start.row,
 2841                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2842                            );
 2843
 2844                            // Remove shortcode from buffer
 2845                            edits.push((
 2846                                emoji_shortcode_start..selection.start,
 2847                                "".to_string().into(),
 2848                            ));
 2849                            new_selections.push((
 2850                                Selection {
 2851                                    id: selection.id,
 2852                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2853                                    end: snapshot.anchor_before(selection.start),
 2854                                    reversed: selection.reversed,
 2855                                    goal: selection.goal,
 2856                                },
 2857                                0,
 2858                            ));
 2859
 2860                            // Insert emoji
 2861                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2862                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2863                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2864
 2865                            continue;
 2866                        }
 2867                    }
 2868                }
 2869            }
 2870
 2871            // If not handling any auto-close operation, then just replace the selected
 2872            // text with the given input and move the selection to the end of the
 2873            // newly inserted text.
 2874            let anchor = snapshot.anchor_after(selection.end);
 2875            if !self.linked_edit_ranges.is_empty() {
 2876                let start_anchor = snapshot.anchor_before(selection.start);
 2877
 2878                let is_word_char = text.chars().next().map_or(true, |char| {
 2879                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2880                    classifier.is_word(char)
 2881                });
 2882
 2883                if is_word_char {
 2884                    if let Some(ranges) = self
 2885                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2886                    {
 2887                        for (buffer, edits) in ranges {
 2888                            linked_edits
 2889                                .entry(buffer.clone())
 2890                                .or_default()
 2891                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2892                        }
 2893                    }
 2894                }
 2895            }
 2896
 2897            new_selections.push((selection.map(|_| anchor), 0));
 2898            edits.push((selection.start..selection.end, text.clone()));
 2899        }
 2900
 2901        drop(snapshot);
 2902
 2903        self.transact(window, cx, |this, window, cx| {
 2904            this.buffer.update(cx, |buffer, cx| {
 2905                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2906            });
 2907            for (buffer, edits) in linked_edits {
 2908                buffer.update(cx, |buffer, cx| {
 2909                    let snapshot = buffer.snapshot();
 2910                    let edits = edits
 2911                        .into_iter()
 2912                        .map(|(range, text)| {
 2913                            use text::ToPoint as TP;
 2914                            let end_point = TP::to_point(&range.end, &snapshot);
 2915                            let start_point = TP::to_point(&range.start, &snapshot);
 2916                            (start_point..end_point, text)
 2917                        })
 2918                        .sorted_by_key(|(range, _)| range.start)
 2919                        .collect::<Vec<_>>();
 2920                    buffer.edit(edits, None, cx);
 2921                })
 2922            }
 2923            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2924            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2925            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2926            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2927                .zip(new_selection_deltas)
 2928                .map(|(selection, delta)| Selection {
 2929                    id: selection.id,
 2930                    start: selection.start + delta,
 2931                    end: selection.end + delta,
 2932                    reversed: selection.reversed,
 2933                    goal: SelectionGoal::None,
 2934                })
 2935                .collect::<Vec<_>>();
 2936
 2937            let mut i = 0;
 2938            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2939                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2940                let start = map.buffer_snapshot.anchor_before(position);
 2941                let end = map.buffer_snapshot.anchor_after(position);
 2942                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2943                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2944                        Ordering::Less => i += 1,
 2945                        Ordering::Greater => break,
 2946                        Ordering::Equal => {
 2947                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2948                                Ordering::Less => i += 1,
 2949                                Ordering::Equal => break,
 2950                                Ordering::Greater => break,
 2951                            }
 2952                        }
 2953                    }
 2954                }
 2955                this.autoclose_regions.insert(
 2956                    i,
 2957                    AutocloseRegion {
 2958                        selection_id,
 2959                        range: start..end,
 2960                        pair,
 2961                    },
 2962                );
 2963            }
 2964
 2965            let had_active_inline_completion = this.has_active_inline_completion();
 2966            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2967                s.select(new_selections)
 2968            });
 2969
 2970            if !bracket_inserted {
 2971                if let Some(on_type_format_task) =
 2972                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2973                {
 2974                    on_type_format_task.detach_and_log_err(cx);
 2975                }
 2976            }
 2977
 2978            let editor_settings = EditorSettings::get_global(cx);
 2979            if bracket_inserted
 2980                && (editor_settings.auto_signature_help
 2981                    || editor_settings.show_signature_help_after_edits)
 2982            {
 2983                this.show_signature_help(&ShowSignatureHelp, window, cx);
 2984            }
 2985
 2986            let trigger_in_words =
 2987                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2988            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 2989            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 2990            this.refresh_inline_completion(true, false, window, cx);
 2991        });
 2992    }
 2993
 2994    fn find_possible_emoji_shortcode_at_position(
 2995        snapshot: &MultiBufferSnapshot,
 2996        position: Point,
 2997    ) -> Option<String> {
 2998        let mut chars = Vec::new();
 2999        let mut found_colon = false;
 3000        for char in snapshot.reversed_chars_at(position).take(100) {
 3001            // Found a possible emoji shortcode in the middle of the buffer
 3002            if found_colon {
 3003                if char.is_whitespace() {
 3004                    chars.reverse();
 3005                    return Some(chars.iter().collect());
 3006                }
 3007                // If the previous character is not a whitespace, we are in the middle of a word
 3008                // and we only want to complete the shortcode if the word is made up of other emojis
 3009                let mut containing_word = String::new();
 3010                for ch in snapshot
 3011                    .reversed_chars_at(position)
 3012                    .skip(chars.len() + 1)
 3013                    .take(100)
 3014                {
 3015                    if ch.is_whitespace() {
 3016                        break;
 3017                    }
 3018                    containing_word.push(ch);
 3019                }
 3020                let containing_word = containing_word.chars().rev().collect::<String>();
 3021                if util::word_consists_of_emojis(containing_word.as_str()) {
 3022                    chars.reverse();
 3023                    return Some(chars.iter().collect());
 3024                }
 3025            }
 3026
 3027            if char.is_whitespace() || !char.is_ascii() {
 3028                return None;
 3029            }
 3030            if char == ':' {
 3031                found_colon = true;
 3032            } else {
 3033                chars.push(char);
 3034            }
 3035        }
 3036        // Found a possible emoji shortcode at the beginning of the buffer
 3037        chars.reverse();
 3038        Some(chars.iter().collect())
 3039    }
 3040
 3041    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3042        self.transact(window, cx, |this, window, cx| {
 3043            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3044                let selections = this.selections.all::<usize>(cx);
 3045                let multi_buffer = this.buffer.read(cx);
 3046                let buffer = multi_buffer.snapshot(cx);
 3047                selections
 3048                    .iter()
 3049                    .map(|selection| {
 3050                        let start_point = selection.start.to_point(&buffer);
 3051                        let mut indent =
 3052                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3053                        indent.len = cmp::min(indent.len, start_point.column);
 3054                        let start = selection.start;
 3055                        let end = selection.end;
 3056                        let selection_is_empty = start == end;
 3057                        let language_scope = buffer.language_scope_at(start);
 3058                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3059                            &language_scope
 3060                        {
 3061                            let leading_whitespace_len = buffer
 3062                                .reversed_chars_at(start)
 3063                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3064                                .map(|c| c.len_utf8())
 3065                                .sum::<usize>();
 3066
 3067                            let trailing_whitespace_len = buffer
 3068                                .chars_at(end)
 3069                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3070                                .map(|c| c.len_utf8())
 3071                                .sum::<usize>();
 3072
 3073                            let insert_extra_newline =
 3074                                language.brackets().any(|(pair, enabled)| {
 3075                                    let pair_start = pair.start.trim_end();
 3076                                    let pair_end = pair.end.trim_start();
 3077
 3078                                    enabled
 3079                                        && pair.newline
 3080                                        && buffer.contains_str_at(
 3081                                            end + trailing_whitespace_len,
 3082                                            pair_end,
 3083                                        )
 3084                                        && buffer.contains_str_at(
 3085                                            (start - leading_whitespace_len)
 3086                                                .saturating_sub(pair_start.len()),
 3087                                            pair_start,
 3088                                        )
 3089                                });
 3090
 3091                            // Comment extension on newline is allowed only for cursor selections
 3092                            let comment_delimiter = maybe!({
 3093                                if !selection_is_empty {
 3094                                    return None;
 3095                                }
 3096
 3097                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3098                                    return None;
 3099                                }
 3100
 3101                                let delimiters = language.line_comment_prefixes();
 3102                                let max_len_of_delimiter =
 3103                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3104                                let (snapshot, range) =
 3105                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3106
 3107                                let mut index_of_first_non_whitespace = 0;
 3108                                let comment_candidate = snapshot
 3109                                    .chars_for_range(range)
 3110                                    .skip_while(|c| {
 3111                                        let should_skip = c.is_whitespace();
 3112                                        if should_skip {
 3113                                            index_of_first_non_whitespace += 1;
 3114                                        }
 3115                                        should_skip
 3116                                    })
 3117                                    .take(max_len_of_delimiter)
 3118                                    .collect::<String>();
 3119                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3120                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3121                                })?;
 3122                                let cursor_is_placed_after_comment_marker =
 3123                                    index_of_first_non_whitespace + comment_prefix.len()
 3124                                        <= start_point.column as usize;
 3125                                if cursor_is_placed_after_comment_marker {
 3126                                    Some(comment_prefix.clone())
 3127                                } else {
 3128                                    None
 3129                                }
 3130                            });
 3131                            (comment_delimiter, insert_extra_newline)
 3132                        } else {
 3133                            (None, false)
 3134                        };
 3135
 3136                        let capacity_for_delimiter = comment_delimiter
 3137                            .as_deref()
 3138                            .map(str::len)
 3139                            .unwrap_or_default();
 3140                        let mut new_text =
 3141                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3142                        new_text.push('\n');
 3143                        new_text.extend(indent.chars());
 3144                        if let Some(delimiter) = &comment_delimiter {
 3145                            new_text.push_str(delimiter);
 3146                        }
 3147                        if insert_extra_newline {
 3148                            new_text = new_text.repeat(2);
 3149                        }
 3150
 3151                        let anchor = buffer.anchor_after(end);
 3152                        let new_selection = selection.map(|_| anchor);
 3153                        (
 3154                            (start..end, new_text),
 3155                            (insert_extra_newline, new_selection),
 3156                        )
 3157                    })
 3158                    .unzip()
 3159            };
 3160
 3161            this.edit_with_autoindent(edits, cx);
 3162            let buffer = this.buffer.read(cx).snapshot(cx);
 3163            let new_selections = selection_fixup_info
 3164                .into_iter()
 3165                .map(|(extra_newline_inserted, new_selection)| {
 3166                    let mut cursor = new_selection.end.to_point(&buffer);
 3167                    if extra_newline_inserted {
 3168                        cursor.row -= 1;
 3169                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3170                    }
 3171                    new_selection.map(|_| cursor)
 3172                })
 3173                .collect();
 3174
 3175            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3176                s.select(new_selections)
 3177            });
 3178            this.refresh_inline_completion(true, false, window, cx);
 3179        });
 3180    }
 3181
 3182    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3183        let buffer = self.buffer.read(cx);
 3184        let snapshot = buffer.snapshot(cx);
 3185
 3186        let mut edits = Vec::new();
 3187        let mut rows = Vec::new();
 3188
 3189        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3190            let cursor = selection.head();
 3191            let row = cursor.row;
 3192
 3193            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3194
 3195            let newline = "\n".to_string();
 3196            edits.push((start_of_line..start_of_line, newline));
 3197
 3198            rows.push(row + rows_inserted as u32);
 3199        }
 3200
 3201        self.transact(window, cx, |editor, window, cx| {
 3202            editor.edit(edits, cx);
 3203
 3204            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3205                let mut index = 0;
 3206                s.move_cursors_with(|map, _, _| {
 3207                    let row = rows[index];
 3208                    index += 1;
 3209
 3210                    let point = Point::new(row, 0);
 3211                    let boundary = map.next_line_boundary(point).1;
 3212                    let clipped = map.clip_point(boundary, Bias::Left);
 3213
 3214                    (clipped, SelectionGoal::None)
 3215                });
 3216            });
 3217
 3218            let mut indent_edits = Vec::new();
 3219            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3220            for row in rows {
 3221                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3222                for (row, indent) in indents {
 3223                    if indent.len == 0 {
 3224                        continue;
 3225                    }
 3226
 3227                    let text = match indent.kind {
 3228                        IndentKind::Space => " ".repeat(indent.len as usize),
 3229                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3230                    };
 3231                    let point = Point::new(row.0, 0);
 3232                    indent_edits.push((point..point, text));
 3233                }
 3234            }
 3235            editor.edit(indent_edits, cx);
 3236        });
 3237    }
 3238
 3239    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3240        let buffer = self.buffer.read(cx);
 3241        let snapshot = buffer.snapshot(cx);
 3242
 3243        let mut edits = Vec::new();
 3244        let mut rows = Vec::new();
 3245        let mut rows_inserted = 0;
 3246
 3247        for selection in self.selections.all_adjusted(cx) {
 3248            let cursor = selection.head();
 3249            let row = cursor.row;
 3250
 3251            let point = Point::new(row + 1, 0);
 3252            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3253
 3254            let newline = "\n".to_string();
 3255            edits.push((start_of_line..start_of_line, newline));
 3256
 3257            rows_inserted += 1;
 3258            rows.push(row + rows_inserted);
 3259        }
 3260
 3261        self.transact(window, cx, |editor, window, cx| {
 3262            editor.edit(edits, cx);
 3263
 3264            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3265                let mut index = 0;
 3266                s.move_cursors_with(|map, _, _| {
 3267                    let row = rows[index];
 3268                    index += 1;
 3269
 3270                    let point = Point::new(row, 0);
 3271                    let boundary = map.next_line_boundary(point).1;
 3272                    let clipped = map.clip_point(boundary, Bias::Left);
 3273
 3274                    (clipped, SelectionGoal::None)
 3275                });
 3276            });
 3277
 3278            let mut indent_edits = Vec::new();
 3279            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3280            for row in rows {
 3281                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3282                for (row, indent) in indents {
 3283                    if indent.len == 0 {
 3284                        continue;
 3285                    }
 3286
 3287                    let text = match indent.kind {
 3288                        IndentKind::Space => " ".repeat(indent.len as usize),
 3289                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3290                    };
 3291                    let point = Point::new(row.0, 0);
 3292                    indent_edits.push((point..point, text));
 3293                }
 3294            }
 3295            editor.edit(indent_edits, cx);
 3296        });
 3297    }
 3298
 3299    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3300        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3301            original_indent_columns: Vec::new(),
 3302        });
 3303        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3304    }
 3305
 3306    fn insert_with_autoindent_mode(
 3307        &mut self,
 3308        text: &str,
 3309        autoindent_mode: Option<AutoindentMode>,
 3310        window: &mut Window,
 3311        cx: &mut Context<Self>,
 3312    ) {
 3313        if self.read_only(cx) {
 3314            return;
 3315        }
 3316
 3317        let text: Arc<str> = text.into();
 3318        self.transact(window, cx, |this, window, cx| {
 3319            let old_selections = this.selections.all_adjusted(cx);
 3320            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3321                let anchors = {
 3322                    let snapshot = buffer.read(cx);
 3323                    old_selections
 3324                        .iter()
 3325                        .map(|s| {
 3326                            let anchor = snapshot.anchor_after(s.head());
 3327                            s.map(|_| anchor)
 3328                        })
 3329                        .collect::<Vec<_>>()
 3330                };
 3331                buffer.edit(
 3332                    old_selections
 3333                        .iter()
 3334                        .map(|s| (s.start..s.end, text.clone())),
 3335                    autoindent_mode,
 3336                    cx,
 3337                );
 3338                anchors
 3339            });
 3340
 3341            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3342                s.select_anchors(selection_anchors);
 3343            });
 3344
 3345            cx.notify();
 3346        });
 3347    }
 3348
 3349    fn trigger_completion_on_input(
 3350        &mut self,
 3351        text: &str,
 3352        trigger_in_words: bool,
 3353        window: &mut Window,
 3354        cx: &mut Context<Self>,
 3355    ) {
 3356        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3357            self.show_completions(
 3358                &ShowCompletions {
 3359                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3360                },
 3361                window,
 3362                cx,
 3363            );
 3364        } else {
 3365            self.hide_context_menu(window, cx);
 3366        }
 3367    }
 3368
 3369    fn is_completion_trigger(
 3370        &self,
 3371        text: &str,
 3372        trigger_in_words: bool,
 3373        cx: &mut Context<Self>,
 3374    ) -> bool {
 3375        let position = self.selections.newest_anchor().head();
 3376        let multibuffer = self.buffer.read(cx);
 3377        let Some(buffer) = position
 3378            .buffer_id
 3379            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3380        else {
 3381            return false;
 3382        };
 3383
 3384        if let Some(completion_provider) = &self.completion_provider {
 3385            completion_provider.is_completion_trigger(
 3386                &buffer,
 3387                position.text_anchor,
 3388                text,
 3389                trigger_in_words,
 3390                cx,
 3391            )
 3392        } else {
 3393            false
 3394        }
 3395    }
 3396
 3397    /// If any empty selections is touching the start of its innermost containing autoclose
 3398    /// region, expand it to select the brackets.
 3399    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3400        let selections = self.selections.all::<usize>(cx);
 3401        let buffer = self.buffer.read(cx).read(cx);
 3402        let new_selections = self
 3403            .selections_with_autoclose_regions(selections, &buffer)
 3404            .map(|(mut selection, region)| {
 3405                if !selection.is_empty() {
 3406                    return selection;
 3407                }
 3408
 3409                if let Some(region) = region {
 3410                    let mut range = region.range.to_offset(&buffer);
 3411                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3412                        range.start -= region.pair.start.len();
 3413                        if buffer.contains_str_at(range.start, &region.pair.start)
 3414                            && buffer.contains_str_at(range.end, &region.pair.end)
 3415                        {
 3416                            range.end += region.pair.end.len();
 3417                            selection.start = range.start;
 3418                            selection.end = range.end;
 3419
 3420                            return selection;
 3421                        }
 3422                    }
 3423                }
 3424
 3425                let always_treat_brackets_as_autoclosed = buffer
 3426                    .settings_at(selection.start, cx)
 3427                    .always_treat_brackets_as_autoclosed;
 3428
 3429                if !always_treat_brackets_as_autoclosed {
 3430                    return selection;
 3431                }
 3432
 3433                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3434                    for (pair, enabled) in scope.brackets() {
 3435                        if !enabled || !pair.close {
 3436                            continue;
 3437                        }
 3438
 3439                        if buffer.contains_str_at(selection.start, &pair.end) {
 3440                            let pair_start_len = pair.start.len();
 3441                            if buffer.contains_str_at(
 3442                                selection.start.saturating_sub(pair_start_len),
 3443                                &pair.start,
 3444                            ) {
 3445                                selection.start -= pair_start_len;
 3446                                selection.end += pair.end.len();
 3447
 3448                                return selection;
 3449                            }
 3450                        }
 3451                    }
 3452                }
 3453
 3454                selection
 3455            })
 3456            .collect();
 3457
 3458        drop(buffer);
 3459        self.change_selections(None, window, cx, |selections| {
 3460            selections.select(new_selections)
 3461        });
 3462    }
 3463
 3464    /// Iterate the given selections, and for each one, find the smallest surrounding
 3465    /// autoclose region. This uses the ordering of the selections and the autoclose
 3466    /// regions to avoid repeated comparisons.
 3467    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3468        &'a self,
 3469        selections: impl IntoIterator<Item = Selection<D>>,
 3470        buffer: &'a MultiBufferSnapshot,
 3471    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3472        let mut i = 0;
 3473        let mut regions = self.autoclose_regions.as_slice();
 3474        selections.into_iter().map(move |selection| {
 3475            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3476
 3477            let mut enclosing = None;
 3478            while let Some(pair_state) = regions.get(i) {
 3479                if pair_state.range.end.to_offset(buffer) < range.start {
 3480                    regions = &regions[i + 1..];
 3481                    i = 0;
 3482                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3483                    break;
 3484                } else {
 3485                    if pair_state.selection_id == selection.id {
 3486                        enclosing = Some(pair_state);
 3487                    }
 3488                    i += 1;
 3489                }
 3490            }
 3491
 3492            (selection, enclosing)
 3493        })
 3494    }
 3495
 3496    /// Remove any autoclose regions that no longer contain their selection.
 3497    fn invalidate_autoclose_regions(
 3498        &mut self,
 3499        mut selections: &[Selection<Anchor>],
 3500        buffer: &MultiBufferSnapshot,
 3501    ) {
 3502        self.autoclose_regions.retain(|state| {
 3503            let mut i = 0;
 3504            while let Some(selection) = selections.get(i) {
 3505                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3506                    selections = &selections[1..];
 3507                    continue;
 3508                }
 3509                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3510                    break;
 3511                }
 3512                if selection.id == state.selection_id {
 3513                    return true;
 3514                } else {
 3515                    i += 1;
 3516                }
 3517            }
 3518            false
 3519        });
 3520    }
 3521
 3522    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3523        let offset = position.to_offset(buffer);
 3524        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3525        if offset > word_range.start && kind == Some(CharKind::Word) {
 3526            Some(
 3527                buffer
 3528                    .text_for_range(word_range.start..offset)
 3529                    .collect::<String>(),
 3530            )
 3531        } else {
 3532            None
 3533        }
 3534    }
 3535
 3536    pub fn toggle_inlay_hints(
 3537        &mut self,
 3538        _: &ToggleInlayHints,
 3539        _: &mut Window,
 3540        cx: &mut Context<Self>,
 3541    ) {
 3542        self.refresh_inlay_hints(
 3543            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3544            cx,
 3545        );
 3546    }
 3547
 3548    pub fn inlay_hints_enabled(&self) -> bool {
 3549        self.inlay_hint_cache.enabled
 3550    }
 3551
 3552    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3553        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3554            return;
 3555        }
 3556
 3557        let reason_description = reason.description();
 3558        let ignore_debounce = matches!(
 3559            reason,
 3560            InlayHintRefreshReason::SettingsChange(_)
 3561                | InlayHintRefreshReason::Toggle(_)
 3562                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3563        );
 3564        let (invalidate_cache, required_languages) = match reason {
 3565            InlayHintRefreshReason::Toggle(enabled) => {
 3566                self.inlay_hint_cache.enabled = enabled;
 3567                if enabled {
 3568                    (InvalidationStrategy::RefreshRequested, None)
 3569                } else {
 3570                    self.inlay_hint_cache.clear();
 3571                    self.splice_inlays(
 3572                        &self
 3573                            .visible_inlay_hints(cx)
 3574                            .iter()
 3575                            .map(|inlay| inlay.id)
 3576                            .collect::<Vec<InlayId>>(),
 3577                        Vec::new(),
 3578                        cx,
 3579                    );
 3580                    return;
 3581                }
 3582            }
 3583            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3584                match self.inlay_hint_cache.update_settings(
 3585                    &self.buffer,
 3586                    new_settings,
 3587                    self.visible_inlay_hints(cx),
 3588                    cx,
 3589                ) {
 3590                    ControlFlow::Break(Some(InlaySplice {
 3591                        to_remove,
 3592                        to_insert,
 3593                    })) => {
 3594                        self.splice_inlays(&to_remove, to_insert, cx);
 3595                        return;
 3596                    }
 3597                    ControlFlow::Break(None) => return,
 3598                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3599                }
 3600            }
 3601            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3602                if let Some(InlaySplice {
 3603                    to_remove,
 3604                    to_insert,
 3605                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3606                {
 3607                    self.splice_inlays(&to_remove, to_insert, cx);
 3608                }
 3609                return;
 3610            }
 3611            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3612            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3613                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3614            }
 3615            InlayHintRefreshReason::RefreshRequested => {
 3616                (InvalidationStrategy::RefreshRequested, None)
 3617            }
 3618        };
 3619
 3620        if let Some(InlaySplice {
 3621            to_remove,
 3622            to_insert,
 3623        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3624            reason_description,
 3625            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3626            invalidate_cache,
 3627            ignore_debounce,
 3628            cx,
 3629        ) {
 3630            self.splice_inlays(&to_remove, to_insert, cx);
 3631        }
 3632    }
 3633
 3634    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3635        self.display_map
 3636            .read(cx)
 3637            .current_inlays()
 3638            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3639            .cloned()
 3640            .collect()
 3641    }
 3642
 3643    pub fn excerpts_for_inlay_hints_query(
 3644        &self,
 3645        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3646        cx: &mut Context<Editor>,
 3647    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3648        let Some(project) = self.project.as_ref() else {
 3649            return HashMap::default();
 3650        };
 3651        let project = project.read(cx);
 3652        let multi_buffer = self.buffer().read(cx);
 3653        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3654        let multi_buffer_visible_start = self
 3655            .scroll_manager
 3656            .anchor()
 3657            .anchor
 3658            .to_point(&multi_buffer_snapshot);
 3659        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3660            multi_buffer_visible_start
 3661                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3662            Bias::Left,
 3663        );
 3664        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3665        multi_buffer_snapshot
 3666            .range_to_buffer_ranges(multi_buffer_visible_range)
 3667            .into_iter()
 3668            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3669            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3670                let buffer_file = project::File::from_dyn(buffer.file())?;
 3671                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3672                let worktree_entry = buffer_worktree
 3673                    .read(cx)
 3674                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3675                if worktree_entry.is_ignored {
 3676                    return None;
 3677                }
 3678
 3679                let language = buffer.language()?;
 3680                if let Some(restrict_to_languages) = restrict_to_languages {
 3681                    if !restrict_to_languages.contains(language) {
 3682                        return None;
 3683                    }
 3684                }
 3685                Some((
 3686                    excerpt_id,
 3687                    (
 3688                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3689                        buffer.version().clone(),
 3690                        excerpt_visible_range,
 3691                    ),
 3692                ))
 3693            })
 3694            .collect()
 3695    }
 3696
 3697    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3698        TextLayoutDetails {
 3699            text_system: window.text_system().clone(),
 3700            editor_style: self.style.clone().unwrap(),
 3701            rem_size: window.rem_size(),
 3702            scroll_anchor: self.scroll_manager.anchor(),
 3703            visible_rows: self.visible_line_count(),
 3704            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3705        }
 3706    }
 3707
 3708    pub fn splice_inlays(
 3709        &self,
 3710        to_remove: &[InlayId],
 3711        to_insert: Vec<Inlay>,
 3712        cx: &mut Context<Self>,
 3713    ) {
 3714        self.display_map.update(cx, |display_map, cx| {
 3715            display_map.splice_inlays(to_remove, to_insert, cx)
 3716        });
 3717        cx.notify();
 3718    }
 3719
 3720    fn trigger_on_type_formatting(
 3721        &self,
 3722        input: String,
 3723        window: &mut Window,
 3724        cx: &mut Context<Self>,
 3725    ) -> Option<Task<Result<()>>> {
 3726        if input.len() != 1 {
 3727            return None;
 3728        }
 3729
 3730        let project = self.project.as_ref()?;
 3731        let position = self.selections.newest_anchor().head();
 3732        let (buffer, buffer_position) = self
 3733            .buffer
 3734            .read(cx)
 3735            .text_anchor_for_position(position, cx)?;
 3736
 3737        let settings = language_settings::language_settings(
 3738            buffer
 3739                .read(cx)
 3740                .language_at(buffer_position)
 3741                .map(|l| l.name()),
 3742            buffer.read(cx).file(),
 3743            cx,
 3744        );
 3745        if !settings.use_on_type_format {
 3746            return None;
 3747        }
 3748
 3749        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3750        // hence we do LSP request & edit on host side only — add formats to host's history.
 3751        let push_to_lsp_host_history = true;
 3752        // If this is not the host, append its history with new edits.
 3753        let push_to_client_history = project.read(cx).is_via_collab();
 3754
 3755        let on_type_formatting = project.update(cx, |project, cx| {
 3756            project.on_type_format(
 3757                buffer.clone(),
 3758                buffer_position,
 3759                input,
 3760                push_to_lsp_host_history,
 3761                cx,
 3762            )
 3763        });
 3764        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3765            if let Some(transaction) = on_type_formatting.await? {
 3766                if push_to_client_history {
 3767                    buffer
 3768                        .update(&mut cx, |buffer, _| {
 3769                            buffer.push_transaction(transaction, Instant::now());
 3770                        })
 3771                        .ok();
 3772                }
 3773                editor.update(&mut cx, |editor, cx| {
 3774                    editor.refresh_document_highlights(cx);
 3775                })?;
 3776            }
 3777            Ok(())
 3778        }))
 3779    }
 3780
 3781    pub fn show_completions(
 3782        &mut self,
 3783        options: &ShowCompletions,
 3784        window: &mut Window,
 3785        cx: &mut Context<Self>,
 3786    ) {
 3787        if self.pending_rename.is_some() {
 3788            return;
 3789        }
 3790
 3791        let Some(provider) = self.completion_provider.as_ref() else {
 3792            return;
 3793        };
 3794
 3795        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3796            return;
 3797        }
 3798
 3799        let position = self.selections.newest_anchor().head();
 3800        if position.diff_base_anchor.is_some() {
 3801            return;
 3802        }
 3803        let (buffer, buffer_position) =
 3804            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3805                output
 3806            } else {
 3807                return;
 3808            };
 3809        let show_completion_documentation = buffer
 3810            .read(cx)
 3811            .snapshot()
 3812            .settings_at(buffer_position, cx)
 3813            .show_completion_documentation;
 3814
 3815        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3816
 3817        let trigger_kind = match &options.trigger {
 3818            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3819                CompletionTriggerKind::TRIGGER_CHARACTER
 3820            }
 3821            _ => CompletionTriggerKind::INVOKED,
 3822        };
 3823        let completion_context = CompletionContext {
 3824            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3825                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3826                    Some(String::from(trigger))
 3827                } else {
 3828                    None
 3829                }
 3830            }),
 3831            trigger_kind,
 3832        };
 3833        let completions =
 3834            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3835        let sort_completions = provider.sort_completions();
 3836
 3837        let id = post_inc(&mut self.next_completion_id);
 3838        let task = cx.spawn_in(window, |editor, mut cx| {
 3839            async move {
 3840                editor.update(&mut cx, |this, _| {
 3841                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3842                })?;
 3843                let completions = completions.await.log_err();
 3844                let menu = if let Some(completions) = completions {
 3845                    let mut menu = CompletionsMenu::new(
 3846                        id,
 3847                        sort_completions,
 3848                        show_completion_documentation,
 3849                        position,
 3850                        buffer.clone(),
 3851                        completions.into(),
 3852                    );
 3853
 3854                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3855                        .await;
 3856
 3857                    menu.visible().then_some(menu)
 3858                } else {
 3859                    None
 3860                };
 3861
 3862                editor.update_in(&mut cx, |editor, window, cx| {
 3863                    match editor.context_menu.borrow().as_ref() {
 3864                        None => {}
 3865                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3866                            if prev_menu.id > id {
 3867                                return;
 3868                            }
 3869                        }
 3870                        _ => return,
 3871                    }
 3872
 3873                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3874                        let mut menu = menu.unwrap();
 3875                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3876
 3877                        *editor.context_menu.borrow_mut() =
 3878                            Some(CodeContextMenu::Completions(menu));
 3879
 3880                        if editor.show_inline_completions_in_menu(cx) {
 3881                            editor.update_visible_inline_completion(window, cx);
 3882                        } else {
 3883                            editor.discard_inline_completion(false, cx);
 3884                        }
 3885
 3886                        cx.notify();
 3887                    } else if editor.completion_tasks.len() <= 1 {
 3888                        // If there are no more completion tasks and the last menu was
 3889                        // empty, we should hide it.
 3890                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3891                        // If it was already hidden and we don't show inline
 3892                        // completions in the menu, we should also show the
 3893                        // inline-completion when available.
 3894                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3895                            editor.update_visible_inline_completion(window, cx);
 3896                        }
 3897                    }
 3898                })?;
 3899
 3900                Ok::<_, anyhow::Error>(())
 3901            }
 3902            .log_err()
 3903        });
 3904
 3905        self.completion_tasks.push((id, task));
 3906    }
 3907
 3908    pub fn confirm_completion(
 3909        &mut self,
 3910        action: &ConfirmCompletion,
 3911        window: &mut Window,
 3912        cx: &mut Context<Self>,
 3913    ) -> Option<Task<Result<()>>> {
 3914        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3915    }
 3916
 3917    pub fn compose_completion(
 3918        &mut self,
 3919        action: &ComposeCompletion,
 3920        window: &mut Window,
 3921        cx: &mut Context<Self>,
 3922    ) -> Option<Task<Result<()>>> {
 3923        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3924    }
 3925
 3926    fn do_completion(
 3927        &mut self,
 3928        item_ix: Option<usize>,
 3929        intent: CompletionIntent,
 3930        window: &mut Window,
 3931        cx: &mut Context<Editor>,
 3932    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3933        use language::ToOffset as _;
 3934
 3935        let completions_menu =
 3936            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3937                menu
 3938            } else {
 3939                return None;
 3940            };
 3941
 3942        let entries = completions_menu.entries.borrow();
 3943        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3944        if self.show_inline_completions_in_menu(cx) {
 3945            self.discard_inline_completion(true, cx);
 3946        }
 3947        let candidate_id = mat.candidate_id;
 3948        drop(entries);
 3949
 3950        let buffer_handle = completions_menu.buffer;
 3951        let completion = completions_menu
 3952            .completions
 3953            .borrow()
 3954            .get(candidate_id)?
 3955            .clone();
 3956        cx.stop_propagation();
 3957
 3958        let snippet;
 3959        let text;
 3960
 3961        if completion.is_snippet() {
 3962            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3963            text = snippet.as_ref().unwrap().text.clone();
 3964        } else {
 3965            snippet = None;
 3966            text = completion.new_text.clone();
 3967        };
 3968        let selections = self.selections.all::<usize>(cx);
 3969        let buffer = buffer_handle.read(cx);
 3970        let old_range = completion.old_range.to_offset(buffer);
 3971        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3972
 3973        let newest_selection = self.selections.newest_anchor();
 3974        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3975            return None;
 3976        }
 3977
 3978        let lookbehind = newest_selection
 3979            .start
 3980            .text_anchor
 3981            .to_offset(buffer)
 3982            .saturating_sub(old_range.start);
 3983        let lookahead = old_range
 3984            .end
 3985            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3986        let mut common_prefix_len = old_text
 3987            .bytes()
 3988            .zip(text.bytes())
 3989            .take_while(|(a, b)| a == b)
 3990            .count();
 3991
 3992        let snapshot = self.buffer.read(cx).snapshot(cx);
 3993        let mut range_to_replace: Option<Range<isize>> = None;
 3994        let mut ranges = Vec::new();
 3995        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3996        for selection in &selections {
 3997            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3998                let start = selection.start.saturating_sub(lookbehind);
 3999                let end = selection.end + lookahead;
 4000                if selection.id == newest_selection.id {
 4001                    range_to_replace = Some(
 4002                        ((start + common_prefix_len) as isize - selection.start as isize)
 4003                            ..(end as isize - selection.start as isize),
 4004                    );
 4005                }
 4006                ranges.push(start + common_prefix_len..end);
 4007            } else {
 4008                common_prefix_len = 0;
 4009                ranges.clear();
 4010                ranges.extend(selections.iter().map(|s| {
 4011                    if s.id == newest_selection.id {
 4012                        range_to_replace = Some(
 4013                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4014                                - selection.start as isize
 4015                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4016                                    - selection.start as isize,
 4017                        );
 4018                        old_range.clone()
 4019                    } else {
 4020                        s.start..s.end
 4021                    }
 4022                }));
 4023                break;
 4024            }
 4025            if !self.linked_edit_ranges.is_empty() {
 4026                let start_anchor = snapshot.anchor_before(selection.head());
 4027                let end_anchor = snapshot.anchor_after(selection.tail());
 4028                if let Some(ranges) = self
 4029                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4030                {
 4031                    for (buffer, edits) in ranges {
 4032                        linked_edits.entry(buffer.clone()).or_default().extend(
 4033                            edits
 4034                                .into_iter()
 4035                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4036                        );
 4037                    }
 4038                }
 4039            }
 4040        }
 4041        let text = &text[common_prefix_len..];
 4042
 4043        cx.emit(EditorEvent::InputHandled {
 4044            utf16_range_to_replace: range_to_replace,
 4045            text: text.into(),
 4046        });
 4047
 4048        self.transact(window, cx, |this, window, cx| {
 4049            if let Some(mut snippet) = snippet {
 4050                snippet.text = text.to_string();
 4051                for tabstop in snippet
 4052                    .tabstops
 4053                    .iter_mut()
 4054                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4055                {
 4056                    tabstop.start -= common_prefix_len as isize;
 4057                    tabstop.end -= common_prefix_len as isize;
 4058                }
 4059
 4060                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4061            } else {
 4062                this.buffer.update(cx, |buffer, cx| {
 4063                    buffer.edit(
 4064                        ranges.iter().map(|range| (range.clone(), text)),
 4065                        this.autoindent_mode.clone(),
 4066                        cx,
 4067                    );
 4068                });
 4069            }
 4070            for (buffer, edits) in linked_edits {
 4071                buffer.update(cx, |buffer, cx| {
 4072                    let snapshot = buffer.snapshot();
 4073                    let edits = edits
 4074                        .into_iter()
 4075                        .map(|(range, text)| {
 4076                            use text::ToPoint as TP;
 4077                            let end_point = TP::to_point(&range.end, &snapshot);
 4078                            let start_point = TP::to_point(&range.start, &snapshot);
 4079                            (start_point..end_point, text)
 4080                        })
 4081                        .sorted_by_key(|(range, _)| range.start)
 4082                        .collect::<Vec<_>>();
 4083                    buffer.edit(edits, None, cx);
 4084                })
 4085            }
 4086
 4087            this.refresh_inline_completion(true, false, window, cx);
 4088        });
 4089
 4090        let show_new_completions_on_confirm = completion
 4091            .confirm
 4092            .as_ref()
 4093            .map_or(false, |confirm| confirm(intent, window, cx));
 4094        if show_new_completions_on_confirm {
 4095            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4096        }
 4097
 4098        let provider = self.completion_provider.as_ref()?;
 4099        drop(completion);
 4100        let apply_edits = provider.apply_additional_edits_for_completion(
 4101            buffer_handle,
 4102            completions_menu.completions.clone(),
 4103            candidate_id,
 4104            true,
 4105            cx,
 4106        );
 4107
 4108        let editor_settings = EditorSettings::get_global(cx);
 4109        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4110            // After the code completion is finished, users often want to know what signatures are needed.
 4111            // so we should automatically call signature_help
 4112            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4113        }
 4114
 4115        Some(cx.foreground_executor().spawn(async move {
 4116            apply_edits.await?;
 4117            Ok(())
 4118        }))
 4119    }
 4120
 4121    pub fn toggle_code_actions(
 4122        &mut self,
 4123        action: &ToggleCodeActions,
 4124        window: &mut Window,
 4125        cx: &mut Context<Self>,
 4126    ) {
 4127        let mut context_menu = self.context_menu.borrow_mut();
 4128        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4129            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4130                // Toggle if we're selecting the same one
 4131                *context_menu = None;
 4132                cx.notify();
 4133                return;
 4134            } else {
 4135                // Otherwise, clear it and start a new one
 4136                *context_menu = None;
 4137                cx.notify();
 4138            }
 4139        }
 4140        drop(context_menu);
 4141        let snapshot = self.snapshot(window, cx);
 4142        let deployed_from_indicator = action.deployed_from_indicator;
 4143        let mut task = self.code_actions_task.take();
 4144        let action = action.clone();
 4145        cx.spawn_in(window, |editor, mut cx| async move {
 4146            while let Some(prev_task) = task {
 4147                prev_task.await.log_err();
 4148                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4149            }
 4150
 4151            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4152                if editor.focus_handle.is_focused(window) {
 4153                    let multibuffer_point = action
 4154                        .deployed_from_indicator
 4155                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4156                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4157                    let (buffer, buffer_row) = snapshot
 4158                        .buffer_snapshot
 4159                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4160                        .and_then(|(buffer_snapshot, range)| {
 4161                            editor
 4162                                .buffer
 4163                                .read(cx)
 4164                                .buffer(buffer_snapshot.remote_id())
 4165                                .map(|buffer| (buffer, range.start.row))
 4166                        })?;
 4167                    let (_, code_actions) = editor
 4168                        .available_code_actions
 4169                        .clone()
 4170                        .and_then(|(location, code_actions)| {
 4171                            let snapshot = location.buffer.read(cx).snapshot();
 4172                            let point_range = location.range.to_point(&snapshot);
 4173                            let point_range = point_range.start.row..=point_range.end.row;
 4174                            if point_range.contains(&buffer_row) {
 4175                                Some((location, code_actions))
 4176                            } else {
 4177                                None
 4178                            }
 4179                        })
 4180                        .unzip();
 4181                    let buffer_id = buffer.read(cx).remote_id();
 4182                    let tasks = editor
 4183                        .tasks
 4184                        .get(&(buffer_id, buffer_row))
 4185                        .map(|t| Arc::new(t.to_owned()));
 4186                    if tasks.is_none() && code_actions.is_none() {
 4187                        return None;
 4188                    }
 4189
 4190                    editor.completion_tasks.clear();
 4191                    editor.discard_inline_completion(false, cx);
 4192                    let task_context =
 4193                        tasks
 4194                            .as_ref()
 4195                            .zip(editor.project.clone())
 4196                            .map(|(tasks, project)| {
 4197                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4198                            });
 4199
 4200                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4201                        let task_context = match task_context {
 4202                            Some(task_context) => task_context.await,
 4203                            None => None,
 4204                        };
 4205                        let resolved_tasks =
 4206                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4207                                Rc::new(ResolvedTasks {
 4208                                    templates: tasks.resolve(&task_context).collect(),
 4209                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4210                                        multibuffer_point.row,
 4211                                        tasks.column,
 4212                                    )),
 4213                                })
 4214                            });
 4215                        let spawn_straight_away = resolved_tasks
 4216                            .as_ref()
 4217                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4218                            && code_actions
 4219                                .as_ref()
 4220                                .map_or(true, |actions| actions.is_empty());
 4221                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4222                            *editor.context_menu.borrow_mut() =
 4223                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4224                                    buffer,
 4225                                    actions: CodeActionContents {
 4226                                        tasks: resolved_tasks,
 4227                                        actions: code_actions,
 4228                                    },
 4229                                    selected_item: Default::default(),
 4230                                    scroll_handle: UniformListScrollHandle::default(),
 4231                                    deployed_from_indicator,
 4232                                }));
 4233                            if spawn_straight_away {
 4234                                if let Some(task) = editor.confirm_code_action(
 4235                                    &ConfirmCodeAction { item_ix: Some(0) },
 4236                                    window,
 4237                                    cx,
 4238                                ) {
 4239                                    cx.notify();
 4240                                    return task;
 4241                                }
 4242                            }
 4243                            cx.notify();
 4244                            Task::ready(Ok(()))
 4245                        }) {
 4246                            task.await
 4247                        } else {
 4248                            Ok(())
 4249                        }
 4250                    }))
 4251                } else {
 4252                    Some(Task::ready(Ok(())))
 4253                }
 4254            })?;
 4255            if let Some(task) = spawned_test_task {
 4256                task.await?;
 4257            }
 4258
 4259            Ok::<_, anyhow::Error>(())
 4260        })
 4261        .detach_and_log_err(cx);
 4262    }
 4263
 4264    pub fn confirm_code_action(
 4265        &mut self,
 4266        action: &ConfirmCodeAction,
 4267        window: &mut Window,
 4268        cx: &mut Context<Self>,
 4269    ) -> Option<Task<Result<()>>> {
 4270        let actions_menu =
 4271            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4272                menu
 4273            } else {
 4274                return None;
 4275            };
 4276        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4277        let action = actions_menu.actions.get(action_ix)?;
 4278        let title = action.label();
 4279        let buffer = actions_menu.buffer;
 4280        let workspace = self.workspace()?;
 4281
 4282        match action {
 4283            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4284                workspace.update(cx, |workspace, cx| {
 4285                    workspace::tasks::schedule_resolved_task(
 4286                        workspace,
 4287                        task_source_kind,
 4288                        resolved_task,
 4289                        false,
 4290                        cx,
 4291                    );
 4292
 4293                    Some(Task::ready(Ok(())))
 4294                })
 4295            }
 4296            CodeActionsItem::CodeAction {
 4297                excerpt_id,
 4298                action,
 4299                provider,
 4300            } => {
 4301                let apply_code_action =
 4302                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4303                let workspace = workspace.downgrade();
 4304                Some(cx.spawn_in(window, |editor, cx| async move {
 4305                    let project_transaction = apply_code_action.await?;
 4306                    Self::open_project_transaction(
 4307                        &editor,
 4308                        workspace,
 4309                        project_transaction,
 4310                        title,
 4311                        cx,
 4312                    )
 4313                    .await
 4314                }))
 4315            }
 4316        }
 4317    }
 4318
 4319    pub async fn open_project_transaction(
 4320        this: &WeakEntity<Editor>,
 4321        workspace: WeakEntity<Workspace>,
 4322        transaction: ProjectTransaction,
 4323        title: String,
 4324        mut cx: AsyncWindowContext,
 4325    ) -> Result<()> {
 4326        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4327        cx.update(|_, cx| {
 4328            entries.sort_unstable_by_key(|(buffer, _)| {
 4329                buffer.read(cx).file().map(|f| f.path().clone())
 4330            });
 4331        })?;
 4332
 4333        // If the project transaction's edits are all contained within this editor, then
 4334        // avoid opening a new editor to display them.
 4335
 4336        if let Some((buffer, transaction)) = entries.first() {
 4337            if entries.len() == 1 {
 4338                let excerpt = this.update(&mut cx, |editor, cx| {
 4339                    editor
 4340                        .buffer()
 4341                        .read(cx)
 4342                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4343                })?;
 4344                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4345                    if excerpted_buffer == *buffer {
 4346                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4347                            let excerpt_range = excerpt_range.to_offset(buffer);
 4348                            buffer
 4349                                .edited_ranges_for_transaction::<usize>(transaction)
 4350                                .all(|range| {
 4351                                    excerpt_range.start <= range.start
 4352                                        && excerpt_range.end >= range.end
 4353                                })
 4354                        })?;
 4355
 4356                        if all_edits_within_excerpt {
 4357                            return Ok(());
 4358                        }
 4359                    }
 4360                }
 4361            }
 4362        } else {
 4363            return Ok(());
 4364        }
 4365
 4366        let mut ranges_to_highlight = Vec::new();
 4367        let excerpt_buffer = cx.new(|cx| {
 4368            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4369            for (buffer_handle, transaction) in &entries {
 4370                let buffer = buffer_handle.read(cx);
 4371                ranges_to_highlight.extend(
 4372                    multibuffer.push_excerpts_with_context_lines(
 4373                        buffer_handle.clone(),
 4374                        buffer
 4375                            .edited_ranges_for_transaction::<usize>(transaction)
 4376                            .collect(),
 4377                        DEFAULT_MULTIBUFFER_CONTEXT,
 4378                        cx,
 4379                    ),
 4380                );
 4381            }
 4382            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4383            multibuffer
 4384        })?;
 4385
 4386        workspace.update_in(&mut cx, |workspace, window, cx| {
 4387            let project = workspace.project().clone();
 4388            let editor = cx
 4389                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4390            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4391            editor.update(cx, |editor, cx| {
 4392                editor.highlight_background::<Self>(
 4393                    &ranges_to_highlight,
 4394                    |theme| theme.editor_highlighted_line_background,
 4395                    cx,
 4396                );
 4397            });
 4398        })?;
 4399
 4400        Ok(())
 4401    }
 4402
 4403    pub fn clear_code_action_providers(&mut self) {
 4404        self.code_action_providers.clear();
 4405        self.available_code_actions.take();
 4406    }
 4407
 4408    pub fn add_code_action_provider(
 4409        &mut self,
 4410        provider: Rc<dyn CodeActionProvider>,
 4411        window: &mut Window,
 4412        cx: &mut Context<Self>,
 4413    ) {
 4414        if self
 4415            .code_action_providers
 4416            .iter()
 4417            .any(|existing_provider| existing_provider.id() == provider.id())
 4418        {
 4419            return;
 4420        }
 4421
 4422        self.code_action_providers.push(provider);
 4423        self.refresh_code_actions(window, cx);
 4424    }
 4425
 4426    pub fn remove_code_action_provider(
 4427        &mut self,
 4428        id: Arc<str>,
 4429        window: &mut Window,
 4430        cx: &mut Context<Self>,
 4431    ) {
 4432        self.code_action_providers
 4433            .retain(|provider| provider.id() != id);
 4434        self.refresh_code_actions(window, cx);
 4435    }
 4436
 4437    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4438        let buffer = self.buffer.read(cx);
 4439        let newest_selection = self.selections.newest_anchor().clone();
 4440        if newest_selection.head().diff_base_anchor.is_some() {
 4441            return None;
 4442        }
 4443        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4444        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4445        if start_buffer != end_buffer {
 4446            return None;
 4447        }
 4448
 4449        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4450            cx.background_executor()
 4451                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4452                .await;
 4453
 4454            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4455                let providers = this.code_action_providers.clone();
 4456                let tasks = this
 4457                    .code_action_providers
 4458                    .iter()
 4459                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4460                    .collect::<Vec<_>>();
 4461                (providers, tasks)
 4462            })?;
 4463
 4464            let mut actions = Vec::new();
 4465            for (provider, provider_actions) in
 4466                providers.into_iter().zip(future::join_all(tasks).await)
 4467            {
 4468                if let Some(provider_actions) = provider_actions.log_err() {
 4469                    actions.extend(provider_actions.into_iter().map(|action| {
 4470                        AvailableCodeAction {
 4471                            excerpt_id: newest_selection.start.excerpt_id,
 4472                            action,
 4473                            provider: provider.clone(),
 4474                        }
 4475                    }));
 4476                }
 4477            }
 4478
 4479            this.update(&mut cx, |this, cx| {
 4480                this.available_code_actions = if actions.is_empty() {
 4481                    None
 4482                } else {
 4483                    Some((
 4484                        Location {
 4485                            buffer: start_buffer,
 4486                            range: start..end,
 4487                        },
 4488                        actions.into(),
 4489                    ))
 4490                };
 4491                cx.notify();
 4492            })
 4493        }));
 4494        None
 4495    }
 4496
 4497    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4498        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4499            self.show_git_blame_inline = false;
 4500
 4501            self.show_git_blame_inline_delay_task =
 4502                Some(cx.spawn_in(window, |this, mut cx| async move {
 4503                    cx.background_executor().timer(delay).await;
 4504
 4505                    this.update(&mut cx, |this, cx| {
 4506                        this.show_git_blame_inline = true;
 4507                        cx.notify();
 4508                    })
 4509                    .log_err();
 4510                }));
 4511        }
 4512    }
 4513
 4514    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4515        if self.pending_rename.is_some() {
 4516            return None;
 4517        }
 4518
 4519        let provider = self.semantics_provider.clone()?;
 4520        let buffer = self.buffer.read(cx);
 4521        let newest_selection = self.selections.newest_anchor().clone();
 4522        let cursor_position = newest_selection.head();
 4523        let (cursor_buffer, cursor_buffer_position) =
 4524            buffer.text_anchor_for_position(cursor_position, cx)?;
 4525        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4526        if cursor_buffer != tail_buffer {
 4527            return None;
 4528        }
 4529        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4530        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4531            cx.background_executor()
 4532                .timer(Duration::from_millis(debounce))
 4533                .await;
 4534
 4535            let highlights = if let Some(highlights) = cx
 4536                .update(|cx| {
 4537                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4538                })
 4539                .ok()
 4540                .flatten()
 4541            {
 4542                highlights.await.log_err()
 4543            } else {
 4544                None
 4545            };
 4546
 4547            if let Some(highlights) = highlights {
 4548                this.update(&mut cx, |this, cx| {
 4549                    if this.pending_rename.is_some() {
 4550                        return;
 4551                    }
 4552
 4553                    let buffer_id = cursor_position.buffer_id;
 4554                    let buffer = this.buffer.read(cx);
 4555                    if !buffer
 4556                        .text_anchor_for_position(cursor_position, cx)
 4557                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4558                    {
 4559                        return;
 4560                    }
 4561
 4562                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4563                    let mut write_ranges = Vec::new();
 4564                    let mut read_ranges = Vec::new();
 4565                    for highlight in highlights {
 4566                        for (excerpt_id, excerpt_range) in
 4567                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4568                        {
 4569                            let start = highlight
 4570                                .range
 4571                                .start
 4572                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4573                            let end = highlight
 4574                                .range
 4575                                .end
 4576                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4577                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4578                                continue;
 4579                            }
 4580
 4581                            let range = Anchor {
 4582                                buffer_id,
 4583                                excerpt_id,
 4584                                text_anchor: start,
 4585                                diff_base_anchor: None,
 4586                            }..Anchor {
 4587                                buffer_id,
 4588                                excerpt_id,
 4589                                text_anchor: end,
 4590                                diff_base_anchor: None,
 4591                            };
 4592                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4593                                write_ranges.push(range);
 4594                            } else {
 4595                                read_ranges.push(range);
 4596                            }
 4597                        }
 4598                    }
 4599
 4600                    this.highlight_background::<DocumentHighlightRead>(
 4601                        &read_ranges,
 4602                        |theme| theme.editor_document_highlight_read_background,
 4603                        cx,
 4604                    );
 4605                    this.highlight_background::<DocumentHighlightWrite>(
 4606                        &write_ranges,
 4607                        |theme| theme.editor_document_highlight_write_background,
 4608                        cx,
 4609                    );
 4610                    cx.notify();
 4611                })
 4612                .log_err();
 4613            }
 4614        }));
 4615        None
 4616    }
 4617
 4618    pub fn refresh_inline_completion(
 4619        &mut self,
 4620        debounce: bool,
 4621        user_requested: bool,
 4622        window: &mut Window,
 4623        cx: &mut Context<Self>,
 4624    ) -> Option<()> {
 4625        let provider = self.inline_completion_provider()?;
 4626        let cursor = self.selections.newest_anchor().head();
 4627        let (buffer, cursor_buffer_position) =
 4628            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4629
 4630        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4631            self.discard_inline_completion(false, cx);
 4632            return None;
 4633        }
 4634
 4635        if !user_requested
 4636            && (!self.show_inline_completions
 4637                || !self.should_show_inline_completions_in_buffer(
 4638                    &buffer,
 4639                    cursor_buffer_position,
 4640                    cx,
 4641                )
 4642                || !self.is_focused(window)
 4643                || buffer.read(cx).is_empty())
 4644        {
 4645            self.discard_inline_completion(false, cx);
 4646            return None;
 4647        }
 4648
 4649        self.update_visible_inline_completion(window, cx);
 4650        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4651        Some(())
 4652    }
 4653
 4654    pub fn should_show_inline_completions(&self, cx: &App) -> bool {
 4655        let cursor = self.selections.newest_anchor().head();
 4656        if let Some((buffer, cursor_position)) =
 4657            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4658        {
 4659            self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
 4660        } else {
 4661            false
 4662        }
 4663    }
 4664
 4665    fn should_show_inline_completions_in_buffer(
 4666        &self,
 4667        buffer: &Entity<Buffer>,
 4668        buffer_position: language::Anchor,
 4669        cx: &App,
 4670    ) -> bool {
 4671        if !self.snippet_stack.is_empty() {
 4672            return false;
 4673        }
 4674
 4675        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 4676            return false;
 4677        }
 4678
 4679        if let Some(show_inline_completions) = self.show_inline_completions_override {
 4680            show_inline_completions
 4681        } else {
 4682            let buffer = buffer.read(cx);
 4683            self.mode == EditorMode::Full
 4684                && language_settings(
 4685                    buffer.language_at(buffer_position).map(|l| l.name()),
 4686                    buffer.file(),
 4687                    cx,
 4688                )
 4689                .show_inline_completions
 4690        }
 4691    }
 4692
 4693    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4694        let cursor = self.selections.newest_anchor().head();
 4695        if let Some((buffer, cursor_position)) =
 4696            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4697        {
 4698            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4699        } else {
 4700            false
 4701        }
 4702    }
 4703
 4704    fn inline_completions_enabled_in_buffer(
 4705        &self,
 4706        buffer: &Entity<Buffer>,
 4707        buffer_position: language::Anchor,
 4708        cx: &App,
 4709    ) -> bool {
 4710        maybe!({
 4711            let provider = self.inline_completion_provider()?;
 4712            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4713                return Some(false);
 4714            }
 4715            let buffer = buffer.read(cx);
 4716            let Some(file) = buffer.file() else {
 4717                return Some(true);
 4718            };
 4719            let settings = all_language_settings(Some(file), cx);
 4720            Some(settings.inline_completions_enabled_for_path(file.path()))
 4721        })
 4722        .unwrap_or(false)
 4723    }
 4724
 4725    fn cycle_inline_completion(
 4726        &mut self,
 4727        direction: Direction,
 4728        window: &mut Window,
 4729        cx: &mut Context<Self>,
 4730    ) -> Option<()> {
 4731        let provider = self.inline_completion_provider()?;
 4732        let cursor = self.selections.newest_anchor().head();
 4733        let (buffer, cursor_buffer_position) =
 4734            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4735        if !self.show_inline_completions
 4736            || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4737        {
 4738            return None;
 4739        }
 4740
 4741        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4742        self.update_visible_inline_completion(window, cx);
 4743
 4744        Some(())
 4745    }
 4746
 4747    pub fn show_inline_completion(
 4748        &mut self,
 4749        _: &ShowInlineCompletion,
 4750        window: &mut Window,
 4751        cx: &mut Context<Self>,
 4752    ) {
 4753        if !self.has_active_inline_completion() {
 4754            self.refresh_inline_completion(false, true, window, cx);
 4755            return;
 4756        }
 4757
 4758        self.update_visible_inline_completion(window, cx);
 4759    }
 4760
 4761    pub fn display_cursor_names(
 4762        &mut self,
 4763        _: &DisplayCursorNames,
 4764        window: &mut Window,
 4765        cx: &mut Context<Self>,
 4766    ) {
 4767        self.show_cursor_names(window, cx);
 4768    }
 4769
 4770    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4771        self.show_cursor_names = true;
 4772        cx.notify();
 4773        cx.spawn_in(window, |this, mut cx| async move {
 4774            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4775            this.update(&mut cx, |this, cx| {
 4776                this.show_cursor_names = false;
 4777                cx.notify()
 4778            })
 4779            .ok()
 4780        })
 4781        .detach();
 4782    }
 4783
 4784    pub fn next_inline_completion(
 4785        &mut self,
 4786        _: &NextInlineCompletion,
 4787        window: &mut Window,
 4788        cx: &mut Context<Self>,
 4789    ) {
 4790        if self.has_active_inline_completion() {
 4791            self.cycle_inline_completion(Direction::Next, window, cx);
 4792        } else {
 4793            let is_copilot_disabled = self
 4794                .refresh_inline_completion(false, true, window, cx)
 4795                .is_none();
 4796            if is_copilot_disabled {
 4797                cx.propagate();
 4798            }
 4799        }
 4800    }
 4801
 4802    pub fn previous_inline_completion(
 4803        &mut self,
 4804        _: &PreviousInlineCompletion,
 4805        window: &mut Window,
 4806        cx: &mut Context<Self>,
 4807    ) {
 4808        if self.has_active_inline_completion() {
 4809            self.cycle_inline_completion(Direction::Prev, window, cx);
 4810        } else {
 4811            let is_copilot_disabled = self
 4812                .refresh_inline_completion(false, true, window, cx)
 4813                .is_none();
 4814            if is_copilot_disabled {
 4815                cx.propagate();
 4816            }
 4817        }
 4818    }
 4819
 4820    pub fn accept_inline_completion(
 4821        &mut self,
 4822        _: &AcceptInlineCompletion,
 4823        window: &mut Window,
 4824        cx: &mut Context<Self>,
 4825    ) {
 4826        let buffer = self.buffer.read(cx);
 4827        let snapshot = buffer.snapshot(cx);
 4828        let selection = self.selections.newest_adjusted(cx);
 4829        let cursor = selection.head();
 4830        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4831        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4832        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4833        {
 4834            if cursor.column < suggested_indent.len
 4835                && cursor.column <= current_indent.len
 4836                && current_indent.len <= suggested_indent.len
 4837            {
 4838                self.tab(&Default::default(), window, cx);
 4839                return;
 4840            }
 4841        }
 4842
 4843        if self.show_inline_completions_in_menu(cx) {
 4844            self.hide_context_menu(window, cx);
 4845        }
 4846
 4847        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4848            return;
 4849        };
 4850
 4851        self.report_inline_completion_event(true, cx);
 4852
 4853        match &active_inline_completion.completion {
 4854            InlineCompletion::Move { target, .. } => {
 4855                let target = *target;
 4856                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4857                    selections.select_anchor_ranges([target..target]);
 4858                });
 4859            }
 4860            InlineCompletion::Edit { edits, .. } => {
 4861                if let Some(provider) = self.inline_completion_provider() {
 4862                    provider.accept(cx);
 4863                }
 4864
 4865                let snapshot = self.buffer.read(cx).snapshot(cx);
 4866                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4867
 4868                self.buffer.update(cx, |buffer, cx| {
 4869                    buffer.edit(edits.iter().cloned(), None, cx)
 4870                });
 4871
 4872                self.change_selections(None, window, cx, |s| {
 4873                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4874                });
 4875
 4876                self.update_visible_inline_completion(window, cx);
 4877                if self.active_inline_completion.is_none() {
 4878                    self.refresh_inline_completion(true, true, window, cx);
 4879                }
 4880
 4881                cx.notify();
 4882            }
 4883        }
 4884    }
 4885
 4886    pub fn accept_partial_inline_completion(
 4887        &mut self,
 4888        _: &AcceptPartialInlineCompletion,
 4889        window: &mut Window,
 4890        cx: &mut Context<Self>,
 4891    ) {
 4892        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4893            return;
 4894        };
 4895        if self.selections.count() != 1 {
 4896            return;
 4897        }
 4898
 4899        self.report_inline_completion_event(true, cx);
 4900
 4901        match &active_inline_completion.completion {
 4902            InlineCompletion::Move { target, .. } => {
 4903                let target = *target;
 4904                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4905                    selections.select_anchor_ranges([target..target]);
 4906                });
 4907            }
 4908            InlineCompletion::Edit { edits, .. } => {
 4909                // Find an insertion that starts at the cursor position.
 4910                let snapshot = self.buffer.read(cx).snapshot(cx);
 4911                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4912                let insertion = edits.iter().find_map(|(range, text)| {
 4913                    let range = range.to_offset(&snapshot);
 4914                    if range.is_empty() && range.start == cursor_offset {
 4915                        Some(text)
 4916                    } else {
 4917                        None
 4918                    }
 4919                });
 4920
 4921                if let Some(text) = insertion {
 4922                    let mut partial_completion = text
 4923                        .chars()
 4924                        .by_ref()
 4925                        .take_while(|c| c.is_alphabetic())
 4926                        .collect::<String>();
 4927                    if partial_completion.is_empty() {
 4928                        partial_completion = text
 4929                            .chars()
 4930                            .by_ref()
 4931                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4932                            .collect::<String>();
 4933                    }
 4934
 4935                    cx.emit(EditorEvent::InputHandled {
 4936                        utf16_range_to_replace: None,
 4937                        text: partial_completion.clone().into(),
 4938                    });
 4939
 4940                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4941
 4942                    self.refresh_inline_completion(true, true, window, cx);
 4943                    cx.notify();
 4944                } else {
 4945                    self.accept_inline_completion(&Default::default(), window, cx);
 4946                }
 4947            }
 4948        }
 4949    }
 4950
 4951    fn discard_inline_completion(
 4952        &mut self,
 4953        should_report_inline_completion_event: bool,
 4954        cx: &mut Context<Self>,
 4955    ) -> bool {
 4956        if should_report_inline_completion_event {
 4957            self.report_inline_completion_event(false, cx);
 4958        }
 4959
 4960        if let Some(provider) = self.inline_completion_provider() {
 4961            provider.discard(cx);
 4962        }
 4963
 4964        self.take_active_inline_completion(cx)
 4965    }
 4966
 4967    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4968        let Some(provider) = self.inline_completion_provider() else {
 4969            return;
 4970        };
 4971
 4972        let Some((_, buffer, _)) = self
 4973            .buffer
 4974            .read(cx)
 4975            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4976        else {
 4977            return;
 4978        };
 4979
 4980        let extension = buffer
 4981            .read(cx)
 4982            .file()
 4983            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4984
 4985        let event_type = match accepted {
 4986            true => "Edit Prediction Accepted",
 4987            false => "Edit Prediction Discarded",
 4988        };
 4989        telemetry::event!(
 4990            event_type,
 4991            provider = provider.name(),
 4992            suggestion_accepted = accepted,
 4993            file_extension = extension,
 4994        );
 4995    }
 4996
 4997    pub fn has_active_inline_completion(&self) -> bool {
 4998        self.active_inline_completion.is_some()
 4999    }
 5000
 5001    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5002        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5003            return false;
 5004        };
 5005
 5006        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5007        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5008        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5009        true
 5010    }
 5011
 5012    pub fn is_previewing_inline_completion(&self) -> bool {
 5013        matches!(
 5014            self.context_menu.borrow().as_ref(),
 5015            Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
 5016        )
 5017    }
 5018
 5019    fn update_inline_completion_preview(
 5020        &mut self,
 5021        modifiers: &Modifiers,
 5022        window: &mut Window,
 5023        cx: &mut Context<Self>,
 5024    ) {
 5025        // Moves jump directly with a preview step
 5026
 5027        if self
 5028            .active_inline_completion
 5029            .as_ref()
 5030            .map_or(true, |c| c.is_move())
 5031        {
 5032            cx.notify();
 5033            return;
 5034        }
 5035
 5036        if !self.show_inline_completions_in_menu(cx) {
 5037            return;
 5038        }
 5039
 5040        let mut menu_borrow = self.context_menu.borrow_mut();
 5041
 5042        let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
 5043            return;
 5044        };
 5045
 5046        if completions_menu.is_empty()
 5047            || completions_menu.previewing_inline_completion == modifiers.alt
 5048        {
 5049            return;
 5050        }
 5051
 5052        completions_menu.set_previewing_inline_completion(modifiers.alt);
 5053        drop(menu_borrow);
 5054        self.update_visible_inline_completion(window, cx);
 5055    }
 5056
 5057    fn update_visible_inline_completion(
 5058        &mut self,
 5059        _window: &mut Window,
 5060        cx: &mut Context<Self>,
 5061    ) -> Option<()> {
 5062        let selection = self.selections.newest_anchor();
 5063        let cursor = selection.head();
 5064        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5065        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5066        let excerpt_id = cursor.excerpt_id;
 5067
 5068        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5069        let completions_menu_has_precedence = !show_in_menu
 5070            && (self.context_menu.borrow().is_some()
 5071                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5072        if completions_menu_has_precedence
 5073            || !offset_selection.is_empty()
 5074            || !self.show_inline_completions
 5075            || self
 5076                .active_inline_completion
 5077                .as_ref()
 5078                .map_or(false, |completion| {
 5079                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5080                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5081                    !invalidation_range.contains(&offset_selection.head())
 5082                })
 5083        {
 5084            self.discard_inline_completion(false, cx);
 5085            return None;
 5086        }
 5087
 5088        self.take_active_inline_completion(cx);
 5089        let provider = self.inline_completion_provider()?;
 5090
 5091        let (buffer, cursor_buffer_position) =
 5092            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5093
 5094        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5095        let edits = inline_completion
 5096            .edits
 5097            .into_iter()
 5098            .flat_map(|(range, new_text)| {
 5099                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5100                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5101                Some((start..end, new_text))
 5102            })
 5103            .collect::<Vec<_>>();
 5104        if edits.is_empty() {
 5105            return None;
 5106        }
 5107
 5108        let first_edit_start = edits.first().unwrap().0.start;
 5109        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5110        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5111
 5112        let last_edit_end = edits.last().unwrap().0.end;
 5113        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5114        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5115
 5116        let cursor_row = cursor.to_point(&multibuffer).row;
 5117
 5118        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5119
 5120        let mut inlay_ids = Vec::new();
 5121        let invalidation_row_range;
 5122        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5123            Some(cursor_row..edit_end_row)
 5124        } else if cursor_row > edit_end_row {
 5125            Some(edit_start_row..cursor_row)
 5126        } else {
 5127            None
 5128        };
 5129        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5130            invalidation_row_range = move_invalidation_row_range;
 5131            let target = first_edit_start;
 5132            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5133            // TODO: Base this off of TreeSitter or word boundaries?
 5134            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5135                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5136                Bias::Left,
 5137            ));
 5138            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5139                Point::new(target_point.row, target_point.column + 20),
 5140                Bias::Right,
 5141            ));
 5142            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5143            InlineCompletion::Move {
 5144                target,
 5145                range_around_target,
 5146                snapshot,
 5147            }
 5148        } else {
 5149            if !show_in_menu || !self.has_active_completions_menu() {
 5150                if edits
 5151                    .iter()
 5152                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5153                {
 5154                    let mut inlays = Vec::new();
 5155                    for (range, new_text) in &edits {
 5156                        let inlay = Inlay::inline_completion(
 5157                            post_inc(&mut self.next_inlay_id),
 5158                            range.start,
 5159                            new_text.as_str(),
 5160                        );
 5161                        inlay_ids.push(inlay.id);
 5162                        inlays.push(inlay);
 5163                    }
 5164
 5165                    self.splice_inlays(&[], inlays, cx);
 5166                } else {
 5167                    let background_color = cx.theme().status().deleted_background;
 5168                    self.highlight_text::<InlineCompletionHighlight>(
 5169                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5170                        HighlightStyle {
 5171                            background_color: Some(background_color),
 5172                            ..Default::default()
 5173                        },
 5174                        cx,
 5175                    );
 5176                }
 5177            }
 5178
 5179            invalidation_row_range = edit_start_row..edit_end_row;
 5180
 5181            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5182                if provider.show_tab_accept_marker() {
 5183                    EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
 5184                } else {
 5185                    EditDisplayMode::Inline
 5186                }
 5187            } else {
 5188                EditDisplayMode::DiffPopover
 5189            };
 5190
 5191            InlineCompletion::Edit {
 5192                edits,
 5193                edit_preview: inline_completion.edit_preview,
 5194                display_mode,
 5195                snapshot,
 5196            }
 5197        };
 5198
 5199        let invalidation_range = multibuffer
 5200            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5201            ..multibuffer.anchor_after(Point::new(
 5202                invalidation_row_range.end,
 5203                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5204            ));
 5205
 5206        self.stale_inline_completion_in_menu = None;
 5207        self.active_inline_completion = Some(InlineCompletionState {
 5208            inlay_ids,
 5209            completion,
 5210            invalidation_range,
 5211        });
 5212
 5213        cx.notify();
 5214
 5215        Some(())
 5216    }
 5217
 5218    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5219        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5220    }
 5221
 5222    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5223        let by_provider = matches!(
 5224            self.menu_inline_completions_policy,
 5225            MenuInlineCompletionsPolicy::ByProvider
 5226        );
 5227
 5228        by_provider
 5229            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5230            && self
 5231                .inline_completion_provider()
 5232                .map_or(false, |provider| provider.show_completions_in_menu())
 5233    }
 5234
 5235    fn render_code_actions_indicator(
 5236        &self,
 5237        _style: &EditorStyle,
 5238        row: DisplayRow,
 5239        is_active: bool,
 5240        cx: &mut Context<Self>,
 5241    ) -> Option<IconButton> {
 5242        if self.available_code_actions.is_some() {
 5243            Some(
 5244                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5245                    .shape(ui::IconButtonShape::Square)
 5246                    .icon_size(IconSize::XSmall)
 5247                    .icon_color(Color::Muted)
 5248                    .toggle_state(is_active)
 5249                    .tooltip({
 5250                        let focus_handle = self.focus_handle.clone();
 5251                        move |window, cx| {
 5252                            Tooltip::for_action_in(
 5253                                "Toggle Code Actions",
 5254                                &ToggleCodeActions {
 5255                                    deployed_from_indicator: None,
 5256                                },
 5257                                &focus_handle,
 5258                                window,
 5259                                cx,
 5260                            )
 5261                        }
 5262                    })
 5263                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5264                        window.focus(&editor.focus_handle(cx));
 5265                        editor.toggle_code_actions(
 5266                            &ToggleCodeActions {
 5267                                deployed_from_indicator: Some(row),
 5268                            },
 5269                            window,
 5270                            cx,
 5271                        );
 5272                    })),
 5273            )
 5274        } else {
 5275            None
 5276        }
 5277    }
 5278
 5279    fn clear_tasks(&mut self) {
 5280        self.tasks.clear()
 5281    }
 5282
 5283    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5284        if self.tasks.insert(key, value).is_some() {
 5285            // This case should hopefully be rare, but just in case...
 5286            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5287        }
 5288    }
 5289
 5290    fn build_tasks_context(
 5291        project: &Entity<Project>,
 5292        buffer: &Entity<Buffer>,
 5293        buffer_row: u32,
 5294        tasks: &Arc<RunnableTasks>,
 5295        cx: &mut Context<Self>,
 5296    ) -> Task<Option<task::TaskContext>> {
 5297        let position = Point::new(buffer_row, tasks.column);
 5298        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5299        let location = Location {
 5300            buffer: buffer.clone(),
 5301            range: range_start..range_start,
 5302        };
 5303        // Fill in the environmental variables from the tree-sitter captures
 5304        let mut captured_task_variables = TaskVariables::default();
 5305        for (capture_name, value) in tasks.extra_variables.clone() {
 5306            captured_task_variables.insert(
 5307                task::VariableName::Custom(capture_name.into()),
 5308                value.clone(),
 5309            );
 5310        }
 5311        project.update(cx, |project, cx| {
 5312            project.task_store().update(cx, |task_store, cx| {
 5313                task_store.task_context_for_location(captured_task_variables, location, cx)
 5314            })
 5315        })
 5316    }
 5317
 5318    pub fn spawn_nearest_task(
 5319        &mut self,
 5320        action: &SpawnNearestTask,
 5321        window: &mut Window,
 5322        cx: &mut Context<Self>,
 5323    ) {
 5324        let Some((workspace, _)) = self.workspace.clone() else {
 5325            return;
 5326        };
 5327        let Some(project) = self.project.clone() else {
 5328            return;
 5329        };
 5330
 5331        // Try to find a closest, enclosing node using tree-sitter that has a
 5332        // task
 5333        let Some((buffer, buffer_row, tasks)) = self
 5334            .find_enclosing_node_task(cx)
 5335            // Or find the task that's closest in row-distance.
 5336            .or_else(|| self.find_closest_task(cx))
 5337        else {
 5338            return;
 5339        };
 5340
 5341        let reveal_strategy = action.reveal;
 5342        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5343        cx.spawn_in(window, |_, mut cx| async move {
 5344            let context = task_context.await?;
 5345            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5346
 5347            let resolved = resolved_task.resolved.as_mut()?;
 5348            resolved.reveal = reveal_strategy;
 5349
 5350            workspace
 5351                .update(&mut cx, |workspace, cx| {
 5352                    workspace::tasks::schedule_resolved_task(
 5353                        workspace,
 5354                        task_source_kind,
 5355                        resolved_task,
 5356                        false,
 5357                        cx,
 5358                    );
 5359                })
 5360                .ok()
 5361        })
 5362        .detach();
 5363    }
 5364
 5365    fn find_closest_task(
 5366        &mut self,
 5367        cx: &mut Context<Self>,
 5368    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5369        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5370
 5371        let ((buffer_id, row), tasks) = self
 5372            .tasks
 5373            .iter()
 5374            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5375
 5376        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5377        let tasks = Arc::new(tasks.to_owned());
 5378        Some((buffer, *row, tasks))
 5379    }
 5380
 5381    fn find_enclosing_node_task(
 5382        &mut self,
 5383        cx: &mut Context<Self>,
 5384    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5385        let snapshot = self.buffer.read(cx).snapshot(cx);
 5386        let offset = self.selections.newest::<usize>(cx).head();
 5387        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5388        let buffer_id = excerpt.buffer().remote_id();
 5389
 5390        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5391        let mut cursor = layer.node().walk();
 5392
 5393        while cursor.goto_first_child_for_byte(offset).is_some() {
 5394            if cursor.node().end_byte() == offset {
 5395                cursor.goto_next_sibling();
 5396            }
 5397        }
 5398
 5399        // Ascend to the smallest ancestor that contains the range and has a task.
 5400        loop {
 5401            let node = cursor.node();
 5402            let node_range = node.byte_range();
 5403            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5404
 5405            // Check if this node contains our offset
 5406            if node_range.start <= offset && node_range.end >= offset {
 5407                // If it contains offset, check for task
 5408                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5409                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5410                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5411                }
 5412            }
 5413
 5414            if !cursor.goto_parent() {
 5415                break;
 5416            }
 5417        }
 5418        None
 5419    }
 5420
 5421    fn render_run_indicator(
 5422        &self,
 5423        _style: &EditorStyle,
 5424        is_active: bool,
 5425        row: DisplayRow,
 5426        cx: &mut Context<Self>,
 5427    ) -> IconButton {
 5428        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5429            .shape(ui::IconButtonShape::Square)
 5430            .icon_size(IconSize::XSmall)
 5431            .icon_color(Color::Muted)
 5432            .toggle_state(is_active)
 5433            .on_click(cx.listener(move |editor, _e, window, cx| {
 5434                window.focus(&editor.focus_handle(cx));
 5435                editor.toggle_code_actions(
 5436                    &ToggleCodeActions {
 5437                        deployed_from_indicator: Some(row),
 5438                    },
 5439                    window,
 5440                    cx,
 5441                );
 5442            }))
 5443    }
 5444
 5445    pub fn context_menu_visible(&self) -> bool {
 5446        self.context_menu
 5447            .borrow()
 5448            .as_ref()
 5449            .map_or(false, |menu| menu.visible())
 5450    }
 5451
 5452    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5453        self.context_menu
 5454            .borrow()
 5455            .as_ref()
 5456            .map(|menu| menu.origin())
 5457    }
 5458
 5459    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5460        px(32.)
 5461    }
 5462
 5463    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5464        if self.read_only(cx) {
 5465            cx.theme().players().read_only()
 5466        } else {
 5467            self.style.as_ref().unwrap().local_player
 5468        }
 5469    }
 5470
 5471    #[allow(clippy::too_many_arguments)]
 5472    fn render_edit_prediction_cursor_popover(
 5473        &self,
 5474        min_width: Pixels,
 5475        max_width: Pixels,
 5476        cursor_point: Point,
 5477        start_row: DisplayRow,
 5478        line_layouts: &[LineWithInvisibles],
 5479        style: &EditorStyle,
 5480        accept_keystroke: &gpui::Keystroke,
 5481        window: &Window,
 5482        cx: &mut Context<Editor>,
 5483    ) -> Option<AnyElement> {
 5484        let provider = self.inline_completion_provider.as_ref()?;
 5485
 5486        if provider.provider.needs_terms_acceptance(cx) {
 5487            return Some(
 5488                h_flex()
 5489                    .h(self.edit_prediction_cursor_popover_height())
 5490                    .min_w(min_width)
 5491                    .flex_1()
 5492                    .px_2()
 5493                    .gap_3()
 5494                    .elevation_2(cx)
 5495                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5496                    .id("accept-terms")
 5497                    .cursor_pointer()
 5498                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5499                    .on_click(cx.listener(|this, _event, window, cx| {
 5500                        cx.stop_propagation();
 5501                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5502                        window.dispatch_action(
 5503                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5504                            cx,
 5505                        );
 5506                    }))
 5507                    .child(
 5508                        h_flex()
 5509                            .w_full()
 5510                            .gap_2()
 5511                            .child(Icon::new(IconName::ZedPredict))
 5512                            .child(Label::new("Accept Terms of Service"))
 5513                            .child(div().w_full())
 5514                            .child(Icon::new(IconName::ArrowUpRight))
 5515                            .into_any_element(),
 5516                    )
 5517                    .into_any(),
 5518            );
 5519        }
 5520
 5521        let is_refreshing = provider.provider.is_refreshing(cx);
 5522
 5523        fn pending_completion_container() -> Div {
 5524            h_flex()
 5525                .flex_1()
 5526                .gap_3()
 5527                .child(Icon::new(IconName::ZedPredict))
 5528        }
 5529
 5530        let completion = match &self.active_inline_completion {
 5531            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5532                completion,
 5533                cursor_point,
 5534                start_row,
 5535                line_layouts,
 5536                style,
 5537                cx,
 5538            )?,
 5539
 5540            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5541                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5542                    stale_completion,
 5543                    cursor_point,
 5544                    start_row,
 5545                    line_layouts,
 5546                    style,
 5547                    cx,
 5548                )?,
 5549
 5550                None => {
 5551                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5552                }
 5553            },
 5554
 5555            None => pending_completion_container().child(Label::new("No Prediction")),
 5556        };
 5557
 5558        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5559        let completion = completion.font(buffer_font.clone());
 5560
 5561        let completion = if is_refreshing {
 5562            completion
 5563                .with_animation(
 5564                    "loading-completion",
 5565                    Animation::new(Duration::from_secs(2))
 5566                        .repeat()
 5567                        .with_easing(pulsating_between(0.4, 0.8)),
 5568                    |label, delta| label.opacity(delta),
 5569                )
 5570                .into_any_element()
 5571        } else {
 5572            completion.into_any_element()
 5573        };
 5574
 5575        let has_completion = self.active_inline_completion.is_some();
 5576
 5577        let is_move = self
 5578            .active_inline_completion
 5579            .as_ref()
 5580            .map_or(false, |c| c.is_move());
 5581
 5582        Some(
 5583            h_flex()
 5584                .h(self.edit_prediction_cursor_popover_height())
 5585                .min_w(min_width)
 5586                .max_w(max_width)
 5587                .flex_1()
 5588                .px_2()
 5589                .gap_3()
 5590                .elevation_2(cx)
 5591                .child(completion)
 5592                .child(
 5593                    h_flex()
 5594                        .border_l_1()
 5595                        .border_color(cx.theme().colors().border_variant)
 5596                        .pl_2()
 5597                        .child(
 5598                            h_flex()
 5599                                .font(buffer_font.clone())
 5600                                .p_1()
 5601                                .rounded_sm()
 5602                                .children(ui::render_modifiers(
 5603                                    &accept_keystroke.modifiers,
 5604                                    PlatformStyle::platform(),
 5605                                    if window.modifiers() == accept_keystroke.modifiers {
 5606                                        Some(Color::Accent)
 5607                                    } else {
 5608                                        None
 5609                                    },
 5610                                    !is_move,
 5611                                )),
 5612                        )
 5613                        .opacity(if has_completion { 1.0 } else { 0.1 })
 5614                        .child(if is_move {
 5615                            div()
 5616                                .child(ui::Key::new(&accept_keystroke.key, None))
 5617                                .font(buffer_font.clone())
 5618                                .into_any()
 5619                        } else {
 5620                            Label::new("Preview").color(Color::Muted).into_any_element()
 5621                        }),
 5622                )
 5623                .into_any(),
 5624        )
 5625    }
 5626
 5627    fn render_edit_prediction_cursor_popover_preview(
 5628        &self,
 5629        completion: &InlineCompletionState,
 5630        cursor_point: Point,
 5631        start_row: DisplayRow,
 5632        line_layouts: &[LineWithInvisibles],
 5633        style: &EditorStyle,
 5634        cx: &mut Context<Editor>,
 5635    ) -> Option<Div> {
 5636        use text::ToPoint as _;
 5637
 5638        fn render_relative_row_jump(
 5639            prefix: impl Into<String>,
 5640            current_row: u32,
 5641            target_row: u32,
 5642        ) -> Div {
 5643            let (row_diff, arrow) = if target_row < current_row {
 5644                (current_row - target_row, IconName::ArrowUp)
 5645            } else {
 5646                (target_row - current_row, IconName::ArrowDown)
 5647            };
 5648
 5649            h_flex()
 5650                .child(
 5651                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5652                        .color(Color::Muted)
 5653                        .size(LabelSize::Small),
 5654                )
 5655                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5656        }
 5657
 5658        match &completion.completion {
 5659            InlineCompletion::Edit {
 5660                edits,
 5661                edit_preview,
 5662                snapshot,
 5663                display_mode: _,
 5664            } => {
 5665                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5666
 5667                let highlighted_edits = crate::inline_completion_edit_text(
 5668                    &snapshot,
 5669                    &edits,
 5670                    edit_preview.as_ref()?,
 5671                    true,
 5672                    cx,
 5673                );
 5674
 5675                let len_total = highlighted_edits.text.len();
 5676                let first_line = &highlighted_edits.text
 5677                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5678                let first_line_len = first_line.len();
 5679
 5680                let first_highlight_start = highlighted_edits
 5681                    .highlights
 5682                    .first()
 5683                    .map_or(0, |(range, _)| range.start);
 5684                let drop_prefix_len = first_line
 5685                    .char_indices()
 5686                    .find(|(_, c)| !c.is_whitespace())
 5687                    .map_or(first_highlight_start, |(ix, _)| {
 5688                        ix.min(first_highlight_start)
 5689                    });
 5690
 5691                let preview_text = &first_line[drop_prefix_len..];
 5692                let preview_len = preview_text.len();
 5693                let highlights = highlighted_edits
 5694                    .highlights
 5695                    .into_iter()
 5696                    .take_until(|(range, _)| range.start > first_line_len)
 5697                    .map(|(range, style)| {
 5698                        (
 5699                            range.start - drop_prefix_len
 5700                                ..(range.end - drop_prefix_len).min(preview_len),
 5701                            style,
 5702                        )
 5703                    });
 5704
 5705                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5706                    .with_highlights(&style.text, highlights);
 5707
 5708                let preview = h_flex()
 5709                    .gap_1()
 5710                    .child(styled_text)
 5711                    .when(len_total > first_line_len, |parent| parent.child(""));
 5712
 5713                let left = if first_edit_row != cursor_point.row {
 5714                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5715                        .into_any_element()
 5716                } else {
 5717                    Icon::new(IconName::ZedPredict).into_any_element()
 5718                };
 5719
 5720                Some(h_flex().flex_1().gap_3().child(left).child(preview))
 5721            }
 5722
 5723            InlineCompletion::Move {
 5724                target,
 5725                range_around_target,
 5726                snapshot,
 5727            } => {
 5728                let highlighted_text = snapshot.highlighted_text_for_range(
 5729                    range_around_target.clone(),
 5730                    None,
 5731                    &style.syntax,
 5732                );
 5733                let cursor_color = self.current_user_player_color(cx).cursor;
 5734
 5735                let start_point = range_around_target.start.to_point(&snapshot);
 5736                let end_point = range_around_target.end.to_point(&snapshot);
 5737                let target_point = target.text_anchor.to_point(&snapshot);
 5738
 5739                let cursor_relative_position = line_layouts
 5740                    .get(start_point.row.saturating_sub(start_row.0) as usize)
 5741                    .map(|line| {
 5742                        let start_column_x = line.x_for_index(start_point.column as usize);
 5743                        let target_column_x = line.x_for_index(target_point.column as usize);
 5744                        target_column_x - start_column_x
 5745                    });
 5746
 5747                let fade_before = start_point.column > 0;
 5748                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5749
 5750                let background = cx.theme().colors().elevated_surface_background;
 5751
 5752                Some(
 5753                    h_flex()
 5754                        .gap_3()
 5755                        .flex_1()
 5756                        .child(render_relative_row_jump(
 5757                            "Jump ",
 5758                            cursor_point.row,
 5759                            target.text_anchor.to_point(&snapshot).row,
 5760                        ))
 5761                        .when(!highlighted_text.text.is_empty(), |parent| {
 5762                            parent.child(
 5763                                h_flex()
 5764                                    .relative()
 5765                                    .child(highlighted_text.to_styled_text(&style.text))
 5766                                    .when(fade_before, |parent| {
 5767                                        parent.child(
 5768                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5769                                                linear_gradient(
 5770                                                    90.,
 5771                                                    linear_color_stop(background, 0.),
 5772                                                    linear_color_stop(background.opacity(0.), 1.),
 5773                                                ),
 5774                                            ),
 5775                                        )
 5776                                    })
 5777                                    .when(fade_after, |parent| {
 5778                                        parent.child(
 5779                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5780                                                linear_gradient(
 5781                                                    -90.,
 5782                                                    linear_color_stop(background, 0.),
 5783                                                    linear_color_stop(background.opacity(0.), 1.),
 5784                                                ),
 5785                                            ),
 5786                                        )
 5787                                    })
 5788                                    .when_some(cursor_relative_position, |parent, position| {
 5789                                        parent.child(
 5790                                            div()
 5791                                                .w(px(2.))
 5792                                                .h_full()
 5793                                                .bg(cursor_color)
 5794                                                .absolute()
 5795                                                .top_0()
 5796                                                .left(position),
 5797                                        )
 5798                                    }),
 5799                            )
 5800                        }),
 5801                )
 5802            }
 5803        }
 5804    }
 5805
 5806    fn render_context_menu(
 5807        &self,
 5808        style: &EditorStyle,
 5809        max_height_in_lines: u32,
 5810        y_flipped: bool,
 5811        window: &mut Window,
 5812        cx: &mut Context<Editor>,
 5813    ) -> Option<AnyElement> {
 5814        let menu = self.context_menu.borrow();
 5815        let menu = menu.as_ref()?;
 5816        if !menu.visible() {
 5817            return None;
 5818        };
 5819        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5820    }
 5821
 5822    fn render_context_menu_aside(
 5823        &self,
 5824        style: &EditorStyle,
 5825        max_size: Size<Pixels>,
 5826        cx: &mut Context<Editor>,
 5827    ) -> Option<AnyElement> {
 5828        self.context_menu.borrow().as_ref().and_then(|menu| {
 5829            if menu.visible() {
 5830                menu.render_aside(
 5831                    style,
 5832                    max_size,
 5833                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5834                    cx,
 5835                )
 5836            } else {
 5837                None
 5838            }
 5839        })
 5840    }
 5841
 5842    fn hide_context_menu(
 5843        &mut self,
 5844        window: &mut Window,
 5845        cx: &mut Context<Self>,
 5846    ) -> Option<CodeContextMenu> {
 5847        cx.notify();
 5848        self.completion_tasks.clear();
 5849        let context_menu = self.context_menu.borrow_mut().take();
 5850        self.stale_inline_completion_in_menu.take();
 5851        if context_menu.is_some() {
 5852            self.update_visible_inline_completion(window, cx);
 5853        }
 5854        context_menu
 5855    }
 5856
 5857    fn show_snippet_choices(
 5858        &mut self,
 5859        choices: &Vec<String>,
 5860        selection: Range<Anchor>,
 5861        cx: &mut Context<Self>,
 5862    ) {
 5863        if selection.start.buffer_id.is_none() {
 5864            return;
 5865        }
 5866        let buffer_id = selection.start.buffer_id.unwrap();
 5867        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5868        let id = post_inc(&mut self.next_completion_id);
 5869
 5870        if let Some(buffer) = buffer {
 5871            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5872                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5873            ));
 5874        }
 5875    }
 5876
 5877    pub fn insert_snippet(
 5878        &mut self,
 5879        insertion_ranges: &[Range<usize>],
 5880        snippet: Snippet,
 5881        window: &mut Window,
 5882        cx: &mut Context<Self>,
 5883    ) -> Result<()> {
 5884        struct Tabstop<T> {
 5885            is_end_tabstop: bool,
 5886            ranges: Vec<Range<T>>,
 5887            choices: Option<Vec<String>>,
 5888        }
 5889
 5890        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5891            let snippet_text: Arc<str> = snippet.text.clone().into();
 5892            buffer.edit(
 5893                insertion_ranges
 5894                    .iter()
 5895                    .cloned()
 5896                    .map(|range| (range, snippet_text.clone())),
 5897                Some(AutoindentMode::EachLine),
 5898                cx,
 5899            );
 5900
 5901            let snapshot = &*buffer.read(cx);
 5902            let snippet = &snippet;
 5903            snippet
 5904                .tabstops
 5905                .iter()
 5906                .map(|tabstop| {
 5907                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5908                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5909                    });
 5910                    let mut tabstop_ranges = tabstop
 5911                        .ranges
 5912                        .iter()
 5913                        .flat_map(|tabstop_range| {
 5914                            let mut delta = 0_isize;
 5915                            insertion_ranges.iter().map(move |insertion_range| {
 5916                                let insertion_start = insertion_range.start as isize + delta;
 5917                                delta +=
 5918                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5919
 5920                                let start = ((insertion_start + tabstop_range.start) as usize)
 5921                                    .min(snapshot.len());
 5922                                let end = ((insertion_start + tabstop_range.end) as usize)
 5923                                    .min(snapshot.len());
 5924                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5925                            })
 5926                        })
 5927                        .collect::<Vec<_>>();
 5928                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5929
 5930                    Tabstop {
 5931                        is_end_tabstop,
 5932                        ranges: tabstop_ranges,
 5933                        choices: tabstop.choices.clone(),
 5934                    }
 5935                })
 5936                .collect::<Vec<_>>()
 5937        });
 5938        if let Some(tabstop) = tabstops.first() {
 5939            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5940                s.select_ranges(tabstop.ranges.iter().cloned());
 5941            });
 5942
 5943            if let Some(choices) = &tabstop.choices {
 5944                if let Some(selection) = tabstop.ranges.first() {
 5945                    self.show_snippet_choices(choices, selection.clone(), cx)
 5946                }
 5947            }
 5948
 5949            // If we're already at the last tabstop and it's at the end of the snippet,
 5950            // we're done, we don't need to keep the state around.
 5951            if !tabstop.is_end_tabstop {
 5952                let choices = tabstops
 5953                    .iter()
 5954                    .map(|tabstop| tabstop.choices.clone())
 5955                    .collect();
 5956
 5957                let ranges = tabstops
 5958                    .into_iter()
 5959                    .map(|tabstop| tabstop.ranges)
 5960                    .collect::<Vec<_>>();
 5961
 5962                self.snippet_stack.push(SnippetState {
 5963                    active_index: 0,
 5964                    ranges,
 5965                    choices,
 5966                });
 5967            }
 5968
 5969            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5970            if self.autoclose_regions.is_empty() {
 5971                let snapshot = self.buffer.read(cx).snapshot(cx);
 5972                for selection in &mut self.selections.all::<Point>(cx) {
 5973                    let selection_head = selection.head();
 5974                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5975                        continue;
 5976                    };
 5977
 5978                    let mut bracket_pair = None;
 5979                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5980                    let prev_chars = snapshot
 5981                        .reversed_chars_at(selection_head)
 5982                        .collect::<String>();
 5983                    for (pair, enabled) in scope.brackets() {
 5984                        if enabled
 5985                            && pair.close
 5986                            && prev_chars.starts_with(pair.start.as_str())
 5987                            && next_chars.starts_with(pair.end.as_str())
 5988                        {
 5989                            bracket_pair = Some(pair.clone());
 5990                            break;
 5991                        }
 5992                    }
 5993                    if let Some(pair) = bracket_pair {
 5994                        let start = snapshot.anchor_after(selection_head);
 5995                        let end = snapshot.anchor_after(selection_head);
 5996                        self.autoclose_regions.push(AutocloseRegion {
 5997                            selection_id: selection.id,
 5998                            range: start..end,
 5999                            pair,
 6000                        });
 6001                    }
 6002                }
 6003            }
 6004        }
 6005        Ok(())
 6006    }
 6007
 6008    pub fn move_to_next_snippet_tabstop(
 6009        &mut self,
 6010        window: &mut Window,
 6011        cx: &mut Context<Self>,
 6012    ) -> bool {
 6013        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6014    }
 6015
 6016    pub fn move_to_prev_snippet_tabstop(
 6017        &mut self,
 6018        window: &mut Window,
 6019        cx: &mut Context<Self>,
 6020    ) -> bool {
 6021        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6022    }
 6023
 6024    pub fn move_to_snippet_tabstop(
 6025        &mut self,
 6026        bias: Bias,
 6027        window: &mut Window,
 6028        cx: &mut Context<Self>,
 6029    ) -> bool {
 6030        if let Some(mut snippet) = self.snippet_stack.pop() {
 6031            match bias {
 6032                Bias::Left => {
 6033                    if snippet.active_index > 0 {
 6034                        snippet.active_index -= 1;
 6035                    } else {
 6036                        self.snippet_stack.push(snippet);
 6037                        return false;
 6038                    }
 6039                }
 6040                Bias::Right => {
 6041                    if snippet.active_index + 1 < snippet.ranges.len() {
 6042                        snippet.active_index += 1;
 6043                    } else {
 6044                        self.snippet_stack.push(snippet);
 6045                        return false;
 6046                    }
 6047                }
 6048            }
 6049            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6050                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6051                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6052                });
 6053
 6054                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6055                    if let Some(selection) = current_ranges.first() {
 6056                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6057                    }
 6058                }
 6059
 6060                // If snippet state is not at the last tabstop, push it back on the stack
 6061                if snippet.active_index + 1 < snippet.ranges.len() {
 6062                    self.snippet_stack.push(snippet);
 6063                }
 6064                return true;
 6065            }
 6066        }
 6067
 6068        false
 6069    }
 6070
 6071    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6072        self.transact(window, cx, |this, window, cx| {
 6073            this.select_all(&SelectAll, window, cx);
 6074            this.insert("", window, cx);
 6075        });
 6076    }
 6077
 6078    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6079        self.transact(window, cx, |this, window, cx| {
 6080            this.select_autoclose_pair(window, cx);
 6081            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6082            if !this.linked_edit_ranges.is_empty() {
 6083                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6084                let snapshot = this.buffer.read(cx).snapshot(cx);
 6085
 6086                for selection in selections.iter() {
 6087                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6088                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6089                    if selection_start.buffer_id != selection_end.buffer_id {
 6090                        continue;
 6091                    }
 6092                    if let Some(ranges) =
 6093                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6094                    {
 6095                        for (buffer, entries) in ranges {
 6096                            linked_ranges.entry(buffer).or_default().extend(entries);
 6097                        }
 6098                    }
 6099                }
 6100            }
 6101
 6102            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6103            if !this.selections.line_mode {
 6104                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6105                for selection in &mut selections {
 6106                    if selection.is_empty() {
 6107                        let old_head = selection.head();
 6108                        let mut new_head =
 6109                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6110                                .to_point(&display_map);
 6111                        if let Some((buffer, line_buffer_range)) = display_map
 6112                            .buffer_snapshot
 6113                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6114                        {
 6115                            let indent_size =
 6116                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6117                            let indent_len = match indent_size.kind {
 6118                                IndentKind::Space => {
 6119                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6120                                }
 6121                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6122                            };
 6123                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6124                                let indent_len = indent_len.get();
 6125                                new_head = cmp::min(
 6126                                    new_head,
 6127                                    MultiBufferPoint::new(
 6128                                        old_head.row,
 6129                                        ((old_head.column - 1) / indent_len) * indent_len,
 6130                                    ),
 6131                                );
 6132                            }
 6133                        }
 6134
 6135                        selection.set_head(new_head, SelectionGoal::None);
 6136                    }
 6137                }
 6138            }
 6139
 6140            this.signature_help_state.set_backspace_pressed(true);
 6141            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6142                s.select(selections)
 6143            });
 6144            this.insert("", window, cx);
 6145            let empty_str: Arc<str> = Arc::from("");
 6146            for (buffer, edits) in linked_ranges {
 6147                let snapshot = buffer.read(cx).snapshot();
 6148                use text::ToPoint as TP;
 6149
 6150                let edits = edits
 6151                    .into_iter()
 6152                    .map(|range| {
 6153                        let end_point = TP::to_point(&range.end, &snapshot);
 6154                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6155
 6156                        if end_point == start_point {
 6157                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6158                                .saturating_sub(1);
 6159                            start_point =
 6160                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6161                        };
 6162
 6163                        (start_point..end_point, empty_str.clone())
 6164                    })
 6165                    .sorted_by_key(|(range, _)| range.start)
 6166                    .collect::<Vec<_>>();
 6167                buffer.update(cx, |this, cx| {
 6168                    this.edit(edits, None, cx);
 6169                })
 6170            }
 6171            this.refresh_inline_completion(true, false, window, cx);
 6172            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6173        });
 6174    }
 6175
 6176    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6177        self.transact(window, cx, |this, window, cx| {
 6178            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6179                let line_mode = s.line_mode;
 6180                s.move_with(|map, selection| {
 6181                    if selection.is_empty() && !line_mode {
 6182                        let cursor = movement::right(map, selection.head());
 6183                        selection.end = cursor;
 6184                        selection.reversed = true;
 6185                        selection.goal = SelectionGoal::None;
 6186                    }
 6187                })
 6188            });
 6189            this.insert("", window, cx);
 6190            this.refresh_inline_completion(true, false, window, cx);
 6191        });
 6192    }
 6193
 6194    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6195        if self.move_to_prev_snippet_tabstop(window, cx) {
 6196            return;
 6197        }
 6198
 6199        self.outdent(&Outdent, window, cx);
 6200    }
 6201
 6202    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6203        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6204            return;
 6205        }
 6206
 6207        let mut selections = self.selections.all_adjusted(cx);
 6208        let buffer = self.buffer.read(cx);
 6209        let snapshot = buffer.snapshot(cx);
 6210        let rows_iter = selections.iter().map(|s| s.head().row);
 6211        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6212
 6213        let mut edits = Vec::new();
 6214        let mut prev_edited_row = 0;
 6215        let mut row_delta = 0;
 6216        for selection in &mut selections {
 6217            if selection.start.row != prev_edited_row {
 6218                row_delta = 0;
 6219            }
 6220            prev_edited_row = selection.end.row;
 6221
 6222            // If the selection is non-empty, then increase the indentation of the selected lines.
 6223            if !selection.is_empty() {
 6224                row_delta =
 6225                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6226                continue;
 6227            }
 6228
 6229            // If the selection is empty and the cursor is in the leading whitespace before the
 6230            // suggested indentation, then auto-indent the line.
 6231            let cursor = selection.head();
 6232            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6233            if let Some(suggested_indent) =
 6234                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6235            {
 6236                if cursor.column < suggested_indent.len
 6237                    && cursor.column <= current_indent.len
 6238                    && current_indent.len <= suggested_indent.len
 6239                {
 6240                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6241                    selection.end = selection.start;
 6242                    if row_delta == 0 {
 6243                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6244                            cursor.row,
 6245                            current_indent,
 6246                            suggested_indent,
 6247                        ));
 6248                        row_delta = suggested_indent.len - current_indent.len;
 6249                    }
 6250                    continue;
 6251                }
 6252            }
 6253
 6254            // Otherwise, insert a hard or soft tab.
 6255            let settings = buffer.settings_at(cursor, cx);
 6256            let tab_size = if settings.hard_tabs {
 6257                IndentSize::tab()
 6258            } else {
 6259                let tab_size = settings.tab_size.get();
 6260                let char_column = snapshot
 6261                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6262                    .flat_map(str::chars)
 6263                    .count()
 6264                    + row_delta as usize;
 6265                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6266                IndentSize::spaces(chars_to_next_tab_stop)
 6267            };
 6268            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6269            selection.end = selection.start;
 6270            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6271            row_delta += tab_size.len;
 6272        }
 6273
 6274        self.transact(window, cx, |this, window, cx| {
 6275            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6276            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6277                s.select(selections)
 6278            });
 6279            this.refresh_inline_completion(true, false, window, cx);
 6280        });
 6281    }
 6282
 6283    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6284        if self.read_only(cx) {
 6285            return;
 6286        }
 6287        let mut selections = self.selections.all::<Point>(cx);
 6288        let mut prev_edited_row = 0;
 6289        let mut row_delta = 0;
 6290        let mut edits = Vec::new();
 6291        let buffer = self.buffer.read(cx);
 6292        let snapshot = buffer.snapshot(cx);
 6293        for selection in &mut selections {
 6294            if selection.start.row != prev_edited_row {
 6295                row_delta = 0;
 6296            }
 6297            prev_edited_row = selection.end.row;
 6298
 6299            row_delta =
 6300                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6301        }
 6302
 6303        self.transact(window, cx, |this, window, cx| {
 6304            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6305            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6306                s.select(selections)
 6307            });
 6308        });
 6309    }
 6310
 6311    fn indent_selection(
 6312        buffer: &MultiBuffer,
 6313        snapshot: &MultiBufferSnapshot,
 6314        selection: &mut Selection<Point>,
 6315        edits: &mut Vec<(Range<Point>, String)>,
 6316        delta_for_start_row: u32,
 6317        cx: &App,
 6318    ) -> u32 {
 6319        let settings = buffer.settings_at(selection.start, cx);
 6320        let tab_size = settings.tab_size.get();
 6321        let indent_kind = if settings.hard_tabs {
 6322            IndentKind::Tab
 6323        } else {
 6324            IndentKind::Space
 6325        };
 6326        let mut start_row = selection.start.row;
 6327        let mut end_row = selection.end.row + 1;
 6328
 6329        // If a selection ends at the beginning of a line, don't indent
 6330        // that last line.
 6331        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6332            end_row -= 1;
 6333        }
 6334
 6335        // Avoid re-indenting a row that has already been indented by a
 6336        // previous selection, but still update this selection's column
 6337        // to reflect that indentation.
 6338        if delta_for_start_row > 0 {
 6339            start_row += 1;
 6340            selection.start.column += delta_for_start_row;
 6341            if selection.end.row == selection.start.row {
 6342                selection.end.column += delta_for_start_row;
 6343            }
 6344        }
 6345
 6346        let mut delta_for_end_row = 0;
 6347        let has_multiple_rows = start_row + 1 != end_row;
 6348        for row in start_row..end_row {
 6349            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6350            let indent_delta = match (current_indent.kind, indent_kind) {
 6351                (IndentKind::Space, IndentKind::Space) => {
 6352                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6353                    IndentSize::spaces(columns_to_next_tab_stop)
 6354                }
 6355                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6356                (_, IndentKind::Tab) => IndentSize::tab(),
 6357            };
 6358
 6359            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6360                0
 6361            } else {
 6362                selection.start.column
 6363            };
 6364            let row_start = Point::new(row, start);
 6365            edits.push((
 6366                row_start..row_start,
 6367                indent_delta.chars().collect::<String>(),
 6368            ));
 6369
 6370            // Update this selection's endpoints to reflect the indentation.
 6371            if row == selection.start.row {
 6372                selection.start.column += indent_delta.len;
 6373            }
 6374            if row == selection.end.row {
 6375                selection.end.column += indent_delta.len;
 6376                delta_for_end_row = indent_delta.len;
 6377            }
 6378        }
 6379
 6380        if selection.start.row == selection.end.row {
 6381            delta_for_start_row + delta_for_end_row
 6382        } else {
 6383            delta_for_end_row
 6384        }
 6385    }
 6386
 6387    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6388        if self.read_only(cx) {
 6389            return;
 6390        }
 6391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6392        let selections = self.selections.all::<Point>(cx);
 6393        let mut deletion_ranges = Vec::new();
 6394        let mut last_outdent = None;
 6395        {
 6396            let buffer = self.buffer.read(cx);
 6397            let snapshot = buffer.snapshot(cx);
 6398            for selection in &selections {
 6399                let settings = buffer.settings_at(selection.start, cx);
 6400                let tab_size = settings.tab_size.get();
 6401                let mut rows = selection.spanned_rows(false, &display_map);
 6402
 6403                // Avoid re-outdenting a row that has already been outdented by a
 6404                // previous selection.
 6405                if let Some(last_row) = last_outdent {
 6406                    if last_row == rows.start {
 6407                        rows.start = rows.start.next_row();
 6408                    }
 6409                }
 6410                let has_multiple_rows = rows.len() > 1;
 6411                for row in rows.iter_rows() {
 6412                    let indent_size = snapshot.indent_size_for_line(row);
 6413                    if indent_size.len > 0 {
 6414                        let deletion_len = match indent_size.kind {
 6415                            IndentKind::Space => {
 6416                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6417                                if columns_to_prev_tab_stop == 0 {
 6418                                    tab_size
 6419                                } else {
 6420                                    columns_to_prev_tab_stop
 6421                                }
 6422                            }
 6423                            IndentKind::Tab => 1,
 6424                        };
 6425                        let start = if has_multiple_rows
 6426                            || deletion_len > selection.start.column
 6427                            || indent_size.len < selection.start.column
 6428                        {
 6429                            0
 6430                        } else {
 6431                            selection.start.column - deletion_len
 6432                        };
 6433                        deletion_ranges.push(
 6434                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6435                        );
 6436                        last_outdent = Some(row);
 6437                    }
 6438                }
 6439            }
 6440        }
 6441
 6442        self.transact(window, cx, |this, window, cx| {
 6443            this.buffer.update(cx, |buffer, cx| {
 6444                let empty_str: Arc<str> = Arc::default();
 6445                buffer.edit(
 6446                    deletion_ranges
 6447                        .into_iter()
 6448                        .map(|range| (range, empty_str.clone())),
 6449                    None,
 6450                    cx,
 6451                );
 6452            });
 6453            let selections = this.selections.all::<usize>(cx);
 6454            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6455                s.select(selections)
 6456            });
 6457        });
 6458    }
 6459
 6460    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6461        if self.read_only(cx) {
 6462            return;
 6463        }
 6464        let selections = self
 6465            .selections
 6466            .all::<usize>(cx)
 6467            .into_iter()
 6468            .map(|s| s.range());
 6469
 6470        self.transact(window, cx, |this, window, cx| {
 6471            this.buffer.update(cx, |buffer, cx| {
 6472                buffer.autoindent_ranges(selections, cx);
 6473            });
 6474            let selections = this.selections.all::<usize>(cx);
 6475            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6476                s.select(selections)
 6477            });
 6478        });
 6479    }
 6480
 6481    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6482        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6483        let selections = self.selections.all::<Point>(cx);
 6484
 6485        let mut new_cursors = Vec::new();
 6486        let mut edit_ranges = Vec::new();
 6487        let mut selections = selections.iter().peekable();
 6488        while let Some(selection) = selections.next() {
 6489            let mut rows = selection.spanned_rows(false, &display_map);
 6490            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6491
 6492            // Accumulate contiguous regions of rows that we want to delete.
 6493            while let Some(next_selection) = selections.peek() {
 6494                let next_rows = next_selection.spanned_rows(false, &display_map);
 6495                if next_rows.start <= rows.end {
 6496                    rows.end = next_rows.end;
 6497                    selections.next().unwrap();
 6498                } else {
 6499                    break;
 6500                }
 6501            }
 6502
 6503            let buffer = &display_map.buffer_snapshot;
 6504            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6505            let edit_end;
 6506            let cursor_buffer_row;
 6507            if buffer.max_point().row >= rows.end.0 {
 6508                // If there's a line after the range, delete the \n from the end of the row range
 6509                // and position the cursor on the next line.
 6510                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6511                cursor_buffer_row = rows.end;
 6512            } else {
 6513                // If there isn't a line after the range, delete the \n from the line before the
 6514                // start of the row range and position the cursor there.
 6515                edit_start = edit_start.saturating_sub(1);
 6516                edit_end = buffer.len();
 6517                cursor_buffer_row = rows.start.previous_row();
 6518            }
 6519
 6520            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6521            *cursor.column_mut() =
 6522                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6523
 6524            new_cursors.push((
 6525                selection.id,
 6526                buffer.anchor_after(cursor.to_point(&display_map)),
 6527            ));
 6528            edit_ranges.push(edit_start..edit_end);
 6529        }
 6530
 6531        self.transact(window, cx, |this, window, cx| {
 6532            let buffer = this.buffer.update(cx, |buffer, cx| {
 6533                let empty_str: Arc<str> = Arc::default();
 6534                buffer.edit(
 6535                    edit_ranges
 6536                        .into_iter()
 6537                        .map(|range| (range, empty_str.clone())),
 6538                    None,
 6539                    cx,
 6540                );
 6541                buffer.snapshot(cx)
 6542            });
 6543            let new_selections = new_cursors
 6544                .into_iter()
 6545                .map(|(id, cursor)| {
 6546                    let cursor = cursor.to_point(&buffer);
 6547                    Selection {
 6548                        id,
 6549                        start: cursor,
 6550                        end: cursor,
 6551                        reversed: false,
 6552                        goal: SelectionGoal::None,
 6553                    }
 6554                })
 6555                .collect();
 6556
 6557            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6558                s.select(new_selections);
 6559            });
 6560        });
 6561    }
 6562
 6563    pub fn join_lines_impl(
 6564        &mut self,
 6565        insert_whitespace: bool,
 6566        window: &mut Window,
 6567        cx: &mut Context<Self>,
 6568    ) {
 6569        if self.read_only(cx) {
 6570            return;
 6571        }
 6572        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6573        for selection in self.selections.all::<Point>(cx) {
 6574            let start = MultiBufferRow(selection.start.row);
 6575            // Treat single line selections as if they include the next line. Otherwise this action
 6576            // would do nothing for single line selections individual cursors.
 6577            let end = if selection.start.row == selection.end.row {
 6578                MultiBufferRow(selection.start.row + 1)
 6579            } else {
 6580                MultiBufferRow(selection.end.row)
 6581            };
 6582
 6583            if let Some(last_row_range) = row_ranges.last_mut() {
 6584                if start <= last_row_range.end {
 6585                    last_row_range.end = end;
 6586                    continue;
 6587                }
 6588            }
 6589            row_ranges.push(start..end);
 6590        }
 6591
 6592        let snapshot = self.buffer.read(cx).snapshot(cx);
 6593        let mut cursor_positions = Vec::new();
 6594        for row_range in &row_ranges {
 6595            let anchor = snapshot.anchor_before(Point::new(
 6596                row_range.end.previous_row().0,
 6597                snapshot.line_len(row_range.end.previous_row()),
 6598            ));
 6599            cursor_positions.push(anchor..anchor);
 6600        }
 6601
 6602        self.transact(window, cx, |this, window, cx| {
 6603            for row_range in row_ranges.into_iter().rev() {
 6604                for row in row_range.iter_rows().rev() {
 6605                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6606                    let next_line_row = row.next_row();
 6607                    let indent = snapshot.indent_size_for_line(next_line_row);
 6608                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6609
 6610                    let replace =
 6611                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6612                            " "
 6613                        } else {
 6614                            ""
 6615                        };
 6616
 6617                    this.buffer.update(cx, |buffer, cx| {
 6618                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6619                    });
 6620                }
 6621            }
 6622
 6623            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6624                s.select_anchor_ranges(cursor_positions)
 6625            });
 6626        });
 6627    }
 6628
 6629    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6630        self.join_lines_impl(true, window, cx);
 6631    }
 6632
 6633    pub fn sort_lines_case_sensitive(
 6634        &mut self,
 6635        _: &SortLinesCaseSensitive,
 6636        window: &mut Window,
 6637        cx: &mut Context<Self>,
 6638    ) {
 6639        self.manipulate_lines(window, cx, |lines| lines.sort())
 6640    }
 6641
 6642    pub fn sort_lines_case_insensitive(
 6643        &mut self,
 6644        _: &SortLinesCaseInsensitive,
 6645        window: &mut Window,
 6646        cx: &mut Context<Self>,
 6647    ) {
 6648        self.manipulate_lines(window, cx, |lines| {
 6649            lines.sort_by_key(|line| line.to_lowercase())
 6650        })
 6651    }
 6652
 6653    pub fn unique_lines_case_insensitive(
 6654        &mut self,
 6655        _: &UniqueLinesCaseInsensitive,
 6656        window: &mut Window,
 6657        cx: &mut Context<Self>,
 6658    ) {
 6659        self.manipulate_lines(window, cx, |lines| {
 6660            let mut seen = HashSet::default();
 6661            lines.retain(|line| seen.insert(line.to_lowercase()));
 6662        })
 6663    }
 6664
 6665    pub fn unique_lines_case_sensitive(
 6666        &mut self,
 6667        _: &UniqueLinesCaseSensitive,
 6668        window: &mut Window,
 6669        cx: &mut Context<Self>,
 6670    ) {
 6671        self.manipulate_lines(window, cx, |lines| {
 6672            let mut seen = HashSet::default();
 6673            lines.retain(|line| seen.insert(*line));
 6674        })
 6675    }
 6676
 6677    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6678        let mut revert_changes = HashMap::default();
 6679        let snapshot = self.snapshot(window, cx);
 6680        for hunk in snapshot
 6681            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6682        {
 6683            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6684        }
 6685        if !revert_changes.is_empty() {
 6686            self.transact(window, cx, |editor, window, cx| {
 6687                editor.revert(revert_changes, window, cx);
 6688            });
 6689        }
 6690    }
 6691
 6692    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6693        let Some(project) = self.project.clone() else {
 6694            return;
 6695        };
 6696        self.reload(project, window, cx)
 6697            .detach_and_notify_err(window, cx);
 6698    }
 6699
 6700    pub fn revert_selected_hunks(
 6701        &mut self,
 6702        _: &RevertSelectedHunks,
 6703        window: &mut Window,
 6704        cx: &mut Context<Self>,
 6705    ) {
 6706        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6707        self.revert_hunks_in_ranges(selections, window, cx);
 6708    }
 6709
 6710    fn revert_hunks_in_ranges(
 6711        &mut self,
 6712        ranges: impl Iterator<Item = Range<Point>>,
 6713        window: &mut Window,
 6714        cx: &mut Context<Editor>,
 6715    ) {
 6716        let mut revert_changes = HashMap::default();
 6717        let snapshot = self.snapshot(window, cx);
 6718        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6719            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6720        }
 6721        if !revert_changes.is_empty() {
 6722            self.transact(window, cx, |editor, window, cx| {
 6723                editor.revert(revert_changes, window, cx);
 6724            });
 6725        }
 6726    }
 6727
 6728    pub fn open_active_item_in_terminal(
 6729        &mut self,
 6730        _: &OpenInTerminal,
 6731        window: &mut Window,
 6732        cx: &mut Context<Self>,
 6733    ) {
 6734        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6735            let project_path = buffer.read(cx).project_path(cx)?;
 6736            let project = self.project.as_ref()?.read(cx);
 6737            let entry = project.entry_for_path(&project_path, cx)?;
 6738            let parent = match &entry.canonical_path {
 6739                Some(canonical_path) => canonical_path.to_path_buf(),
 6740                None => project.absolute_path(&project_path, cx)?,
 6741            }
 6742            .parent()?
 6743            .to_path_buf();
 6744            Some(parent)
 6745        }) {
 6746            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6747        }
 6748    }
 6749
 6750    pub fn prepare_revert_change(
 6751        &self,
 6752        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6753        hunk: &MultiBufferDiffHunk,
 6754        cx: &mut App,
 6755    ) -> Option<()> {
 6756        let buffer = self.buffer.read(cx);
 6757        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6758        let buffer = buffer.buffer(hunk.buffer_id)?;
 6759        let buffer = buffer.read(cx);
 6760        let original_text = change_set
 6761            .read(cx)
 6762            .base_text
 6763            .as_ref()?
 6764            .as_rope()
 6765            .slice(hunk.diff_base_byte_range.clone());
 6766        let buffer_snapshot = buffer.snapshot();
 6767        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6768        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6769            probe
 6770                .0
 6771                .start
 6772                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6773                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6774        }) {
 6775            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6776            Some(())
 6777        } else {
 6778            None
 6779        }
 6780    }
 6781
 6782    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6783        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6784    }
 6785
 6786    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6787        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6788    }
 6789
 6790    fn manipulate_lines<Fn>(
 6791        &mut self,
 6792        window: &mut Window,
 6793        cx: &mut Context<Self>,
 6794        mut callback: Fn,
 6795    ) where
 6796        Fn: FnMut(&mut Vec<&str>),
 6797    {
 6798        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6799        let buffer = self.buffer.read(cx).snapshot(cx);
 6800
 6801        let mut edits = Vec::new();
 6802
 6803        let selections = self.selections.all::<Point>(cx);
 6804        let mut selections = selections.iter().peekable();
 6805        let mut contiguous_row_selections = Vec::new();
 6806        let mut new_selections = Vec::new();
 6807        let mut added_lines = 0;
 6808        let mut removed_lines = 0;
 6809
 6810        while let Some(selection) = selections.next() {
 6811            let (start_row, end_row) = consume_contiguous_rows(
 6812                &mut contiguous_row_selections,
 6813                selection,
 6814                &display_map,
 6815                &mut selections,
 6816            );
 6817
 6818            let start_point = Point::new(start_row.0, 0);
 6819            let end_point = Point::new(
 6820                end_row.previous_row().0,
 6821                buffer.line_len(end_row.previous_row()),
 6822            );
 6823            let text = buffer
 6824                .text_for_range(start_point..end_point)
 6825                .collect::<String>();
 6826
 6827            let mut lines = text.split('\n').collect_vec();
 6828
 6829            let lines_before = lines.len();
 6830            callback(&mut lines);
 6831            let lines_after = lines.len();
 6832
 6833            edits.push((start_point..end_point, lines.join("\n")));
 6834
 6835            // Selections must change based on added and removed line count
 6836            let start_row =
 6837                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6838            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6839            new_selections.push(Selection {
 6840                id: selection.id,
 6841                start: start_row,
 6842                end: end_row,
 6843                goal: SelectionGoal::None,
 6844                reversed: selection.reversed,
 6845            });
 6846
 6847            if lines_after > lines_before {
 6848                added_lines += lines_after - lines_before;
 6849            } else if lines_before > lines_after {
 6850                removed_lines += lines_before - lines_after;
 6851            }
 6852        }
 6853
 6854        self.transact(window, cx, |this, window, cx| {
 6855            let buffer = this.buffer.update(cx, |buffer, cx| {
 6856                buffer.edit(edits, None, cx);
 6857                buffer.snapshot(cx)
 6858            });
 6859
 6860            // Recalculate offsets on newly edited buffer
 6861            let new_selections = new_selections
 6862                .iter()
 6863                .map(|s| {
 6864                    let start_point = Point::new(s.start.0, 0);
 6865                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6866                    Selection {
 6867                        id: s.id,
 6868                        start: buffer.point_to_offset(start_point),
 6869                        end: buffer.point_to_offset(end_point),
 6870                        goal: s.goal,
 6871                        reversed: s.reversed,
 6872                    }
 6873                })
 6874                .collect();
 6875
 6876            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6877                s.select(new_selections);
 6878            });
 6879
 6880            this.request_autoscroll(Autoscroll::fit(), cx);
 6881        });
 6882    }
 6883
 6884    pub fn convert_to_upper_case(
 6885        &mut self,
 6886        _: &ConvertToUpperCase,
 6887        window: &mut Window,
 6888        cx: &mut Context<Self>,
 6889    ) {
 6890        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6891    }
 6892
 6893    pub fn convert_to_lower_case(
 6894        &mut self,
 6895        _: &ConvertToLowerCase,
 6896        window: &mut Window,
 6897        cx: &mut Context<Self>,
 6898    ) {
 6899        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6900    }
 6901
 6902    pub fn convert_to_title_case(
 6903        &mut self,
 6904        _: &ConvertToTitleCase,
 6905        window: &mut Window,
 6906        cx: &mut Context<Self>,
 6907    ) {
 6908        self.manipulate_text(window, cx, |text| {
 6909            text.split('\n')
 6910                .map(|line| line.to_case(Case::Title))
 6911                .join("\n")
 6912        })
 6913    }
 6914
 6915    pub fn convert_to_snake_case(
 6916        &mut self,
 6917        _: &ConvertToSnakeCase,
 6918        window: &mut Window,
 6919        cx: &mut Context<Self>,
 6920    ) {
 6921        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6922    }
 6923
 6924    pub fn convert_to_kebab_case(
 6925        &mut self,
 6926        _: &ConvertToKebabCase,
 6927        window: &mut Window,
 6928        cx: &mut Context<Self>,
 6929    ) {
 6930        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6931    }
 6932
 6933    pub fn convert_to_upper_camel_case(
 6934        &mut self,
 6935        _: &ConvertToUpperCamelCase,
 6936        window: &mut Window,
 6937        cx: &mut Context<Self>,
 6938    ) {
 6939        self.manipulate_text(window, cx, |text| {
 6940            text.split('\n')
 6941                .map(|line| line.to_case(Case::UpperCamel))
 6942                .join("\n")
 6943        })
 6944    }
 6945
 6946    pub fn convert_to_lower_camel_case(
 6947        &mut self,
 6948        _: &ConvertToLowerCamelCase,
 6949        window: &mut Window,
 6950        cx: &mut Context<Self>,
 6951    ) {
 6952        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6953    }
 6954
 6955    pub fn convert_to_opposite_case(
 6956        &mut self,
 6957        _: &ConvertToOppositeCase,
 6958        window: &mut Window,
 6959        cx: &mut Context<Self>,
 6960    ) {
 6961        self.manipulate_text(window, cx, |text| {
 6962            text.chars()
 6963                .fold(String::with_capacity(text.len()), |mut t, c| {
 6964                    if c.is_uppercase() {
 6965                        t.extend(c.to_lowercase());
 6966                    } else {
 6967                        t.extend(c.to_uppercase());
 6968                    }
 6969                    t
 6970                })
 6971        })
 6972    }
 6973
 6974    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6975    where
 6976        Fn: FnMut(&str) -> String,
 6977    {
 6978        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6979        let buffer = self.buffer.read(cx).snapshot(cx);
 6980
 6981        let mut new_selections = Vec::new();
 6982        let mut edits = Vec::new();
 6983        let mut selection_adjustment = 0i32;
 6984
 6985        for selection in self.selections.all::<usize>(cx) {
 6986            let selection_is_empty = selection.is_empty();
 6987
 6988            let (start, end) = if selection_is_empty {
 6989                let word_range = movement::surrounding_word(
 6990                    &display_map,
 6991                    selection.start.to_display_point(&display_map),
 6992                );
 6993                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6994                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6995                (start, end)
 6996            } else {
 6997                (selection.start, selection.end)
 6998            };
 6999
 7000            let text = buffer.text_for_range(start..end).collect::<String>();
 7001            let old_length = text.len() as i32;
 7002            let text = callback(&text);
 7003
 7004            new_selections.push(Selection {
 7005                start: (start as i32 - selection_adjustment) as usize,
 7006                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7007                goal: SelectionGoal::None,
 7008                ..selection
 7009            });
 7010
 7011            selection_adjustment += old_length - text.len() as i32;
 7012
 7013            edits.push((start..end, text));
 7014        }
 7015
 7016        self.transact(window, cx, |this, window, cx| {
 7017            this.buffer.update(cx, |buffer, cx| {
 7018                buffer.edit(edits, None, cx);
 7019            });
 7020
 7021            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7022                s.select(new_selections);
 7023            });
 7024
 7025            this.request_autoscroll(Autoscroll::fit(), cx);
 7026        });
 7027    }
 7028
 7029    pub fn duplicate(
 7030        &mut self,
 7031        upwards: bool,
 7032        whole_lines: bool,
 7033        window: &mut Window,
 7034        cx: &mut Context<Self>,
 7035    ) {
 7036        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7037        let buffer = &display_map.buffer_snapshot;
 7038        let selections = self.selections.all::<Point>(cx);
 7039
 7040        let mut edits = Vec::new();
 7041        let mut selections_iter = selections.iter().peekable();
 7042        while let Some(selection) = selections_iter.next() {
 7043            let mut rows = selection.spanned_rows(false, &display_map);
 7044            // duplicate line-wise
 7045            if whole_lines || selection.start == selection.end {
 7046                // Avoid duplicating the same lines twice.
 7047                while let Some(next_selection) = selections_iter.peek() {
 7048                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7049                    if next_rows.start < rows.end {
 7050                        rows.end = next_rows.end;
 7051                        selections_iter.next().unwrap();
 7052                    } else {
 7053                        break;
 7054                    }
 7055                }
 7056
 7057                // Copy the text from the selected row region and splice it either at the start
 7058                // or end of the region.
 7059                let start = Point::new(rows.start.0, 0);
 7060                let end = Point::new(
 7061                    rows.end.previous_row().0,
 7062                    buffer.line_len(rows.end.previous_row()),
 7063                );
 7064                let text = buffer
 7065                    .text_for_range(start..end)
 7066                    .chain(Some("\n"))
 7067                    .collect::<String>();
 7068                let insert_location = if upwards {
 7069                    Point::new(rows.end.0, 0)
 7070                } else {
 7071                    start
 7072                };
 7073                edits.push((insert_location..insert_location, text));
 7074            } else {
 7075                // duplicate character-wise
 7076                let start = selection.start;
 7077                let end = selection.end;
 7078                let text = buffer.text_for_range(start..end).collect::<String>();
 7079                edits.push((selection.end..selection.end, text));
 7080            }
 7081        }
 7082
 7083        self.transact(window, cx, |this, _, cx| {
 7084            this.buffer.update(cx, |buffer, cx| {
 7085                buffer.edit(edits, None, cx);
 7086            });
 7087
 7088            this.request_autoscroll(Autoscroll::fit(), cx);
 7089        });
 7090    }
 7091
 7092    pub fn duplicate_line_up(
 7093        &mut self,
 7094        _: &DuplicateLineUp,
 7095        window: &mut Window,
 7096        cx: &mut Context<Self>,
 7097    ) {
 7098        self.duplicate(true, true, window, cx);
 7099    }
 7100
 7101    pub fn duplicate_line_down(
 7102        &mut self,
 7103        _: &DuplicateLineDown,
 7104        window: &mut Window,
 7105        cx: &mut Context<Self>,
 7106    ) {
 7107        self.duplicate(false, true, window, cx);
 7108    }
 7109
 7110    pub fn duplicate_selection(
 7111        &mut self,
 7112        _: &DuplicateSelection,
 7113        window: &mut Window,
 7114        cx: &mut Context<Self>,
 7115    ) {
 7116        self.duplicate(false, false, window, cx);
 7117    }
 7118
 7119    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7120        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7121        let buffer = self.buffer.read(cx).snapshot(cx);
 7122
 7123        let mut edits = Vec::new();
 7124        let mut unfold_ranges = Vec::new();
 7125        let mut refold_creases = Vec::new();
 7126
 7127        let selections = self.selections.all::<Point>(cx);
 7128        let mut selections = selections.iter().peekable();
 7129        let mut contiguous_row_selections = Vec::new();
 7130        let mut new_selections = Vec::new();
 7131
 7132        while let Some(selection) = selections.next() {
 7133            // Find all the selections that span a contiguous row range
 7134            let (start_row, end_row) = consume_contiguous_rows(
 7135                &mut contiguous_row_selections,
 7136                selection,
 7137                &display_map,
 7138                &mut selections,
 7139            );
 7140
 7141            // Move the text spanned by the row range to be before the line preceding the row range
 7142            if start_row.0 > 0 {
 7143                let range_to_move = Point::new(
 7144                    start_row.previous_row().0,
 7145                    buffer.line_len(start_row.previous_row()),
 7146                )
 7147                    ..Point::new(
 7148                        end_row.previous_row().0,
 7149                        buffer.line_len(end_row.previous_row()),
 7150                    );
 7151                let insertion_point = display_map
 7152                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7153                    .0;
 7154
 7155                // Don't move lines across excerpts
 7156                if buffer
 7157                    .excerpt_containing(insertion_point..range_to_move.end)
 7158                    .is_some()
 7159                {
 7160                    let text = buffer
 7161                        .text_for_range(range_to_move.clone())
 7162                        .flat_map(|s| s.chars())
 7163                        .skip(1)
 7164                        .chain(['\n'])
 7165                        .collect::<String>();
 7166
 7167                    edits.push((
 7168                        buffer.anchor_after(range_to_move.start)
 7169                            ..buffer.anchor_before(range_to_move.end),
 7170                        String::new(),
 7171                    ));
 7172                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7173                    edits.push((insertion_anchor..insertion_anchor, text));
 7174
 7175                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7176
 7177                    // Move selections up
 7178                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7179                        |mut selection| {
 7180                            selection.start.row -= row_delta;
 7181                            selection.end.row -= row_delta;
 7182                            selection
 7183                        },
 7184                    ));
 7185
 7186                    // Move folds up
 7187                    unfold_ranges.push(range_to_move.clone());
 7188                    for fold in display_map.folds_in_range(
 7189                        buffer.anchor_before(range_to_move.start)
 7190                            ..buffer.anchor_after(range_to_move.end),
 7191                    ) {
 7192                        let mut start = fold.range.start.to_point(&buffer);
 7193                        let mut end = fold.range.end.to_point(&buffer);
 7194                        start.row -= row_delta;
 7195                        end.row -= row_delta;
 7196                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7197                    }
 7198                }
 7199            }
 7200
 7201            // If we didn't move line(s), preserve the existing selections
 7202            new_selections.append(&mut contiguous_row_selections);
 7203        }
 7204
 7205        self.transact(window, cx, |this, window, cx| {
 7206            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7207            this.buffer.update(cx, |buffer, cx| {
 7208                for (range, text) in edits {
 7209                    buffer.edit([(range, text)], None, cx);
 7210                }
 7211            });
 7212            this.fold_creases(refold_creases, true, window, cx);
 7213            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7214                s.select(new_selections);
 7215            })
 7216        });
 7217    }
 7218
 7219    pub fn move_line_down(
 7220        &mut self,
 7221        _: &MoveLineDown,
 7222        window: &mut Window,
 7223        cx: &mut Context<Self>,
 7224    ) {
 7225        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7226        let buffer = self.buffer.read(cx).snapshot(cx);
 7227
 7228        let mut edits = Vec::new();
 7229        let mut unfold_ranges = Vec::new();
 7230        let mut refold_creases = Vec::new();
 7231
 7232        let selections = self.selections.all::<Point>(cx);
 7233        let mut selections = selections.iter().peekable();
 7234        let mut contiguous_row_selections = Vec::new();
 7235        let mut new_selections = Vec::new();
 7236
 7237        while let Some(selection) = selections.next() {
 7238            // Find all the selections that span a contiguous row range
 7239            let (start_row, end_row) = consume_contiguous_rows(
 7240                &mut contiguous_row_selections,
 7241                selection,
 7242                &display_map,
 7243                &mut selections,
 7244            );
 7245
 7246            // Move the text spanned by the row range to be after the last line of the row range
 7247            if end_row.0 <= buffer.max_point().row {
 7248                let range_to_move =
 7249                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7250                let insertion_point = display_map
 7251                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7252                    .0;
 7253
 7254                // Don't move lines across excerpt boundaries
 7255                if buffer
 7256                    .excerpt_containing(range_to_move.start..insertion_point)
 7257                    .is_some()
 7258                {
 7259                    let mut text = String::from("\n");
 7260                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7261                    text.pop(); // Drop trailing newline
 7262                    edits.push((
 7263                        buffer.anchor_after(range_to_move.start)
 7264                            ..buffer.anchor_before(range_to_move.end),
 7265                        String::new(),
 7266                    ));
 7267                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7268                    edits.push((insertion_anchor..insertion_anchor, text));
 7269
 7270                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7271
 7272                    // Move selections down
 7273                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7274                        |mut selection| {
 7275                            selection.start.row += row_delta;
 7276                            selection.end.row += row_delta;
 7277                            selection
 7278                        },
 7279                    ));
 7280
 7281                    // Move folds down
 7282                    unfold_ranges.push(range_to_move.clone());
 7283                    for fold in display_map.folds_in_range(
 7284                        buffer.anchor_before(range_to_move.start)
 7285                            ..buffer.anchor_after(range_to_move.end),
 7286                    ) {
 7287                        let mut start = fold.range.start.to_point(&buffer);
 7288                        let mut end = fold.range.end.to_point(&buffer);
 7289                        start.row += row_delta;
 7290                        end.row += row_delta;
 7291                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7292                    }
 7293                }
 7294            }
 7295
 7296            // If we didn't move line(s), preserve the existing selections
 7297            new_selections.append(&mut contiguous_row_selections);
 7298        }
 7299
 7300        self.transact(window, cx, |this, window, cx| {
 7301            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7302            this.buffer.update(cx, |buffer, cx| {
 7303                for (range, text) in edits {
 7304                    buffer.edit([(range, text)], None, cx);
 7305                }
 7306            });
 7307            this.fold_creases(refold_creases, true, window, cx);
 7308            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7309                s.select(new_selections)
 7310            });
 7311        });
 7312    }
 7313
 7314    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7315        let text_layout_details = &self.text_layout_details(window);
 7316        self.transact(window, cx, |this, window, cx| {
 7317            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7318                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7319                let line_mode = s.line_mode;
 7320                s.move_with(|display_map, selection| {
 7321                    if !selection.is_empty() || line_mode {
 7322                        return;
 7323                    }
 7324
 7325                    let mut head = selection.head();
 7326                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7327                    if head.column() == display_map.line_len(head.row()) {
 7328                        transpose_offset = display_map
 7329                            .buffer_snapshot
 7330                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7331                    }
 7332
 7333                    if transpose_offset == 0 {
 7334                        return;
 7335                    }
 7336
 7337                    *head.column_mut() += 1;
 7338                    head = display_map.clip_point(head, Bias::Right);
 7339                    let goal = SelectionGoal::HorizontalPosition(
 7340                        display_map
 7341                            .x_for_display_point(head, text_layout_details)
 7342                            .into(),
 7343                    );
 7344                    selection.collapse_to(head, goal);
 7345
 7346                    let transpose_start = display_map
 7347                        .buffer_snapshot
 7348                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7349                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7350                        let transpose_end = display_map
 7351                            .buffer_snapshot
 7352                            .clip_offset(transpose_offset + 1, Bias::Right);
 7353                        if let Some(ch) =
 7354                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7355                        {
 7356                            edits.push((transpose_start..transpose_offset, String::new()));
 7357                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7358                        }
 7359                    }
 7360                });
 7361                edits
 7362            });
 7363            this.buffer
 7364                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7365            let selections = this.selections.all::<usize>(cx);
 7366            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7367                s.select(selections);
 7368            });
 7369        });
 7370    }
 7371
 7372    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7373        self.rewrap_impl(IsVimMode::No, cx)
 7374    }
 7375
 7376    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7377        let buffer = self.buffer.read(cx).snapshot(cx);
 7378        let selections = self.selections.all::<Point>(cx);
 7379        let mut selections = selections.iter().peekable();
 7380
 7381        let mut edits = Vec::new();
 7382        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7383
 7384        while let Some(selection) = selections.next() {
 7385            let mut start_row = selection.start.row;
 7386            let mut end_row = selection.end.row;
 7387
 7388            // Skip selections that overlap with a range that has already been rewrapped.
 7389            let selection_range = start_row..end_row;
 7390            if rewrapped_row_ranges
 7391                .iter()
 7392                .any(|range| range.overlaps(&selection_range))
 7393            {
 7394                continue;
 7395            }
 7396
 7397            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7398
 7399            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7400                match language_scope.language_name().as_ref() {
 7401                    "Markdown" | "Plain Text" => {
 7402                        should_rewrap = true;
 7403                    }
 7404                    _ => {}
 7405                }
 7406            }
 7407
 7408            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7409
 7410            // Since not all lines in the selection may be at the same indent
 7411            // level, choose the indent size that is the most common between all
 7412            // of the lines.
 7413            //
 7414            // If there is a tie, we use the deepest indent.
 7415            let (indent_size, indent_end) = {
 7416                let mut indent_size_occurrences = HashMap::default();
 7417                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7418
 7419                for row in start_row..=end_row {
 7420                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7421                    rows_by_indent_size.entry(indent).or_default().push(row);
 7422                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7423                }
 7424
 7425                let indent_size = indent_size_occurrences
 7426                    .into_iter()
 7427                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7428                    .map(|(indent, _)| indent)
 7429                    .unwrap_or_default();
 7430                let row = rows_by_indent_size[&indent_size][0];
 7431                let indent_end = Point::new(row, indent_size.len);
 7432
 7433                (indent_size, indent_end)
 7434            };
 7435
 7436            let mut line_prefix = indent_size.chars().collect::<String>();
 7437
 7438            if let Some(comment_prefix) =
 7439                buffer
 7440                    .language_scope_at(selection.head())
 7441                    .and_then(|language| {
 7442                        language
 7443                            .line_comment_prefixes()
 7444                            .iter()
 7445                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7446                            .cloned()
 7447                    })
 7448            {
 7449                line_prefix.push_str(&comment_prefix);
 7450                should_rewrap = true;
 7451            }
 7452
 7453            if !should_rewrap {
 7454                continue;
 7455            }
 7456
 7457            if selection.is_empty() {
 7458                'expand_upwards: while start_row > 0 {
 7459                    let prev_row = start_row - 1;
 7460                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7461                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7462                    {
 7463                        start_row = prev_row;
 7464                    } else {
 7465                        break 'expand_upwards;
 7466                    }
 7467                }
 7468
 7469                'expand_downwards: while end_row < buffer.max_point().row {
 7470                    let next_row = end_row + 1;
 7471                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7472                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7473                    {
 7474                        end_row = next_row;
 7475                    } else {
 7476                        break 'expand_downwards;
 7477                    }
 7478                }
 7479            }
 7480
 7481            let start = Point::new(start_row, 0);
 7482            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7483            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7484            let Some(lines_without_prefixes) = selection_text
 7485                .lines()
 7486                .map(|line| {
 7487                    line.strip_prefix(&line_prefix)
 7488                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7489                        .ok_or_else(|| {
 7490                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7491                        })
 7492                })
 7493                .collect::<Result<Vec<_>, _>>()
 7494                .log_err()
 7495            else {
 7496                continue;
 7497            };
 7498
 7499            let wrap_column = buffer
 7500                .settings_at(Point::new(start_row, 0), cx)
 7501                .preferred_line_length as usize;
 7502            let wrapped_text = wrap_with_prefix(
 7503                line_prefix,
 7504                lines_without_prefixes.join(" "),
 7505                wrap_column,
 7506                tab_size,
 7507            );
 7508
 7509            // TODO: should always use char-based diff while still supporting cursor behavior that
 7510            // matches vim.
 7511            let diff = match is_vim_mode {
 7512                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7513                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7514            };
 7515            let mut offset = start.to_offset(&buffer);
 7516            let mut moved_since_edit = true;
 7517
 7518            for change in diff.iter_all_changes() {
 7519                let value = change.value();
 7520                match change.tag() {
 7521                    ChangeTag::Equal => {
 7522                        offset += value.len();
 7523                        moved_since_edit = true;
 7524                    }
 7525                    ChangeTag::Delete => {
 7526                        let start = buffer.anchor_after(offset);
 7527                        let end = buffer.anchor_before(offset + value.len());
 7528
 7529                        if moved_since_edit {
 7530                            edits.push((start..end, String::new()));
 7531                        } else {
 7532                            edits.last_mut().unwrap().0.end = end;
 7533                        }
 7534
 7535                        offset += value.len();
 7536                        moved_since_edit = false;
 7537                    }
 7538                    ChangeTag::Insert => {
 7539                        if moved_since_edit {
 7540                            let anchor = buffer.anchor_after(offset);
 7541                            edits.push((anchor..anchor, value.to_string()));
 7542                        } else {
 7543                            edits.last_mut().unwrap().1.push_str(value);
 7544                        }
 7545
 7546                        moved_since_edit = false;
 7547                    }
 7548                }
 7549            }
 7550
 7551            rewrapped_row_ranges.push(start_row..=end_row);
 7552        }
 7553
 7554        self.buffer
 7555            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7556    }
 7557
 7558    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7559        let mut text = String::new();
 7560        let buffer = self.buffer.read(cx).snapshot(cx);
 7561        let mut selections = self.selections.all::<Point>(cx);
 7562        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7563        {
 7564            let max_point = buffer.max_point();
 7565            let mut is_first = true;
 7566            for selection in &mut selections {
 7567                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7568                if is_entire_line {
 7569                    selection.start = Point::new(selection.start.row, 0);
 7570                    if !selection.is_empty() && selection.end.column == 0 {
 7571                        selection.end = cmp::min(max_point, selection.end);
 7572                    } else {
 7573                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7574                    }
 7575                    selection.goal = SelectionGoal::None;
 7576                }
 7577                if is_first {
 7578                    is_first = false;
 7579                } else {
 7580                    text += "\n";
 7581                }
 7582                let mut len = 0;
 7583                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7584                    text.push_str(chunk);
 7585                    len += chunk.len();
 7586                }
 7587                clipboard_selections.push(ClipboardSelection {
 7588                    len,
 7589                    is_entire_line,
 7590                    first_line_indent: buffer
 7591                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7592                        .len,
 7593                });
 7594            }
 7595        }
 7596
 7597        self.transact(window, cx, |this, window, cx| {
 7598            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7599                s.select(selections);
 7600            });
 7601            this.insert("", window, cx);
 7602        });
 7603        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7604    }
 7605
 7606    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7607        let item = self.cut_common(window, cx);
 7608        cx.write_to_clipboard(item);
 7609    }
 7610
 7611    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7612        self.change_selections(None, window, cx, |s| {
 7613            s.move_with(|snapshot, sel| {
 7614                if sel.is_empty() {
 7615                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7616                }
 7617            });
 7618        });
 7619        let item = self.cut_common(window, cx);
 7620        cx.set_global(KillRing(item))
 7621    }
 7622
 7623    pub fn kill_ring_yank(
 7624        &mut self,
 7625        _: &KillRingYank,
 7626        window: &mut Window,
 7627        cx: &mut Context<Self>,
 7628    ) {
 7629        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7630            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7631                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7632            } else {
 7633                return;
 7634            }
 7635        } else {
 7636            return;
 7637        };
 7638        self.do_paste(&text, metadata, false, window, cx);
 7639    }
 7640
 7641    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7642        let selections = self.selections.all::<Point>(cx);
 7643        let buffer = self.buffer.read(cx).read(cx);
 7644        let mut text = String::new();
 7645
 7646        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7647        {
 7648            let max_point = buffer.max_point();
 7649            let mut is_first = true;
 7650            for selection in selections.iter() {
 7651                let mut start = selection.start;
 7652                let mut end = selection.end;
 7653                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7654                if is_entire_line {
 7655                    start = Point::new(start.row, 0);
 7656                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7657                }
 7658                if is_first {
 7659                    is_first = false;
 7660                } else {
 7661                    text += "\n";
 7662                }
 7663                let mut len = 0;
 7664                for chunk in buffer.text_for_range(start..end) {
 7665                    text.push_str(chunk);
 7666                    len += chunk.len();
 7667                }
 7668                clipboard_selections.push(ClipboardSelection {
 7669                    len,
 7670                    is_entire_line,
 7671                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7672                });
 7673            }
 7674        }
 7675
 7676        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7677            text,
 7678            clipboard_selections,
 7679        ));
 7680    }
 7681
 7682    pub fn do_paste(
 7683        &mut self,
 7684        text: &String,
 7685        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7686        handle_entire_lines: bool,
 7687        window: &mut Window,
 7688        cx: &mut Context<Self>,
 7689    ) {
 7690        if self.read_only(cx) {
 7691            return;
 7692        }
 7693
 7694        let clipboard_text = Cow::Borrowed(text);
 7695
 7696        self.transact(window, cx, |this, window, cx| {
 7697            if let Some(mut clipboard_selections) = clipboard_selections {
 7698                let old_selections = this.selections.all::<usize>(cx);
 7699                let all_selections_were_entire_line =
 7700                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7701                let first_selection_indent_column =
 7702                    clipboard_selections.first().map(|s| s.first_line_indent);
 7703                if clipboard_selections.len() != old_selections.len() {
 7704                    clipboard_selections.drain(..);
 7705                }
 7706                let cursor_offset = this.selections.last::<usize>(cx).head();
 7707                let mut auto_indent_on_paste = true;
 7708
 7709                this.buffer.update(cx, |buffer, cx| {
 7710                    let snapshot = buffer.read(cx);
 7711                    auto_indent_on_paste =
 7712                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7713
 7714                    let mut start_offset = 0;
 7715                    let mut edits = Vec::new();
 7716                    let mut original_indent_columns = Vec::new();
 7717                    for (ix, selection) in old_selections.iter().enumerate() {
 7718                        let to_insert;
 7719                        let entire_line;
 7720                        let original_indent_column;
 7721                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7722                            let end_offset = start_offset + clipboard_selection.len;
 7723                            to_insert = &clipboard_text[start_offset..end_offset];
 7724                            entire_line = clipboard_selection.is_entire_line;
 7725                            start_offset = end_offset + 1;
 7726                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7727                        } else {
 7728                            to_insert = clipboard_text.as_str();
 7729                            entire_line = all_selections_were_entire_line;
 7730                            original_indent_column = first_selection_indent_column
 7731                        }
 7732
 7733                        // If the corresponding selection was empty when this slice of the
 7734                        // clipboard text was written, then the entire line containing the
 7735                        // selection was copied. If this selection is also currently empty,
 7736                        // then paste the line before the current line of the buffer.
 7737                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7738                            let column = selection.start.to_point(&snapshot).column as usize;
 7739                            let line_start = selection.start - column;
 7740                            line_start..line_start
 7741                        } else {
 7742                            selection.range()
 7743                        };
 7744
 7745                        edits.push((range, to_insert));
 7746                        original_indent_columns.extend(original_indent_column);
 7747                    }
 7748                    drop(snapshot);
 7749
 7750                    buffer.edit(
 7751                        edits,
 7752                        if auto_indent_on_paste {
 7753                            Some(AutoindentMode::Block {
 7754                                original_indent_columns,
 7755                            })
 7756                        } else {
 7757                            None
 7758                        },
 7759                        cx,
 7760                    );
 7761                });
 7762
 7763                let selections = this.selections.all::<usize>(cx);
 7764                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7765                    s.select(selections)
 7766                });
 7767            } else {
 7768                this.insert(&clipboard_text, window, cx);
 7769            }
 7770        });
 7771    }
 7772
 7773    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7774        if let Some(item) = cx.read_from_clipboard() {
 7775            let entries = item.entries();
 7776
 7777            match entries.first() {
 7778                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7779                // of all the pasted entries.
 7780                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7781                    .do_paste(
 7782                        clipboard_string.text(),
 7783                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7784                        true,
 7785                        window,
 7786                        cx,
 7787                    ),
 7788                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7789            }
 7790        }
 7791    }
 7792
 7793    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7794        if self.read_only(cx) {
 7795            return;
 7796        }
 7797
 7798        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7799            if let Some((selections, _)) =
 7800                self.selection_history.transaction(transaction_id).cloned()
 7801            {
 7802                self.change_selections(None, window, cx, |s| {
 7803                    s.select_anchors(selections.to_vec());
 7804                });
 7805            }
 7806            self.request_autoscroll(Autoscroll::fit(), cx);
 7807            self.unmark_text(window, cx);
 7808            self.refresh_inline_completion(true, false, window, cx);
 7809            cx.emit(EditorEvent::Edited { transaction_id });
 7810            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7811        }
 7812    }
 7813
 7814    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7815        if self.read_only(cx) {
 7816            return;
 7817        }
 7818
 7819        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7820            if let Some((_, Some(selections))) =
 7821                self.selection_history.transaction(transaction_id).cloned()
 7822            {
 7823                self.change_selections(None, window, cx, |s| {
 7824                    s.select_anchors(selections.to_vec());
 7825                });
 7826            }
 7827            self.request_autoscroll(Autoscroll::fit(), cx);
 7828            self.unmark_text(window, cx);
 7829            self.refresh_inline_completion(true, false, window, cx);
 7830            cx.emit(EditorEvent::Edited { transaction_id });
 7831        }
 7832    }
 7833
 7834    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7835        self.buffer
 7836            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7837    }
 7838
 7839    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7840        self.buffer
 7841            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7842    }
 7843
 7844    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7845        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7846            let line_mode = s.line_mode;
 7847            s.move_with(|map, selection| {
 7848                let cursor = if selection.is_empty() && !line_mode {
 7849                    movement::left(map, selection.start)
 7850                } else {
 7851                    selection.start
 7852                };
 7853                selection.collapse_to(cursor, SelectionGoal::None);
 7854            });
 7855        })
 7856    }
 7857
 7858    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7860            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7861        })
 7862    }
 7863
 7864    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7865        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7866            let line_mode = s.line_mode;
 7867            s.move_with(|map, selection| {
 7868                let cursor = if selection.is_empty() && !line_mode {
 7869                    movement::right(map, selection.end)
 7870                } else {
 7871                    selection.end
 7872                };
 7873                selection.collapse_to(cursor, SelectionGoal::None)
 7874            });
 7875        })
 7876    }
 7877
 7878    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7879        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7880            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7881        })
 7882    }
 7883
 7884    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7885        if self.take_rename(true, window, cx).is_some() {
 7886            return;
 7887        }
 7888
 7889        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7890            cx.propagate();
 7891            return;
 7892        }
 7893
 7894        let text_layout_details = &self.text_layout_details(window);
 7895        let selection_count = self.selections.count();
 7896        let first_selection = self.selections.first_anchor();
 7897
 7898        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7899            let line_mode = s.line_mode;
 7900            s.move_with(|map, selection| {
 7901                if !selection.is_empty() && !line_mode {
 7902                    selection.goal = SelectionGoal::None;
 7903                }
 7904                let (cursor, goal) = movement::up(
 7905                    map,
 7906                    selection.start,
 7907                    selection.goal,
 7908                    false,
 7909                    text_layout_details,
 7910                );
 7911                selection.collapse_to(cursor, goal);
 7912            });
 7913        });
 7914
 7915        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7916        {
 7917            cx.propagate();
 7918        }
 7919    }
 7920
 7921    pub fn move_up_by_lines(
 7922        &mut self,
 7923        action: &MoveUpByLines,
 7924        window: &mut Window,
 7925        cx: &mut Context<Self>,
 7926    ) {
 7927        if self.take_rename(true, window, cx).is_some() {
 7928            return;
 7929        }
 7930
 7931        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7932            cx.propagate();
 7933            return;
 7934        }
 7935
 7936        let text_layout_details = &self.text_layout_details(window);
 7937
 7938        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7939            let line_mode = s.line_mode;
 7940            s.move_with(|map, selection| {
 7941                if !selection.is_empty() && !line_mode {
 7942                    selection.goal = SelectionGoal::None;
 7943                }
 7944                let (cursor, goal) = movement::up_by_rows(
 7945                    map,
 7946                    selection.start,
 7947                    action.lines,
 7948                    selection.goal,
 7949                    false,
 7950                    text_layout_details,
 7951                );
 7952                selection.collapse_to(cursor, goal);
 7953            });
 7954        })
 7955    }
 7956
 7957    pub fn move_down_by_lines(
 7958        &mut self,
 7959        action: &MoveDownByLines,
 7960        window: &mut Window,
 7961        cx: &mut Context<Self>,
 7962    ) {
 7963        if self.take_rename(true, window, cx).is_some() {
 7964            return;
 7965        }
 7966
 7967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7968            cx.propagate();
 7969            return;
 7970        }
 7971
 7972        let text_layout_details = &self.text_layout_details(window);
 7973
 7974        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7975            let line_mode = s.line_mode;
 7976            s.move_with(|map, selection| {
 7977                if !selection.is_empty() && !line_mode {
 7978                    selection.goal = SelectionGoal::None;
 7979                }
 7980                let (cursor, goal) = movement::down_by_rows(
 7981                    map,
 7982                    selection.start,
 7983                    action.lines,
 7984                    selection.goal,
 7985                    false,
 7986                    text_layout_details,
 7987                );
 7988                selection.collapse_to(cursor, goal);
 7989            });
 7990        })
 7991    }
 7992
 7993    pub fn select_down_by_lines(
 7994        &mut self,
 7995        action: &SelectDownByLines,
 7996        window: &mut Window,
 7997        cx: &mut Context<Self>,
 7998    ) {
 7999        let text_layout_details = &self.text_layout_details(window);
 8000        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8001            s.move_heads_with(|map, head, goal| {
 8002                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8003            })
 8004        })
 8005    }
 8006
 8007    pub fn select_up_by_lines(
 8008        &mut self,
 8009        action: &SelectUpByLines,
 8010        window: &mut Window,
 8011        cx: &mut Context<Self>,
 8012    ) {
 8013        let text_layout_details = &self.text_layout_details(window);
 8014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8015            s.move_heads_with(|map, head, goal| {
 8016                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8017            })
 8018        })
 8019    }
 8020
 8021    pub fn select_page_up(
 8022        &mut self,
 8023        _: &SelectPageUp,
 8024        window: &mut Window,
 8025        cx: &mut Context<Self>,
 8026    ) {
 8027        let Some(row_count) = self.visible_row_count() else {
 8028            return;
 8029        };
 8030
 8031        let text_layout_details = &self.text_layout_details(window);
 8032
 8033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8034            s.move_heads_with(|map, head, goal| {
 8035                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8036            })
 8037        })
 8038    }
 8039
 8040    pub fn move_page_up(
 8041        &mut self,
 8042        action: &MovePageUp,
 8043        window: &mut Window,
 8044        cx: &mut Context<Self>,
 8045    ) {
 8046        if self.take_rename(true, window, cx).is_some() {
 8047            return;
 8048        }
 8049
 8050        if self
 8051            .context_menu
 8052            .borrow_mut()
 8053            .as_mut()
 8054            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8055            .unwrap_or(false)
 8056        {
 8057            return;
 8058        }
 8059
 8060        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8061            cx.propagate();
 8062            return;
 8063        }
 8064
 8065        let Some(row_count) = self.visible_row_count() else {
 8066            return;
 8067        };
 8068
 8069        let autoscroll = if action.center_cursor {
 8070            Autoscroll::center()
 8071        } else {
 8072            Autoscroll::fit()
 8073        };
 8074
 8075        let text_layout_details = &self.text_layout_details(window);
 8076
 8077        self.change_selections(Some(autoscroll), window, cx, |s| {
 8078            let line_mode = s.line_mode;
 8079            s.move_with(|map, selection| {
 8080                if !selection.is_empty() && !line_mode {
 8081                    selection.goal = SelectionGoal::None;
 8082                }
 8083                let (cursor, goal) = movement::up_by_rows(
 8084                    map,
 8085                    selection.end,
 8086                    row_count,
 8087                    selection.goal,
 8088                    false,
 8089                    text_layout_details,
 8090                );
 8091                selection.collapse_to(cursor, goal);
 8092            });
 8093        });
 8094    }
 8095
 8096    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8097        let text_layout_details = &self.text_layout_details(window);
 8098        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8099            s.move_heads_with(|map, head, goal| {
 8100                movement::up(map, head, goal, false, text_layout_details)
 8101            })
 8102        })
 8103    }
 8104
 8105    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8106        self.take_rename(true, window, cx);
 8107
 8108        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8109            cx.propagate();
 8110            return;
 8111        }
 8112
 8113        let text_layout_details = &self.text_layout_details(window);
 8114        let selection_count = self.selections.count();
 8115        let first_selection = self.selections.first_anchor();
 8116
 8117        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8118            let line_mode = s.line_mode;
 8119            s.move_with(|map, selection| {
 8120                if !selection.is_empty() && !line_mode {
 8121                    selection.goal = SelectionGoal::None;
 8122                }
 8123                let (cursor, goal) = movement::down(
 8124                    map,
 8125                    selection.end,
 8126                    selection.goal,
 8127                    false,
 8128                    text_layout_details,
 8129                );
 8130                selection.collapse_to(cursor, goal);
 8131            });
 8132        });
 8133
 8134        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8135        {
 8136            cx.propagate();
 8137        }
 8138    }
 8139
 8140    pub fn select_page_down(
 8141        &mut self,
 8142        _: &SelectPageDown,
 8143        window: &mut Window,
 8144        cx: &mut Context<Self>,
 8145    ) {
 8146        let Some(row_count) = self.visible_row_count() else {
 8147            return;
 8148        };
 8149
 8150        let text_layout_details = &self.text_layout_details(window);
 8151
 8152        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8153            s.move_heads_with(|map, head, goal| {
 8154                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8155            })
 8156        })
 8157    }
 8158
 8159    pub fn move_page_down(
 8160        &mut self,
 8161        action: &MovePageDown,
 8162        window: &mut Window,
 8163        cx: &mut Context<Self>,
 8164    ) {
 8165        if self.take_rename(true, window, cx).is_some() {
 8166            return;
 8167        }
 8168
 8169        if self
 8170            .context_menu
 8171            .borrow_mut()
 8172            .as_mut()
 8173            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8174            .unwrap_or(false)
 8175        {
 8176            return;
 8177        }
 8178
 8179        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8180            cx.propagate();
 8181            return;
 8182        }
 8183
 8184        let Some(row_count) = self.visible_row_count() else {
 8185            return;
 8186        };
 8187
 8188        let autoscroll = if action.center_cursor {
 8189            Autoscroll::center()
 8190        } else {
 8191            Autoscroll::fit()
 8192        };
 8193
 8194        let text_layout_details = &self.text_layout_details(window);
 8195        self.change_selections(Some(autoscroll), window, cx, |s| {
 8196            let line_mode = s.line_mode;
 8197            s.move_with(|map, selection| {
 8198                if !selection.is_empty() && !line_mode {
 8199                    selection.goal = SelectionGoal::None;
 8200                }
 8201                let (cursor, goal) = movement::down_by_rows(
 8202                    map,
 8203                    selection.end,
 8204                    row_count,
 8205                    selection.goal,
 8206                    false,
 8207                    text_layout_details,
 8208                );
 8209                selection.collapse_to(cursor, goal);
 8210            });
 8211        });
 8212    }
 8213
 8214    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8215        let text_layout_details = &self.text_layout_details(window);
 8216        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8217            s.move_heads_with(|map, head, goal| {
 8218                movement::down(map, head, goal, false, text_layout_details)
 8219            })
 8220        });
 8221    }
 8222
 8223    pub fn context_menu_first(
 8224        &mut self,
 8225        _: &ContextMenuFirst,
 8226        _window: &mut Window,
 8227        cx: &mut Context<Self>,
 8228    ) {
 8229        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8230            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8231        }
 8232    }
 8233
 8234    pub fn context_menu_prev(
 8235        &mut self,
 8236        _: &ContextMenuPrev,
 8237        _window: &mut Window,
 8238        cx: &mut Context<Self>,
 8239    ) {
 8240        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8241            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8242        }
 8243    }
 8244
 8245    pub fn context_menu_next(
 8246        &mut self,
 8247        _: &ContextMenuNext,
 8248        _window: &mut Window,
 8249        cx: &mut Context<Self>,
 8250    ) {
 8251        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8252            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8253        }
 8254    }
 8255
 8256    pub fn context_menu_last(
 8257        &mut self,
 8258        _: &ContextMenuLast,
 8259        _window: &mut Window,
 8260        cx: &mut Context<Self>,
 8261    ) {
 8262        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8263            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8264        }
 8265    }
 8266
 8267    pub fn move_to_previous_word_start(
 8268        &mut self,
 8269        _: &MoveToPreviousWordStart,
 8270        window: &mut Window,
 8271        cx: &mut Context<Self>,
 8272    ) {
 8273        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8274            s.move_cursors_with(|map, head, _| {
 8275                (
 8276                    movement::previous_word_start(map, head),
 8277                    SelectionGoal::None,
 8278                )
 8279            });
 8280        })
 8281    }
 8282
 8283    pub fn move_to_previous_subword_start(
 8284        &mut self,
 8285        _: &MoveToPreviousSubwordStart,
 8286        window: &mut Window,
 8287        cx: &mut Context<Self>,
 8288    ) {
 8289        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8290            s.move_cursors_with(|map, head, _| {
 8291                (
 8292                    movement::previous_subword_start(map, head),
 8293                    SelectionGoal::None,
 8294                )
 8295            });
 8296        })
 8297    }
 8298
 8299    pub fn select_to_previous_word_start(
 8300        &mut self,
 8301        _: &SelectToPreviousWordStart,
 8302        window: &mut Window,
 8303        cx: &mut Context<Self>,
 8304    ) {
 8305        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8306            s.move_heads_with(|map, head, _| {
 8307                (
 8308                    movement::previous_word_start(map, head),
 8309                    SelectionGoal::None,
 8310                )
 8311            });
 8312        })
 8313    }
 8314
 8315    pub fn select_to_previous_subword_start(
 8316        &mut self,
 8317        _: &SelectToPreviousSubwordStart,
 8318        window: &mut Window,
 8319        cx: &mut Context<Self>,
 8320    ) {
 8321        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8322            s.move_heads_with(|map, head, _| {
 8323                (
 8324                    movement::previous_subword_start(map, head),
 8325                    SelectionGoal::None,
 8326                )
 8327            });
 8328        })
 8329    }
 8330
 8331    pub fn delete_to_previous_word_start(
 8332        &mut self,
 8333        action: &DeleteToPreviousWordStart,
 8334        window: &mut Window,
 8335        cx: &mut Context<Self>,
 8336    ) {
 8337        self.transact(window, cx, |this, window, cx| {
 8338            this.select_autoclose_pair(window, cx);
 8339            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8340                let line_mode = s.line_mode;
 8341                s.move_with(|map, selection| {
 8342                    if selection.is_empty() && !line_mode {
 8343                        let cursor = if action.ignore_newlines {
 8344                            movement::previous_word_start(map, selection.head())
 8345                        } else {
 8346                            movement::previous_word_start_or_newline(map, selection.head())
 8347                        };
 8348                        selection.set_head(cursor, SelectionGoal::None);
 8349                    }
 8350                });
 8351            });
 8352            this.insert("", window, cx);
 8353        });
 8354    }
 8355
 8356    pub fn delete_to_previous_subword_start(
 8357        &mut self,
 8358        _: &DeleteToPreviousSubwordStart,
 8359        window: &mut Window,
 8360        cx: &mut Context<Self>,
 8361    ) {
 8362        self.transact(window, cx, |this, window, cx| {
 8363            this.select_autoclose_pair(window, cx);
 8364            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8365                let line_mode = s.line_mode;
 8366                s.move_with(|map, selection| {
 8367                    if selection.is_empty() && !line_mode {
 8368                        let cursor = movement::previous_subword_start(map, selection.head());
 8369                        selection.set_head(cursor, SelectionGoal::None);
 8370                    }
 8371                });
 8372            });
 8373            this.insert("", window, cx);
 8374        });
 8375    }
 8376
 8377    pub fn move_to_next_word_end(
 8378        &mut self,
 8379        _: &MoveToNextWordEnd,
 8380        window: &mut Window,
 8381        cx: &mut Context<Self>,
 8382    ) {
 8383        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8384            s.move_cursors_with(|map, head, _| {
 8385                (movement::next_word_end(map, head), SelectionGoal::None)
 8386            });
 8387        })
 8388    }
 8389
 8390    pub fn move_to_next_subword_end(
 8391        &mut self,
 8392        _: &MoveToNextSubwordEnd,
 8393        window: &mut Window,
 8394        cx: &mut Context<Self>,
 8395    ) {
 8396        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8397            s.move_cursors_with(|map, head, _| {
 8398                (movement::next_subword_end(map, head), SelectionGoal::None)
 8399            });
 8400        })
 8401    }
 8402
 8403    pub fn select_to_next_word_end(
 8404        &mut self,
 8405        _: &SelectToNextWordEnd,
 8406        window: &mut Window,
 8407        cx: &mut Context<Self>,
 8408    ) {
 8409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8410            s.move_heads_with(|map, head, _| {
 8411                (movement::next_word_end(map, head), SelectionGoal::None)
 8412            });
 8413        })
 8414    }
 8415
 8416    pub fn select_to_next_subword_end(
 8417        &mut self,
 8418        _: &SelectToNextSubwordEnd,
 8419        window: &mut Window,
 8420        cx: &mut Context<Self>,
 8421    ) {
 8422        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8423            s.move_heads_with(|map, head, _| {
 8424                (movement::next_subword_end(map, head), SelectionGoal::None)
 8425            });
 8426        })
 8427    }
 8428
 8429    pub fn delete_to_next_word_end(
 8430        &mut self,
 8431        action: &DeleteToNextWordEnd,
 8432        window: &mut Window,
 8433        cx: &mut Context<Self>,
 8434    ) {
 8435        self.transact(window, cx, |this, window, cx| {
 8436            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8437                let line_mode = s.line_mode;
 8438                s.move_with(|map, selection| {
 8439                    if selection.is_empty() && !line_mode {
 8440                        let cursor = if action.ignore_newlines {
 8441                            movement::next_word_end(map, selection.head())
 8442                        } else {
 8443                            movement::next_word_end_or_newline(map, selection.head())
 8444                        };
 8445                        selection.set_head(cursor, SelectionGoal::None);
 8446                    }
 8447                });
 8448            });
 8449            this.insert("", window, cx);
 8450        });
 8451    }
 8452
 8453    pub fn delete_to_next_subword_end(
 8454        &mut self,
 8455        _: &DeleteToNextSubwordEnd,
 8456        window: &mut Window,
 8457        cx: &mut Context<Self>,
 8458    ) {
 8459        self.transact(window, cx, |this, window, cx| {
 8460            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8461                s.move_with(|map, selection| {
 8462                    if selection.is_empty() {
 8463                        let cursor = movement::next_subword_end(map, selection.head());
 8464                        selection.set_head(cursor, SelectionGoal::None);
 8465                    }
 8466                });
 8467            });
 8468            this.insert("", window, cx);
 8469        });
 8470    }
 8471
 8472    pub fn move_to_beginning_of_line(
 8473        &mut self,
 8474        action: &MoveToBeginningOfLine,
 8475        window: &mut Window,
 8476        cx: &mut Context<Self>,
 8477    ) {
 8478        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8479            s.move_cursors_with(|map, head, _| {
 8480                (
 8481                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8482                    SelectionGoal::None,
 8483                )
 8484            });
 8485        })
 8486    }
 8487
 8488    pub fn select_to_beginning_of_line(
 8489        &mut self,
 8490        action: &SelectToBeginningOfLine,
 8491        window: &mut Window,
 8492        cx: &mut Context<Self>,
 8493    ) {
 8494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8495            s.move_heads_with(|map, head, _| {
 8496                (
 8497                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8498                    SelectionGoal::None,
 8499                )
 8500            });
 8501        });
 8502    }
 8503
 8504    pub fn delete_to_beginning_of_line(
 8505        &mut self,
 8506        _: &DeleteToBeginningOfLine,
 8507        window: &mut Window,
 8508        cx: &mut Context<Self>,
 8509    ) {
 8510        self.transact(window, cx, |this, window, cx| {
 8511            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8512                s.move_with(|_, selection| {
 8513                    selection.reversed = true;
 8514                });
 8515            });
 8516
 8517            this.select_to_beginning_of_line(
 8518                &SelectToBeginningOfLine {
 8519                    stop_at_soft_wraps: false,
 8520                },
 8521                window,
 8522                cx,
 8523            );
 8524            this.backspace(&Backspace, window, cx);
 8525        });
 8526    }
 8527
 8528    pub fn move_to_end_of_line(
 8529        &mut self,
 8530        action: &MoveToEndOfLine,
 8531        window: &mut Window,
 8532        cx: &mut Context<Self>,
 8533    ) {
 8534        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8535            s.move_cursors_with(|map, head, _| {
 8536                (
 8537                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8538                    SelectionGoal::None,
 8539                )
 8540            });
 8541        })
 8542    }
 8543
 8544    pub fn select_to_end_of_line(
 8545        &mut self,
 8546        action: &SelectToEndOfLine,
 8547        window: &mut Window,
 8548        cx: &mut Context<Self>,
 8549    ) {
 8550        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8551            s.move_heads_with(|map, head, _| {
 8552                (
 8553                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8554                    SelectionGoal::None,
 8555                )
 8556            });
 8557        })
 8558    }
 8559
 8560    pub fn delete_to_end_of_line(
 8561        &mut self,
 8562        _: &DeleteToEndOfLine,
 8563        window: &mut Window,
 8564        cx: &mut Context<Self>,
 8565    ) {
 8566        self.transact(window, cx, |this, window, cx| {
 8567            this.select_to_end_of_line(
 8568                &SelectToEndOfLine {
 8569                    stop_at_soft_wraps: false,
 8570                },
 8571                window,
 8572                cx,
 8573            );
 8574            this.delete(&Delete, window, cx);
 8575        });
 8576    }
 8577
 8578    pub fn cut_to_end_of_line(
 8579        &mut self,
 8580        _: &CutToEndOfLine,
 8581        window: &mut Window,
 8582        cx: &mut Context<Self>,
 8583    ) {
 8584        self.transact(window, cx, |this, window, cx| {
 8585            this.select_to_end_of_line(
 8586                &SelectToEndOfLine {
 8587                    stop_at_soft_wraps: false,
 8588                },
 8589                window,
 8590                cx,
 8591            );
 8592            this.cut(&Cut, window, cx);
 8593        });
 8594    }
 8595
 8596    pub fn move_to_start_of_paragraph(
 8597        &mut self,
 8598        _: &MoveToStartOfParagraph,
 8599        window: &mut Window,
 8600        cx: &mut Context<Self>,
 8601    ) {
 8602        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8603            cx.propagate();
 8604            return;
 8605        }
 8606
 8607        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608            s.move_with(|map, selection| {
 8609                selection.collapse_to(
 8610                    movement::start_of_paragraph(map, selection.head(), 1),
 8611                    SelectionGoal::None,
 8612                )
 8613            });
 8614        })
 8615    }
 8616
 8617    pub fn move_to_end_of_paragraph(
 8618        &mut self,
 8619        _: &MoveToEndOfParagraph,
 8620        window: &mut Window,
 8621        cx: &mut Context<Self>,
 8622    ) {
 8623        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8624            cx.propagate();
 8625            return;
 8626        }
 8627
 8628        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8629            s.move_with(|map, selection| {
 8630                selection.collapse_to(
 8631                    movement::end_of_paragraph(map, selection.head(), 1),
 8632                    SelectionGoal::None,
 8633                )
 8634            });
 8635        })
 8636    }
 8637
 8638    pub fn select_to_start_of_paragraph(
 8639        &mut self,
 8640        _: &SelectToStartOfParagraph,
 8641        window: &mut Window,
 8642        cx: &mut Context<Self>,
 8643    ) {
 8644        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8645            cx.propagate();
 8646            return;
 8647        }
 8648
 8649        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8650            s.move_heads_with(|map, head, _| {
 8651                (
 8652                    movement::start_of_paragraph(map, head, 1),
 8653                    SelectionGoal::None,
 8654                )
 8655            });
 8656        })
 8657    }
 8658
 8659    pub fn select_to_end_of_paragraph(
 8660        &mut self,
 8661        _: &SelectToEndOfParagraph,
 8662        window: &mut Window,
 8663        cx: &mut Context<Self>,
 8664    ) {
 8665        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8666            cx.propagate();
 8667            return;
 8668        }
 8669
 8670        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8671            s.move_heads_with(|map, head, _| {
 8672                (
 8673                    movement::end_of_paragraph(map, head, 1),
 8674                    SelectionGoal::None,
 8675                )
 8676            });
 8677        })
 8678    }
 8679
 8680    pub fn move_to_beginning(
 8681        &mut self,
 8682        _: &MoveToBeginning,
 8683        window: &mut Window,
 8684        cx: &mut Context<Self>,
 8685    ) {
 8686        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8687            cx.propagate();
 8688            return;
 8689        }
 8690
 8691        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8692            s.select_ranges(vec![0..0]);
 8693        });
 8694    }
 8695
 8696    pub fn select_to_beginning(
 8697        &mut self,
 8698        _: &SelectToBeginning,
 8699        window: &mut Window,
 8700        cx: &mut Context<Self>,
 8701    ) {
 8702        let mut selection = self.selections.last::<Point>(cx);
 8703        selection.set_head(Point::zero(), SelectionGoal::None);
 8704
 8705        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8706            s.select(vec![selection]);
 8707        });
 8708    }
 8709
 8710    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8711        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8712            cx.propagate();
 8713            return;
 8714        }
 8715
 8716        let cursor = self.buffer.read(cx).read(cx).len();
 8717        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8718            s.select_ranges(vec![cursor..cursor])
 8719        });
 8720    }
 8721
 8722    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8723        self.nav_history = nav_history;
 8724    }
 8725
 8726    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8727        self.nav_history.as_ref()
 8728    }
 8729
 8730    fn push_to_nav_history(
 8731        &mut self,
 8732        cursor_anchor: Anchor,
 8733        new_position: Option<Point>,
 8734        cx: &mut Context<Self>,
 8735    ) {
 8736        if let Some(nav_history) = self.nav_history.as_mut() {
 8737            let buffer = self.buffer.read(cx).read(cx);
 8738            let cursor_position = cursor_anchor.to_point(&buffer);
 8739            let scroll_state = self.scroll_manager.anchor();
 8740            let scroll_top_row = scroll_state.top_row(&buffer);
 8741            drop(buffer);
 8742
 8743            if let Some(new_position) = new_position {
 8744                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8745                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8746                    return;
 8747                }
 8748            }
 8749
 8750            nav_history.push(
 8751                Some(NavigationData {
 8752                    cursor_anchor,
 8753                    cursor_position,
 8754                    scroll_anchor: scroll_state,
 8755                    scroll_top_row,
 8756                }),
 8757                cx,
 8758            );
 8759        }
 8760    }
 8761
 8762    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8763        let buffer = self.buffer.read(cx).snapshot(cx);
 8764        let mut selection = self.selections.first::<usize>(cx);
 8765        selection.set_head(buffer.len(), SelectionGoal::None);
 8766        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8767            s.select(vec![selection]);
 8768        });
 8769    }
 8770
 8771    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8772        let end = self.buffer.read(cx).read(cx).len();
 8773        self.change_selections(None, window, cx, |s| {
 8774            s.select_ranges(vec![0..end]);
 8775        });
 8776    }
 8777
 8778    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8779        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8780        let mut selections = self.selections.all::<Point>(cx);
 8781        let max_point = display_map.buffer_snapshot.max_point();
 8782        for selection in &mut selections {
 8783            let rows = selection.spanned_rows(true, &display_map);
 8784            selection.start = Point::new(rows.start.0, 0);
 8785            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8786            selection.reversed = false;
 8787        }
 8788        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8789            s.select(selections);
 8790        });
 8791    }
 8792
 8793    pub fn split_selection_into_lines(
 8794        &mut self,
 8795        _: &SplitSelectionIntoLines,
 8796        window: &mut Window,
 8797        cx: &mut Context<Self>,
 8798    ) {
 8799        let mut to_unfold = Vec::new();
 8800        let mut new_selection_ranges = Vec::new();
 8801        {
 8802            let selections = self.selections.all::<Point>(cx);
 8803            let buffer = self.buffer.read(cx).read(cx);
 8804            for selection in selections {
 8805                for row in selection.start.row..selection.end.row {
 8806                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8807                    new_selection_ranges.push(cursor..cursor);
 8808                }
 8809                new_selection_ranges.push(selection.end..selection.end);
 8810                to_unfold.push(selection.start..selection.end);
 8811            }
 8812        }
 8813        self.unfold_ranges(&to_unfold, true, true, cx);
 8814        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8815            s.select_ranges(new_selection_ranges);
 8816        });
 8817    }
 8818
 8819    pub fn add_selection_above(
 8820        &mut self,
 8821        _: &AddSelectionAbove,
 8822        window: &mut Window,
 8823        cx: &mut Context<Self>,
 8824    ) {
 8825        self.add_selection(true, window, cx);
 8826    }
 8827
 8828    pub fn add_selection_below(
 8829        &mut self,
 8830        _: &AddSelectionBelow,
 8831        window: &mut Window,
 8832        cx: &mut Context<Self>,
 8833    ) {
 8834        self.add_selection(false, window, cx);
 8835    }
 8836
 8837    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8839        let mut selections = self.selections.all::<Point>(cx);
 8840        let text_layout_details = self.text_layout_details(window);
 8841        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8842            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8843            let range = oldest_selection.display_range(&display_map).sorted();
 8844
 8845            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8846            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8847            let positions = start_x.min(end_x)..start_x.max(end_x);
 8848
 8849            selections.clear();
 8850            let mut stack = Vec::new();
 8851            for row in range.start.row().0..=range.end.row().0 {
 8852                if let Some(selection) = self.selections.build_columnar_selection(
 8853                    &display_map,
 8854                    DisplayRow(row),
 8855                    &positions,
 8856                    oldest_selection.reversed,
 8857                    &text_layout_details,
 8858                ) {
 8859                    stack.push(selection.id);
 8860                    selections.push(selection);
 8861                }
 8862            }
 8863
 8864            if above {
 8865                stack.reverse();
 8866            }
 8867
 8868            AddSelectionsState { above, stack }
 8869        });
 8870
 8871        let last_added_selection = *state.stack.last().unwrap();
 8872        let mut new_selections = Vec::new();
 8873        if above == state.above {
 8874            let end_row = if above {
 8875                DisplayRow(0)
 8876            } else {
 8877                display_map.max_point().row()
 8878            };
 8879
 8880            'outer: for selection in selections {
 8881                if selection.id == last_added_selection {
 8882                    let range = selection.display_range(&display_map).sorted();
 8883                    debug_assert_eq!(range.start.row(), range.end.row());
 8884                    let mut row = range.start.row();
 8885                    let positions =
 8886                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8887                            px(start)..px(end)
 8888                        } else {
 8889                            let start_x =
 8890                                display_map.x_for_display_point(range.start, &text_layout_details);
 8891                            let end_x =
 8892                                display_map.x_for_display_point(range.end, &text_layout_details);
 8893                            start_x.min(end_x)..start_x.max(end_x)
 8894                        };
 8895
 8896                    while row != end_row {
 8897                        if above {
 8898                            row.0 -= 1;
 8899                        } else {
 8900                            row.0 += 1;
 8901                        }
 8902
 8903                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8904                            &display_map,
 8905                            row,
 8906                            &positions,
 8907                            selection.reversed,
 8908                            &text_layout_details,
 8909                        ) {
 8910                            state.stack.push(new_selection.id);
 8911                            if above {
 8912                                new_selections.push(new_selection);
 8913                                new_selections.push(selection);
 8914                            } else {
 8915                                new_selections.push(selection);
 8916                                new_selections.push(new_selection);
 8917                            }
 8918
 8919                            continue 'outer;
 8920                        }
 8921                    }
 8922                }
 8923
 8924                new_selections.push(selection);
 8925            }
 8926        } else {
 8927            new_selections = selections;
 8928            new_selections.retain(|s| s.id != last_added_selection);
 8929            state.stack.pop();
 8930        }
 8931
 8932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8933            s.select(new_selections);
 8934        });
 8935        if state.stack.len() > 1 {
 8936            self.add_selections_state = Some(state);
 8937        }
 8938    }
 8939
 8940    pub fn select_next_match_internal(
 8941        &mut self,
 8942        display_map: &DisplaySnapshot,
 8943        replace_newest: bool,
 8944        autoscroll: Option<Autoscroll>,
 8945        window: &mut Window,
 8946        cx: &mut Context<Self>,
 8947    ) -> Result<()> {
 8948        fn select_next_match_ranges(
 8949            this: &mut Editor,
 8950            range: Range<usize>,
 8951            replace_newest: bool,
 8952            auto_scroll: Option<Autoscroll>,
 8953            window: &mut Window,
 8954            cx: &mut Context<Editor>,
 8955        ) {
 8956            this.unfold_ranges(&[range.clone()], false, true, cx);
 8957            this.change_selections(auto_scroll, window, cx, |s| {
 8958                if replace_newest {
 8959                    s.delete(s.newest_anchor().id);
 8960                }
 8961                s.insert_range(range.clone());
 8962            });
 8963        }
 8964
 8965        let buffer = &display_map.buffer_snapshot;
 8966        let mut selections = self.selections.all::<usize>(cx);
 8967        if let Some(mut select_next_state) = self.select_next_state.take() {
 8968            let query = &select_next_state.query;
 8969            if !select_next_state.done {
 8970                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8971                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8972                let mut next_selected_range = None;
 8973
 8974                let bytes_after_last_selection =
 8975                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8976                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8977                let query_matches = query
 8978                    .stream_find_iter(bytes_after_last_selection)
 8979                    .map(|result| (last_selection.end, result))
 8980                    .chain(
 8981                        query
 8982                            .stream_find_iter(bytes_before_first_selection)
 8983                            .map(|result| (0, result)),
 8984                    );
 8985
 8986                for (start_offset, query_match) in query_matches {
 8987                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8988                    let offset_range =
 8989                        start_offset + query_match.start()..start_offset + query_match.end();
 8990                    let display_range = offset_range.start.to_display_point(display_map)
 8991                        ..offset_range.end.to_display_point(display_map);
 8992
 8993                    if !select_next_state.wordwise
 8994                        || (!movement::is_inside_word(display_map, display_range.start)
 8995                            && !movement::is_inside_word(display_map, display_range.end))
 8996                    {
 8997                        // TODO: This is n^2, because we might check all the selections
 8998                        if !selections
 8999                            .iter()
 9000                            .any(|selection| selection.range().overlaps(&offset_range))
 9001                        {
 9002                            next_selected_range = Some(offset_range);
 9003                            break;
 9004                        }
 9005                    }
 9006                }
 9007
 9008                if let Some(next_selected_range) = next_selected_range {
 9009                    select_next_match_ranges(
 9010                        self,
 9011                        next_selected_range,
 9012                        replace_newest,
 9013                        autoscroll,
 9014                        window,
 9015                        cx,
 9016                    );
 9017                } else {
 9018                    select_next_state.done = true;
 9019                }
 9020            }
 9021
 9022            self.select_next_state = Some(select_next_state);
 9023        } else {
 9024            let mut only_carets = true;
 9025            let mut same_text_selected = true;
 9026            let mut selected_text = None;
 9027
 9028            let mut selections_iter = selections.iter().peekable();
 9029            while let Some(selection) = selections_iter.next() {
 9030                if selection.start != selection.end {
 9031                    only_carets = false;
 9032                }
 9033
 9034                if same_text_selected {
 9035                    if selected_text.is_none() {
 9036                        selected_text =
 9037                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9038                    }
 9039
 9040                    if let Some(next_selection) = selections_iter.peek() {
 9041                        if next_selection.range().len() == selection.range().len() {
 9042                            let next_selected_text = buffer
 9043                                .text_for_range(next_selection.range())
 9044                                .collect::<String>();
 9045                            if Some(next_selected_text) != selected_text {
 9046                                same_text_selected = false;
 9047                                selected_text = None;
 9048                            }
 9049                        } else {
 9050                            same_text_selected = false;
 9051                            selected_text = None;
 9052                        }
 9053                    }
 9054                }
 9055            }
 9056
 9057            if only_carets {
 9058                for selection in &mut selections {
 9059                    let word_range = movement::surrounding_word(
 9060                        display_map,
 9061                        selection.start.to_display_point(display_map),
 9062                    );
 9063                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9064                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9065                    selection.goal = SelectionGoal::None;
 9066                    selection.reversed = false;
 9067                    select_next_match_ranges(
 9068                        self,
 9069                        selection.start..selection.end,
 9070                        replace_newest,
 9071                        autoscroll,
 9072                        window,
 9073                        cx,
 9074                    );
 9075                }
 9076
 9077                if selections.len() == 1 {
 9078                    let selection = selections
 9079                        .last()
 9080                        .expect("ensured that there's only one selection");
 9081                    let query = buffer
 9082                        .text_for_range(selection.start..selection.end)
 9083                        .collect::<String>();
 9084                    let is_empty = query.is_empty();
 9085                    let select_state = SelectNextState {
 9086                        query: AhoCorasick::new(&[query])?,
 9087                        wordwise: true,
 9088                        done: is_empty,
 9089                    };
 9090                    self.select_next_state = Some(select_state);
 9091                } else {
 9092                    self.select_next_state = None;
 9093                }
 9094            } else if let Some(selected_text) = selected_text {
 9095                self.select_next_state = Some(SelectNextState {
 9096                    query: AhoCorasick::new(&[selected_text])?,
 9097                    wordwise: false,
 9098                    done: false,
 9099                });
 9100                self.select_next_match_internal(
 9101                    display_map,
 9102                    replace_newest,
 9103                    autoscroll,
 9104                    window,
 9105                    cx,
 9106                )?;
 9107            }
 9108        }
 9109        Ok(())
 9110    }
 9111
 9112    pub fn select_all_matches(
 9113        &mut self,
 9114        _action: &SelectAllMatches,
 9115        window: &mut Window,
 9116        cx: &mut Context<Self>,
 9117    ) -> Result<()> {
 9118        self.push_to_selection_history();
 9119        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9120
 9121        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9122        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9123            return Ok(());
 9124        };
 9125        if select_next_state.done {
 9126            return Ok(());
 9127        }
 9128
 9129        let mut new_selections = self.selections.all::<usize>(cx);
 9130
 9131        let buffer = &display_map.buffer_snapshot;
 9132        let query_matches = select_next_state
 9133            .query
 9134            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9135
 9136        for query_match in query_matches {
 9137            let query_match = query_match.unwrap(); // can only fail due to I/O
 9138            let offset_range = query_match.start()..query_match.end();
 9139            let display_range = offset_range.start.to_display_point(&display_map)
 9140                ..offset_range.end.to_display_point(&display_map);
 9141
 9142            if !select_next_state.wordwise
 9143                || (!movement::is_inside_word(&display_map, display_range.start)
 9144                    && !movement::is_inside_word(&display_map, display_range.end))
 9145            {
 9146                self.selections.change_with(cx, |selections| {
 9147                    new_selections.push(Selection {
 9148                        id: selections.new_selection_id(),
 9149                        start: offset_range.start,
 9150                        end: offset_range.end,
 9151                        reversed: false,
 9152                        goal: SelectionGoal::None,
 9153                    });
 9154                });
 9155            }
 9156        }
 9157
 9158        new_selections.sort_by_key(|selection| selection.start);
 9159        let mut ix = 0;
 9160        while ix + 1 < new_selections.len() {
 9161            let current_selection = &new_selections[ix];
 9162            let next_selection = &new_selections[ix + 1];
 9163            if current_selection.range().overlaps(&next_selection.range()) {
 9164                if current_selection.id < next_selection.id {
 9165                    new_selections.remove(ix + 1);
 9166                } else {
 9167                    new_selections.remove(ix);
 9168                }
 9169            } else {
 9170                ix += 1;
 9171            }
 9172        }
 9173
 9174        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9175
 9176        for selection in new_selections.iter_mut() {
 9177            selection.reversed = reversed;
 9178        }
 9179
 9180        select_next_state.done = true;
 9181        self.unfold_ranges(
 9182            &new_selections
 9183                .iter()
 9184                .map(|selection| selection.range())
 9185                .collect::<Vec<_>>(),
 9186            false,
 9187            false,
 9188            cx,
 9189        );
 9190        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9191            selections.select(new_selections)
 9192        });
 9193
 9194        Ok(())
 9195    }
 9196
 9197    pub fn select_next(
 9198        &mut self,
 9199        action: &SelectNext,
 9200        window: &mut Window,
 9201        cx: &mut Context<Self>,
 9202    ) -> Result<()> {
 9203        self.push_to_selection_history();
 9204        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9205        self.select_next_match_internal(
 9206            &display_map,
 9207            action.replace_newest,
 9208            Some(Autoscroll::newest()),
 9209            window,
 9210            cx,
 9211        )?;
 9212        Ok(())
 9213    }
 9214
 9215    pub fn select_previous(
 9216        &mut self,
 9217        action: &SelectPrevious,
 9218        window: &mut Window,
 9219        cx: &mut Context<Self>,
 9220    ) -> Result<()> {
 9221        self.push_to_selection_history();
 9222        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9223        let buffer = &display_map.buffer_snapshot;
 9224        let mut selections = self.selections.all::<usize>(cx);
 9225        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9226            let query = &select_prev_state.query;
 9227            if !select_prev_state.done {
 9228                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9229                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9230                let mut next_selected_range = None;
 9231                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9232                let bytes_before_last_selection =
 9233                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9234                let bytes_after_first_selection =
 9235                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9236                let query_matches = query
 9237                    .stream_find_iter(bytes_before_last_selection)
 9238                    .map(|result| (last_selection.start, result))
 9239                    .chain(
 9240                        query
 9241                            .stream_find_iter(bytes_after_first_selection)
 9242                            .map(|result| (buffer.len(), result)),
 9243                    );
 9244                for (end_offset, query_match) in query_matches {
 9245                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9246                    let offset_range =
 9247                        end_offset - query_match.end()..end_offset - query_match.start();
 9248                    let display_range = offset_range.start.to_display_point(&display_map)
 9249                        ..offset_range.end.to_display_point(&display_map);
 9250
 9251                    if !select_prev_state.wordwise
 9252                        || (!movement::is_inside_word(&display_map, display_range.start)
 9253                            && !movement::is_inside_word(&display_map, display_range.end))
 9254                    {
 9255                        next_selected_range = Some(offset_range);
 9256                        break;
 9257                    }
 9258                }
 9259
 9260                if let Some(next_selected_range) = next_selected_range {
 9261                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9262                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9263                        if action.replace_newest {
 9264                            s.delete(s.newest_anchor().id);
 9265                        }
 9266                        s.insert_range(next_selected_range);
 9267                    });
 9268                } else {
 9269                    select_prev_state.done = true;
 9270                }
 9271            }
 9272
 9273            self.select_prev_state = Some(select_prev_state);
 9274        } else {
 9275            let mut only_carets = true;
 9276            let mut same_text_selected = true;
 9277            let mut selected_text = None;
 9278
 9279            let mut selections_iter = selections.iter().peekable();
 9280            while let Some(selection) = selections_iter.next() {
 9281                if selection.start != selection.end {
 9282                    only_carets = false;
 9283                }
 9284
 9285                if same_text_selected {
 9286                    if selected_text.is_none() {
 9287                        selected_text =
 9288                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9289                    }
 9290
 9291                    if let Some(next_selection) = selections_iter.peek() {
 9292                        if next_selection.range().len() == selection.range().len() {
 9293                            let next_selected_text = buffer
 9294                                .text_for_range(next_selection.range())
 9295                                .collect::<String>();
 9296                            if Some(next_selected_text) != selected_text {
 9297                                same_text_selected = false;
 9298                                selected_text = None;
 9299                            }
 9300                        } else {
 9301                            same_text_selected = false;
 9302                            selected_text = None;
 9303                        }
 9304                    }
 9305                }
 9306            }
 9307
 9308            if only_carets {
 9309                for selection in &mut selections {
 9310                    let word_range = movement::surrounding_word(
 9311                        &display_map,
 9312                        selection.start.to_display_point(&display_map),
 9313                    );
 9314                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9315                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9316                    selection.goal = SelectionGoal::None;
 9317                    selection.reversed = false;
 9318                }
 9319                if selections.len() == 1 {
 9320                    let selection = selections
 9321                        .last()
 9322                        .expect("ensured that there's only one selection");
 9323                    let query = buffer
 9324                        .text_for_range(selection.start..selection.end)
 9325                        .collect::<String>();
 9326                    let is_empty = query.is_empty();
 9327                    let select_state = SelectNextState {
 9328                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9329                        wordwise: true,
 9330                        done: is_empty,
 9331                    };
 9332                    self.select_prev_state = Some(select_state);
 9333                } else {
 9334                    self.select_prev_state = None;
 9335                }
 9336
 9337                self.unfold_ranges(
 9338                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9339                    false,
 9340                    true,
 9341                    cx,
 9342                );
 9343                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9344                    s.select(selections);
 9345                });
 9346            } else if let Some(selected_text) = selected_text {
 9347                self.select_prev_state = Some(SelectNextState {
 9348                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9349                    wordwise: false,
 9350                    done: false,
 9351                });
 9352                self.select_previous(action, window, cx)?;
 9353            }
 9354        }
 9355        Ok(())
 9356    }
 9357
 9358    pub fn toggle_comments(
 9359        &mut self,
 9360        action: &ToggleComments,
 9361        window: &mut Window,
 9362        cx: &mut Context<Self>,
 9363    ) {
 9364        if self.read_only(cx) {
 9365            return;
 9366        }
 9367        let text_layout_details = &self.text_layout_details(window);
 9368        self.transact(window, cx, |this, window, cx| {
 9369            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9370            let mut edits = Vec::new();
 9371            let mut selection_edit_ranges = Vec::new();
 9372            let mut last_toggled_row = None;
 9373            let snapshot = this.buffer.read(cx).read(cx);
 9374            let empty_str: Arc<str> = Arc::default();
 9375            let mut suffixes_inserted = Vec::new();
 9376            let ignore_indent = action.ignore_indent;
 9377
 9378            fn comment_prefix_range(
 9379                snapshot: &MultiBufferSnapshot,
 9380                row: MultiBufferRow,
 9381                comment_prefix: &str,
 9382                comment_prefix_whitespace: &str,
 9383                ignore_indent: bool,
 9384            ) -> Range<Point> {
 9385                let indent_size = if ignore_indent {
 9386                    0
 9387                } else {
 9388                    snapshot.indent_size_for_line(row).len
 9389                };
 9390
 9391                let start = Point::new(row.0, indent_size);
 9392
 9393                let mut line_bytes = snapshot
 9394                    .bytes_in_range(start..snapshot.max_point())
 9395                    .flatten()
 9396                    .copied();
 9397
 9398                // If this line currently begins with the line comment prefix, then record
 9399                // the range containing the prefix.
 9400                if line_bytes
 9401                    .by_ref()
 9402                    .take(comment_prefix.len())
 9403                    .eq(comment_prefix.bytes())
 9404                {
 9405                    // Include any whitespace that matches the comment prefix.
 9406                    let matching_whitespace_len = line_bytes
 9407                        .zip(comment_prefix_whitespace.bytes())
 9408                        .take_while(|(a, b)| a == b)
 9409                        .count() as u32;
 9410                    let end = Point::new(
 9411                        start.row,
 9412                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9413                    );
 9414                    start..end
 9415                } else {
 9416                    start..start
 9417                }
 9418            }
 9419
 9420            fn comment_suffix_range(
 9421                snapshot: &MultiBufferSnapshot,
 9422                row: MultiBufferRow,
 9423                comment_suffix: &str,
 9424                comment_suffix_has_leading_space: bool,
 9425            ) -> Range<Point> {
 9426                let end = Point::new(row.0, snapshot.line_len(row));
 9427                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9428
 9429                let mut line_end_bytes = snapshot
 9430                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9431                    .flatten()
 9432                    .copied();
 9433
 9434                let leading_space_len = if suffix_start_column > 0
 9435                    && line_end_bytes.next() == Some(b' ')
 9436                    && comment_suffix_has_leading_space
 9437                {
 9438                    1
 9439                } else {
 9440                    0
 9441                };
 9442
 9443                // If this line currently begins with the line comment prefix, then record
 9444                // the range containing the prefix.
 9445                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9446                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9447                    start..end
 9448                } else {
 9449                    end..end
 9450                }
 9451            }
 9452
 9453            // TODO: Handle selections that cross excerpts
 9454            for selection in &mut selections {
 9455                let start_column = snapshot
 9456                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9457                    .len;
 9458                let language = if let Some(language) =
 9459                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9460                {
 9461                    language
 9462                } else {
 9463                    continue;
 9464                };
 9465
 9466                selection_edit_ranges.clear();
 9467
 9468                // If multiple selections contain a given row, avoid processing that
 9469                // row more than once.
 9470                let mut start_row = MultiBufferRow(selection.start.row);
 9471                if last_toggled_row == Some(start_row) {
 9472                    start_row = start_row.next_row();
 9473                }
 9474                let end_row =
 9475                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9476                        MultiBufferRow(selection.end.row - 1)
 9477                    } else {
 9478                        MultiBufferRow(selection.end.row)
 9479                    };
 9480                last_toggled_row = Some(end_row);
 9481
 9482                if start_row > end_row {
 9483                    continue;
 9484                }
 9485
 9486                // If the language has line comments, toggle those.
 9487                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9488
 9489                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9490                if ignore_indent {
 9491                    full_comment_prefixes = full_comment_prefixes
 9492                        .into_iter()
 9493                        .map(|s| Arc::from(s.trim_end()))
 9494                        .collect();
 9495                }
 9496
 9497                if !full_comment_prefixes.is_empty() {
 9498                    let first_prefix = full_comment_prefixes
 9499                        .first()
 9500                        .expect("prefixes is non-empty");
 9501                    let prefix_trimmed_lengths = full_comment_prefixes
 9502                        .iter()
 9503                        .map(|p| p.trim_end_matches(' ').len())
 9504                        .collect::<SmallVec<[usize; 4]>>();
 9505
 9506                    let mut all_selection_lines_are_comments = true;
 9507
 9508                    for row in start_row.0..=end_row.0 {
 9509                        let row = MultiBufferRow(row);
 9510                        if start_row < end_row && snapshot.is_line_blank(row) {
 9511                            continue;
 9512                        }
 9513
 9514                        let prefix_range = full_comment_prefixes
 9515                            .iter()
 9516                            .zip(prefix_trimmed_lengths.iter().copied())
 9517                            .map(|(prefix, trimmed_prefix_len)| {
 9518                                comment_prefix_range(
 9519                                    snapshot.deref(),
 9520                                    row,
 9521                                    &prefix[..trimmed_prefix_len],
 9522                                    &prefix[trimmed_prefix_len..],
 9523                                    ignore_indent,
 9524                                )
 9525                            })
 9526                            .max_by_key(|range| range.end.column - range.start.column)
 9527                            .expect("prefixes is non-empty");
 9528
 9529                        if prefix_range.is_empty() {
 9530                            all_selection_lines_are_comments = false;
 9531                        }
 9532
 9533                        selection_edit_ranges.push(prefix_range);
 9534                    }
 9535
 9536                    if all_selection_lines_are_comments {
 9537                        edits.extend(
 9538                            selection_edit_ranges
 9539                                .iter()
 9540                                .cloned()
 9541                                .map(|range| (range, empty_str.clone())),
 9542                        );
 9543                    } else {
 9544                        let min_column = selection_edit_ranges
 9545                            .iter()
 9546                            .map(|range| range.start.column)
 9547                            .min()
 9548                            .unwrap_or(0);
 9549                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9550                            let position = Point::new(range.start.row, min_column);
 9551                            (position..position, first_prefix.clone())
 9552                        }));
 9553                    }
 9554                } else if let Some((full_comment_prefix, comment_suffix)) =
 9555                    language.block_comment_delimiters()
 9556                {
 9557                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9558                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9559                    let prefix_range = comment_prefix_range(
 9560                        snapshot.deref(),
 9561                        start_row,
 9562                        comment_prefix,
 9563                        comment_prefix_whitespace,
 9564                        ignore_indent,
 9565                    );
 9566                    let suffix_range = comment_suffix_range(
 9567                        snapshot.deref(),
 9568                        end_row,
 9569                        comment_suffix.trim_start_matches(' '),
 9570                        comment_suffix.starts_with(' '),
 9571                    );
 9572
 9573                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9574                        edits.push((
 9575                            prefix_range.start..prefix_range.start,
 9576                            full_comment_prefix.clone(),
 9577                        ));
 9578                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9579                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9580                    } else {
 9581                        edits.push((prefix_range, empty_str.clone()));
 9582                        edits.push((suffix_range, empty_str.clone()));
 9583                    }
 9584                } else {
 9585                    continue;
 9586                }
 9587            }
 9588
 9589            drop(snapshot);
 9590            this.buffer.update(cx, |buffer, cx| {
 9591                buffer.edit(edits, None, cx);
 9592            });
 9593
 9594            // Adjust selections so that they end before any comment suffixes that
 9595            // were inserted.
 9596            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9597            let mut selections = this.selections.all::<Point>(cx);
 9598            let snapshot = this.buffer.read(cx).read(cx);
 9599            for selection in &mut selections {
 9600                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9601                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9602                        Ordering::Less => {
 9603                            suffixes_inserted.next();
 9604                            continue;
 9605                        }
 9606                        Ordering::Greater => break,
 9607                        Ordering::Equal => {
 9608                            if selection.end.column == snapshot.line_len(row) {
 9609                                if selection.is_empty() {
 9610                                    selection.start.column -= suffix_len as u32;
 9611                                }
 9612                                selection.end.column -= suffix_len as u32;
 9613                            }
 9614                            break;
 9615                        }
 9616                    }
 9617                }
 9618            }
 9619
 9620            drop(snapshot);
 9621            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9622                s.select(selections)
 9623            });
 9624
 9625            let selections = this.selections.all::<Point>(cx);
 9626            let selections_on_single_row = selections.windows(2).all(|selections| {
 9627                selections[0].start.row == selections[1].start.row
 9628                    && selections[0].end.row == selections[1].end.row
 9629                    && selections[0].start.row == selections[0].end.row
 9630            });
 9631            let selections_selecting = selections
 9632                .iter()
 9633                .any(|selection| selection.start != selection.end);
 9634            let advance_downwards = action.advance_downwards
 9635                && selections_on_single_row
 9636                && !selections_selecting
 9637                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9638
 9639            if advance_downwards {
 9640                let snapshot = this.buffer.read(cx).snapshot(cx);
 9641
 9642                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9643                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9644                        let mut point = display_point.to_point(display_snapshot);
 9645                        point.row += 1;
 9646                        point = snapshot.clip_point(point, Bias::Left);
 9647                        let display_point = point.to_display_point(display_snapshot);
 9648                        let goal = SelectionGoal::HorizontalPosition(
 9649                            display_snapshot
 9650                                .x_for_display_point(display_point, text_layout_details)
 9651                                .into(),
 9652                        );
 9653                        (display_point, goal)
 9654                    })
 9655                });
 9656            }
 9657        });
 9658    }
 9659
 9660    pub fn select_enclosing_symbol(
 9661        &mut self,
 9662        _: &SelectEnclosingSymbol,
 9663        window: &mut Window,
 9664        cx: &mut Context<Self>,
 9665    ) {
 9666        let buffer = self.buffer.read(cx).snapshot(cx);
 9667        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9668
 9669        fn update_selection(
 9670            selection: &Selection<usize>,
 9671            buffer_snap: &MultiBufferSnapshot,
 9672        ) -> Option<Selection<usize>> {
 9673            let cursor = selection.head();
 9674            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9675            for symbol in symbols.iter().rev() {
 9676                let start = symbol.range.start.to_offset(buffer_snap);
 9677                let end = symbol.range.end.to_offset(buffer_snap);
 9678                let new_range = start..end;
 9679                if start < selection.start || end > selection.end {
 9680                    return Some(Selection {
 9681                        id: selection.id,
 9682                        start: new_range.start,
 9683                        end: new_range.end,
 9684                        goal: SelectionGoal::None,
 9685                        reversed: selection.reversed,
 9686                    });
 9687                }
 9688            }
 9689            None
 9690        }
 9691
 9692        let mut selected_larger_symbol = false;
 9693        let new_selections = old_selections
 9694            .iter()
 9695            .map(|selection| match update_selection(selection, &buffer) {
 9696                Some(new_selection) => {
 9697                    if new_selection.range() != selection.range() {
 9698                        selected_larger_symbol = true;
 9699                    }
 9700                    new_selection
 9701                }
 9702                None => selection.clone(),
 9703            })
 9704            .collect::<Vec<_>>();
 9705
 9706        if selected_larger_symbol {
 9707            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9708                s.select(new_selections);
 9709            });
 9710        }
 9711    }
 9712
 9713    pub fn select_larger_syntax_node(
 9714        &mut self,
 9715        _: &SelectLargerSyntaxNode,
 9716        window: &mut Window,
 9717        cx: &mut Context<Self>,
 9718    ) {
 9719        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9720        let buffer = self.buffer.read(cx).snapshot(cx);
 9721        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9722
 9723        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9724        let mut selected_larger_node = false;
 9725        let new_selections = old_selections
 9726            .iter()
 9727            .map(|selection| {
 9728                let old_range = selection.start..selection.end;
 9729                let mut new_range = old_range.clone();
 9730                let mut new_node = None;
 9731                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9732                {
 9733                    new_node = Some(node);
 9734                    new_range = containing_range;
 9735                    if !display_map.intersects_fold(new_range.start)
 9736                        && !display_map.intersects_fold(new_range.end)
 9737                    {
 9738                        break;
 9739                    }
 9740                }
 9741
 9742                if let Some(node) = new_node {
 9743                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9744                    // nodes. Parent and grandparent are also logged because this operation will not
 9745                    // visit nodes that have the same range as their parent.
 9746                    log::info!("Node: {node:?}");
 9747                    let parent = node.parent();
 9748                    log::info!("Parent: {parent:?}");
 9749                    let grandparent = parent.and_then(|x| x.parent());
 9750                    log::info!("Grandparent: {grandparent:?}");
 9751                }
 9752
 9753                selected_larger_node |= new_range != old_range;
 9754                Selection {
 9755                    id: selection.id,
 9756                    start: new_range.start,
 9757                    end: new_range.end,
 9758                    goal: SelectionGoal::None,
 9759                    reversed: selection.reversed,
 9760                }
 9761            })
 9762            .collect::<Vec<_>>();
 9763
 9764        if selected_larger_node {
 9765            stack.push(old_selections);
 9766            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9767                s.select(new_selections);
 9768            });
 9769        }
 9770        self.select_larger_syntax_node_stack = stack;
 9771    }
 9772
 9773    pub fn select_smaller_syntax_node(
 9774        &mut self,
 9775        _: &SelectSmallerSyntaxNode,
 9776        window: &mut Window,
 9777        cx: &mut Context<Self>,
 9778    ) {
 9779        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9780        if let Some(selections) = stack.pop() {
 9781            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9782                s.select(selections.to_vec());
 9783            });
 9784        }
 9785        self.select_larger_syntax_node_stack = stack;
 9786    }
 9787
 9788    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9789        if !EditorSettings::get_global(cx).gutter.runnables {
 9790            self.clear_tasks();
 9791            return Task::ready(());
 9792        }
 9793        let project = self.project.as_ref().map(Entity::downgrade);
 9794        cx.spawn_in(window, |this, mut cx| async move {
 9795            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9796            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9797                return;
 9798            };
 9799            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9800                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9801            }) else {
 9802                return;
 9803            };
 9804
 9805            let hide_runnables = project
 9806                .update(&mut cx, |project, cx| {
 9807                    // Do not display any test indicators in non-dev server remote projects.
 9808                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9809                })
 9810                .unwrap_or(true);
 9811            if hide_runnables {
 9812                return;
 9813            }
 9814            let new_rows =
 9815                cx.background_executor()
 9816                    .spawn({
 9817                        let snapshot = display_snapshot.clone();
 9818                        async move {
 9819                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9820                        }
 9821                    })
 9822                    .await;
 9823
 9824            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9825            this.update(&mut cx, |this, _| {
 9826                this.clear_tasks();
 9827                for (key, value) in rows {
 9828                    this.insert_tasks(key, value);
 9829                }
 9830            })
 9831            .ok();
 9832        })
 9833    }
 9834    fn fetch_runnable_ranges(
 9835        snapshot: &DisplaySnapshot,
 9836        range: Range<Anchor>,
 9837    ) -> Vec<language::RunnableRange> {
 9838        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9839    }
 9840
 9841    fn runnable_rows(
 9842        project: Entity<Project>,
 9843        snapshot: DisplaySnapshot,
 9844        runnable_ranges: Vec<RunnableRange>,
 9845        mut cx: AsyncWindowContext,
 9846    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9847        runnable_ranges
 9848            .into_iter()
 9849            .filter_map(|mut runnable| {
 9850                let tasks = cx
 9851                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9852                    .ok()?;
 9853                if tasks.is_empty() {
 9854                    return None;
 9855                }
 9856
 9857                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9858
 9859                let row = snapshot
 9860                    .buffer_snapshot
 9861                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9862                    .1
 9863                    .start
 9864                    .row;
 9865
 9866                let context_range =
 9867                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9868                Some((
 9869                    (runnable.buffer_id, row),
 9870                    RunnableTasks {
 9871                        templates: tasks,
 9872                        offset: MultiBufferOffset(runnable.run_range.start),
 9873                        context_range,
 9874                        column: point.column,
 9875                        extra_variables: runnable.extra_captures,
 9876                    },
 9877                ))
 9878            })
 9879            .collect()
 9880    }
 9881
 9882    fn templates_with_tags(
 9883        project: &Entity<Project>,
 9884        runnable: &mut Runnable,
 9885        cx: &mut App,
 9886    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9887        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9888            let (worktree_id, file) = project
 9889                .buffer_for_id(runnable.buffer, cx)
 9890                .and_then(|buffer| buffer.read(cx).file())
 9891                .map(|file| (file.worktree_id(cx), file.clone()))
 9892                .unzip();
 9893
 9894            (
 9895                project.task_store().read(cx).task_inventory().cloned(),
 9896                worktree_id,
 9897                file,
 9898            )
 9899        });
 9900
 9901        let tags = mem::take(&mut runnable.tags);
 9902        let mut tags: Vec<_> = tags
 9903            .into_iter()
 9904            .flat_map(|tag| {
 9905                let tag = tag.0.clone();
 9906                inventory
 9907                    .as_ref()
 9908                    .into_iter()
 9909                    .flat_map(|inventory| {
 9910                        inventory.read(cx).list_tasks(
 9911                            file.clone(),
 9912                            Some(runnable.language.clone()),
 9913                            worktree_id,
 9914                            cx,
 9915                        )
 9916                    })
 9917                    .filter(move |(_, template)| {
 9918                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9919                    })
 9920            })
 9921            .sorted_by_key(|(kind, _)| kind.to_owned())
 9922            .collect();
 9923        if let Some((leading_tag_source, _)) = tags.first() {
 9924            // Strongest source wins; if we have worktree tag binding, prefer that to
 9925            // global and language bindings;
 9926            // if we have a global binding, prefer that to language binding.
 9927            let first_mismatch = tags
 9928                .iter()
 9929                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9930            if let Some(index) = first_mismatch {
 9931                tags.truncate(index);
 9932            }
 9933        }
 9934
 9935        tags
 9936    }
 9937
 9938    pub fn move_to_enclosing_bracket(
 9939        &mut self,
 9940        _: &MoveToEnclosingBracket,
 9941        window: &mut Window,
 9942        cx: &mut Context<Self>,
 9943    ) {
 9944        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9945            s.move_offsets_with(|snapshot, selection| {
 9946                let Some(enclosing_bracket_ranges) =
 9947                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9948                else {
 9949                    return;
 9950                };
 9951
 9952                let mut best_length = usize::MAX;
 9953                let mut best_inside = false;
 9954                let mut best_in_bracket_range = false;
 9955                let mut best_destination = None;
 9956                for (open, close) in enclosing_bracket_ranges {
 9957                    let close = close.to_inclusive();
 9958                    let length = close.end() - open.start;
 9959                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9960                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9961                        || close.contains(&selection.head());
 9962
 9963                    // If best is next to a bracket and current isn't, skip
 9964                    if !in_bracket_range && best_in_bracket_range {
 9965                        continue;
 9966                    }
 9967
 9968                    // Prefer smaller lengths unless best is inside and current isn't
 9969                    if length > best_length && (best_inside || !inside) {
 9970                        continue;
 9971                    }
 9972
 9973                    best_length = length;
 9974                    best_inside = inside;
 9975                    best_in_bracket_range = in_bracket_range;
 9976                    best_destination = Some(
 9977                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9978                            if inside {
 9979                                open.end
 9980                            } else {
 9981                                open.start
 9982                            }
 9983                        } else if inside {
 9984                            *close.start()
 9985                        } else {
 9986                            *close.end()
 9987                        },
 9988                    );
 9989                }
 9990
 9991                if let Some(destination) = best_destination {
 9992                    selection.collapse_to(destination, SelectionGoal::None);
 9993                }
 9994            })
 9995        });
 9996    }
 9997
 9998    pub fn undo_selection(
 9999        &mut self,
10000        _: &UndoSelection,
10001        window: &mut Window,
10002        cx: &mut Context<Self>,
10003    ) {
10004        self.end_selection(window, cx);
10005        self.selection_history.mode = SelectionHistoryMode::Undoing;
10006        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10007            self.change_selections(None, window, cx, |s| {
10008                s.select_anchors(entry.selections.to_vec())
10009            });
10010            self.select_next_state = entry.select_next_state;
10011            self.select_prev_state = entry.select_prev_state;
10012            self.add_selections_state = entry.add_selections_state;
10013            self.request_autoscroll(Autoscroll::newest(), cx);
10014        }
10015        self.selection_history.mode = SelectionHistoryMode::Normal;
10016    }
10017
10018    pub fn redo_selection(
10019        &mut self,
10020        _: &RedoSelection,
10021        window: &mut Window,
10022        cx: &mut Context<Self>,
10023    ) {
10024        self.end_selection(window, cx);
10025        self.selection_history.mode = SelectionHistoryMode::Redoing;
10026        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10027            self.change_selections(None, window, cx, |s| {
10028                s.select_anchors(entry.selections.to_vec())
10029            });
10030            self.select_next_state = entry.select_next_state;
10031            self.select_prev_state = entry.select_prev_state;
10032            self.add_selections_state = entry.add_selections_state;
10033            self.request_autoscroll(Autoscroll::newest(), cx);
10034        }
10035        self.selection_history.mode = SelectionHistoryMode::Normal;
10036    }
10037
10038    pub fn expand_excerpts(
10039        &mut self,
10040        action: &ExpandExcerpts,
10041        _: &mut Window,
10042        cx: &mut Context<Self>,
10043    ) {
10044        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10045    }
10046
10047    pub fn expand_excerpts_down(
10048        &mut self,
10049        action: &ExpandExcerptsDown,
10050        _: &mut Window,
10051        cx: &mut Context<Self>,
10052    ) {
10053        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10054    }
10055
10056    pub fn expand_excerpts_up(
10057        &mut self,
10058        action: &ExpandExcerptsUp,
10059        _: &mut Window,
10060        cx: &mut Context<Self>,
10061    ) {
10062        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10063    }
10064
10065    pub fn expand_excerpts_for_direction(
10066        &mut self,
10067        lines: u32,
10068        direction: ExpandExcerptDirection,
10069
10070        cx: &mut Context<Self>,
10071    ) {
10072        let selections = self.selections.disjoint_anchors();
10073
10074        let lines = if lines == 0 {
10075            EditorSettings::get_global(cx).expand_excerpt_lines
10076        } else {
10077            lines
10078        };
10079
10080        self.buffer.update(cx, |buffer, cx| {
10081            let snapshot = buffer.snapshot(cx);
10082            let mut excerpt_ids = selections
10083                .iter()
10084                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10085                .collect::<Vec<_>>();
10086            excerpt_ids.sort();
10087            excerpt_ids.dedup();
10088            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10089        })
10090    }
10091
10092    pub fn expand_excerpt(
10093        &mut self,
10094        excerpt: ExcerptId,
10095        direction: ExpandExcerptDirection,
10096        cx: &mut Context<Self>,
10097    ) {
10098        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10099        self.buffer.update(cx, |buffer, cx| {
10100            buffer.expand_excerpts([excerpt], lines, direction, cx)
10101        })
10102    }
10103
10104    pub fn go_to_singleton_buffer_point(
10105        &mut self,
10106        point: Point,
10107        window: &mut Window,
10108        cx: &mut Context<Self>,
10109    ) {
10110        self.go_to_singleton_buffer_range(point..point, window, cx);
10111    }
10112
10113    pub fn go_to_singleton_buffer_range(
10114        &mut self,
10115        range: Range<Point>,
10116        window: &mut Window,
10117        cx: &mut Context<Self>,
10118    ) {
10119        let multibuffer = self.buffer().read(cx);
10120        let Some(buffer) = multibuffer.as_singleton() else {
10121            return;
10122        };
10123        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10124            return;
10125        };
10126        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10127            return;
10128        };
10129        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10130            s.select_anchor_ranges([start..end])
10131        });
10132    }
10133
10134    fn go_to_diagnostic(
10135        &mut self,
10136        _: &GoToDiagnostic,
10137        window: &mut Window,
10138        cx: &mut Context<Self>,
10139    ) {
10140        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10141    }
10142
10143    fn go_to_prev_diagnostic(
10144        &mut self,
10145        _: &GoToPrevDiagnostic,
10146        window: &mut Window,
10147        cx: &mut Context<Self>,
10148    ) {
10149        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10150    }
10151
10152    pub fn go_to_diagnostic_impl(
10153        &mut self,
10154        direction: Direction,
10155        window: &mut Window,
10156        cx: &mut Context<Self>,
10157    ) {
10158        let buffer = self.buffer.read(cx).snapshot(cx);
10159        let selection = self.selections.newest::<usize>(cx);
10160
10161        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10162        if direction == Direction::Next {
10163            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10164                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10165                    return;
10166                };
10167                self.activate_diagnostics(
10168                    buffer_id,
10169                    popover.local_diagnostic.diagnostic.group_id,
10170                    window,
10171                    cx,
10172                );
10173                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10174                    let primary_range_start = active_diagnostics.primary_range.start;
10175                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10176                        let mut new_selection = s.newest_anchor().clone();
10177                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10178                        s.select_anchors(vec![new_selection.clone()]);
10179                    });
10180                    self.refresh_inline_completion(false, true, window, cx);
10181                }
10182                return;
10183            }
10184        }
10185
10186        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10187            active_diagnostics
10188                .primary_range
10189                .to_offset(&buffer)
10190                .to_inclusive()
10191        });
10192        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10193            if active_primary_range.contains(&selection.head()) {
10194                *active_primary_range.start()
10195            } else {
10196                selection.head()
10197            }
10198        } else {
10199            selection.head()
10200        };
10201        let snapshot = self.snapshot(window, cx);
10202        loop {
10203            let mut diagnostics;
10204            if direction == Direction::Prev {
10205                diagnostics = buffer
10206                    .diagnostics_in_range::<usize>(0..search_start)
10207                    .collect::<Vec<_>>();
10208                diagnostics.reverse();
10209            } else {
10210                diagnostics = buffer
10211                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10212                    .collect::<Vec<_>>();
10213            };
10214            let group = diagnostics
10215                .into_iter()
10216                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10217                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10218                // be sorted in a stable way
10219                // skip until we are at current active diagnostic, if it exists
10220                .skip_while(|entry| {
10221                    let is_in_range = match direction {
10222                        Direction::Prev => entry.range.end > search_start,
10223                        Direction::Next => entry.range.start < search_start,
10224                    };
10225                    is_in_range
10226                        && self
10227                            .active_diagnostics
10228                            .as_ref()
10229                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10230                })
10231                .find_map(|entry| {
10232                    if entry.diagnostic.is_primary
10233                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10234                        && entry.range.start != entry.range.end
10235                        // if we match with the active diagnostic, skip it
10236                        && Some(entry.diagnostic.group_id)
10237                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10238                    {
10239                        Some((entry.range, entry.diagnostic.group_id))
10240                    } else {
10241                        None
10242                    }
10243                });
10244
10245            if let Some((primary_range, group_id)) = group {
10246                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10247                    return;
10248                };
10249                self.activate_diagnostics(buffer_id, group_id, window, cx);
10250                if self.active_diagnostics.is_some() {
10251                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252                        s.select(vec![Selection {
10253                            id: selection.id,
10254                            start: primary_range.start,
10255                            end: primary_range.start,
10256                            reversed: false,
10257                            goal: SelectionGoal::None,
10258                        }]);
10259                    });
10260                    self.refresh_inline_completion(false, true, window, cx);
10261                }
10262                break;
10263            } else {
10264                // Cycle around to the start of the buffer, potentially moving back to the start of
10265                // the currently active diagnostic.
10266                active_primary_range.take();
10267                if direction == Direction::Prev {
10268                    if search_start == buffer.len() {
10269                        break;
10270                    } else {
10271                        search_start = buffer.len();
10272                    }
10273                } else if search_start == 0 {
10274                    break;
10275                } else {
10276                    search_start = 0;
10277                }
10278            }
10279        }
10280    }
10281
10282    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10283        let snapshot = self.snapshot(window, cx);
10284        let selection = self.selections.newest::<Point>(cx);
10285        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10286    }
10287
10288    fn go_to_hunk_after_position(
10289        &mut self,
10290        snapshot: &EditorSnapshot,
10291        position: Point,
10292        window: &mut Window,
10293        cx: &mut Context<Editor>,
10294    ) -> Option<MultiBufferDiffHunk> {
10295        let mut hunk = snapshot
10296            .buffer_snapshot
10297            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10298            .find(|hunk| hunk.row_range.start.0 > position.row);
10299        if hunk.is_none() {
10300            hunk = snapshot
10301                .buffer_snapshot
10302                .diff_hunks_in_range(Point::zero()..position)
10303                .find(|hunk| hunk.row_range.end.0 < position.row)
10304        }
10305        if let Some(hunk) = &hunk {
10306            let destination = Point::new(hunk.row_range.start.0, 0);
10307            self.unfold_ranges(&[destination..destination], false, false, cx);
10308            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10309                s.select_ranges(vec![destination..destination]);
10310            });
10311        }
10312
10313        hunk
10314    }
10315
10316    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10317        let snapshot = self.snapshot(window, cx);
10318        let selection = self.selections.newest::<Point>(cx);
10319        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10320    }
10321
10322    fn go_to_hunk_before_position(
10323        &mut self,
10324        snapshot: &EditorSnapshot,
10325        position: Point,
10326        window: &mut Window,
10327        cx: &mut Context<Editor>,
10328    ) -> Option<MultiBufferDiffHunk> {
10329        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10330        if hunk.is_none() {
10331            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10332        }
10333        if let Some(hunk) = &hunk {
10334            let destination = Point::new(hunk.row_range.start.0, 0);
10335            self.unfold_ranges(&[destination..destination], false, false, cx);
10336            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10337                s.select_ranges(vec![destination..destination]);
10338            });
10339        }
10340
10341        hunk
10342    }
10343
10344    pub fn go_to_definition(
10345        &mut self,
10346        _: &GoToDefinition,
10347        window: &mut Window,
10348        cx: &mut Context<Self>,
10349    ) -> Task<Result<Navigated>> {
10350        let definition =
10351            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10352        cx.spawn_in(window, |editor, mut cx| async move {
10353            if definition.await? == Navigated::Yes {
10354                return Ok(Navigated::Yes);
10355            }
10356            match editor.update_in(&mut cx, |editor, window, cx| {
10357                editor.find_all_references(&FindAllReferences, window, cx)
10358            })? {
10359                Some(references) => references.await,
10360                None => Ok(Navigated::No),
10361            }
10362        })
10363    }
10364
10365    pub fn go_to_declaration(
10366        &mut self,
10367        _: &GoToDeclaration,
10368        window: &mut Window,
10369        cx: &mut Context<Self>,
10370    ) -> Task<Result<Navigated>> {
10371        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10372    }
10373
10374    pub fn go_to_declaration_split(
10375        &mut self,
10376        _: &GoToDeclaration,
10377        window: &mut Window,
10378        cx: &mut Context<Self>,
10379    ) -> Task<Result<Navigated>> {
10380        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10381    }
10382
10383    pub fn go_to_implementation(
10384        &mut self,
10385        _: &GoToImplementation,
10386        window: &mut Window,
10387        cx: &mut Context<Self>,
10388    ) -> Task<Result<Navigated>> {
10389        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10390    }
10391
10392    pub fn go_to_implementation_split(
10393        &mut self,
10394        _: &GoToImplementationSplit,
10395        window: &mut Window,
10396        cx: &mut Context<Self>,
10397    ) -> Task<Result<Navigated>> {
10398        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10399    }
10400
10401    pub fn go_to_type_definition(
10402        &mut self,
10403        _: &GoToTypeDefinition,
10404        window: &mut Window,
10405        cx: &mut Context<Self>,
10406    ) -> Task<Result<Navigated>> {
10407        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10408    }
10409
10410    pub fn go_to_definition_split(
10411        &mut self,
10412        _: &GoToDefinitionSplit,
10413        window: &mut Window,
10414        cx: &mut Context<Self>,
10415    ) -> Task<Result<Navigated>> {
10416        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10417    }
10418
10419    pub fn go_to_type_definition_split(
10420        &mut self,
10421        _: &GoToTypeDefinitionSplit,
10422        window: &mut Window,
10423        cx: &mut Context<Self>,
10424    ) -> Task<Result<Navigated>> {
10425        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10426    }
10427
10428    fn go_to_definition_of_kind(
10429        &mut self,
10430        kind: GotoDefinitionKind,
10431        split: bool,
10432        window: &mut Window,
10433        cx: &mut Context<Self>,
10434    ) -> Task<Result<Navigated>> {
10435        let Some(provider) = self.semantics_provider.clone() else {
10436            return Task::ready(Ok(Navigated::No));
10437        };
10438        let head = self.selections.newest::<usize>(cx).head();
10439        let buffer = self.buffer.read(cx);
10440        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10441            text_anchor
10442        } else {
10443            return Task::ready(Ok(Navigated::No));
10444        };
10445
10446        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10447            return Task::ready(Ok(Navigated::No));
10448        };
10449
10450        cx.spawn_in(window, |editor, mut cx| async move {
10451            let definitions = definitions.await?;
10452            let navigated = editor
10453                .update_in(&mut cx, |editor, window, cx| {
10454                    editor.navigate_to_hover_links(
10455                        Some(kind),
10456                        definitions
10457                            .into_iter()
10458                            .filter(|location| {
10459                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10460                            })
10461                            .map(HoverLink::Text)
10462                            .collect::<Vec<_>>(),
10463                        split,
10464                        window,
10465                        cx,
10466                    )
10467                })?
10468                .await?;
10469            anyhow::Ok(navigated)
10470        })
10471    }
10472
10473    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10474        let selection = self.selections.newest_anchor();
10475        let head = selection.head();
10476        let tail = selection.tail();
10477
10478        let Some((buffer, start_position)) =
10479            self.buffer.read(cx).text_anchor_for_position(head, cx)
10480        else {
10481            return;
10482        };
10483
10484        let end_position = if head != tail {
10485            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10486                return;
10487            };
10488            Some(pos)
10489        } else {
10490            None
10491        };
10492
10493        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10494            let url = if let Some(end_pos) = end_position {
10495                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10496            } else {
10497                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10498            };
10499
10500            if let Some(url) = url {
10501                editor.update(&mut cx, |_, cx| {
10502                    cx.open_url(&url);
10503                })
10504            } else {
10505                Ok(())
10506            }
10507        });
10508
10509        url_finder.detach();
10510    }
10511
10512    pub fn open_selected_filename(
10513        &mut self,
10514        _: &OpenSelectedFilename,
10515        window: &mut Window,
10516        cx: &mut Context<Self>,
10517    ) {
10518        let Some(workspace) = self.workspace() else {
10519            return;
10520        };
10521
10522        let position = self.selections.newest_anchor().head();
10523
10524        let Some((buffer, buffer_position)) =
10525            self.buffer.read(cx).text_anchor_for_position(position, cx)
10526        else {
10527            return;
10528        };
10529
10530        let project = self.project.clone();
10531
10532        cx.spawn_in(window, |_, mut cx| async move {
10533            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10534
10535            if let Some((_, path)) = result {
10536                workspace
10537                    .update_in(&mut cx, |workspace, window, cx| {
10538                        workspace.open_resolved_path(path, window, cx)
10539                    })?
10540                    .await?;
10541            }
10542            anyhow::Ok(())
10543        })
10544        .detach();
10545    }
10546
10547    pub(crate) fn navigate_to_hover_links(
10548        &mut self,
10549        kind: Option<GotoDefinitionKind>,
10550        mut definitions: Vec<HoverLink>,
10551        split: bool,
10552        window: &mut Window,
10553        cx: &mut Context<Editor>,
10554    ) -> Task<Result<Navigated>> {
10555        // If there is one definition, just open it directly
10556        if definitions.len() == 1 {
10557            let definition = definitions.pop().unwrap();
10558
10559            enum TargetTaskResult {
10560                Location(Option<Location>),
10561                AlreadyNavigated,
10562            }
10563
10564            let target_task = match definition {
10565                HoverLink::Text(link) => {
10566                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10567                }
10568                HoverLink::InlayHint(lsp_location, server_id) => {
10569                    let computation =
10570                        self.compute_target_location(lsp_location, server_id, window, cx);
10571                    cx.background_executor().spawn(async move {
10572                        let location = computation.await?;
10573                        Ok(TargetTaskResult::Location(location))
10574                    })
10575                }
10576                HoverLink::Url(url) => {
10577                    cx.open_url(&url);
10578                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10579                }
10580                HoverLink::File(path) => {
10581                    if let Some(workspace) = self.workspace() {
10582                        cx.spawn_in(window, |_, mut cx| async move {
10583                            workspace
10584                                .update_in(&mut cx, |workspace, window, cx| {
10585                                    workspace.open_resolved_path(path, window, cx)
10586                                })?
10587                                .await
10588                                .map(|_| TargetTaskResult::AlreadyNavigated)
10589                        })
10590                    } else {
10591                        Task::ready(Ok(TargetTaskResult::Location(None)))
10592                    }
10593                }
10594            };
10595            cx.spawn_in(window, |editor, mut cx| async move {
10596                let target = match target_task.await.context("target resolution task")? {
10597                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10598                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10599                    TargetTaskResult::Location(Some(target)) => target,
10600                };
10601
10602                editor.update_in(&mut cx, |editor, window, cx| {
10603                    let Some(workspace) = editor.workspace() else {
10604                        return Navigated::No;
10605                    };
10606                    let pane = workspace.read(cx).active_pane().clone();
10607
10608                    let range = target.range.to_point(target.buffer.read(cx));
10609                    let range = editor.range_for_match(&range);
10610                    let range = collapse_multiline_range(range);
10611
10612                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10613                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10614                    } else {
10615                        window.defer(cx, move |window, cx| {
10616                            let target_editor: Entity<Self> =
10617                                workspace.update(cx, |workspace, cx| {
10618                                    let pane = if split {
10619                                        workspace.adjacent_pane(window, cx)
10620                                    } else {
10621                                        workspace.active_pane().clone()
10622                                    };
10623
10624                                    workspace.open_project_item(
10625                                        pane,
10626                                        target.buffer.clone(),
10627                                        true,
10628                                        true,
10629                                        window,
10630                                        cx,
10631                                    )
10632                                });
10633                            target_editor.update(cx, |target_editor, cx| {
10634                                // When selecting a definition in a different buffer, disable the nav history
10635                                // to avoid creating a history entry at the previous cursor location.
10636                                pane.update(cx, |pane, _| pane.disable_history());
10637                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10638                                pane.update(cx, |pane, _| pane.enable_history());
10639                            });
10640                        });
10641                    }
10642                    Navigated::Yes
10643                })
10644            })
10645        } else if !definitions.is_empty() {
10646            cx.spawn_in(window, |editor, mut cx| async move {
10647                let (title, location_tasks, workspace) = editor
10648                    .update_in(&mut cx, |editor, window, cx| {
10649                        let tab_kind = match kind {
10650                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10651                            _ => "Definitions",
10652                        };
10653                        let title = definitions
10654                            .iter()
10655                            .find_map(|definition| match definition {
10656                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10657                                    let buffer = origin.buffer.read(cx);
10658                                    format!(
10659                                        "{} for {}",
10660                                        tab_kind,
10661                                        buffer
10662                                            .text_for_range(origin.range.clone())
10663                                            .collect::<String>()
10664                                    )
10665                                }),
10666                                HoverLink::InlayHint(_, _) => None,
10667                                HoverLink::Url(_) => None,
10668                                HoverLink::File(_) => None,
10669                            })
10670                            .unwrap_or(tab_kind.to_string());
10671                        let location_tasks = definitions
10672                            .into_iter()
10673                            .map(|definition| match definition {
10674                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10675                                HoverLink::InlayHint(lsp_location, server_id) => editor
10676                                    .compute_target_location(lsp_location, server_id, window, cx),
10677                                HoverLink::Url(_) => Task::ready(Ok(None)),
10678                                HoverLink::File(_) => Task::ready(Ok(None)),
10679                            })
10680                            .collect::<Vec<_>>();
10681                        (title, location_tasks, editor.workspace().clone())
10682                    })
10683                    .context("location tasks preparation")?;
10684
10685                let locations = future::join_all(location_tasks)
10686                    .await
10687                    .into_iter()
10688                    .filter_map(|location| location.transpose())
10689                    .collect::<Result<_>>()
10690                    .context("location tasks")?;
10691
10692                let Some(workspace) = workspace else {
10693                    return Ok(Navigated::No);
10694                };
10695                let opened = workspace
10696                    .update_in(&mut cx, |workspace, window, cx| {
10697                        Self::open_locations_in_multibuffer(
10698                            workspace,
10699                            locations,
10700                            title,
10701                            split,
10702                            MultibufferSelectionMode::First,
10703                            window,
10704                            cx,
10705                        )
10706                    })
10707                    .ok();
10708
10709                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10710            })
10711        } else {
10712            Task::ready(Ok(Navigated::No))
10713        }
10714    }
10715
10716    fn compute_target_location(
10717        &self,
10718        lsp_location: lsp::Location,
10719        server_id: LanguageServerId,
10720        window: &mut Window,
10721        cx: &mut Context<Self>,
10722    ) -> Task<anyhow::Result<Option<Location>>> {
10723        let Some(project) = self.project.clone() else {
10724            return Task::ready(Ok(None));
10725        };
10726
10727        cx.spawn_in(window, move |editor, mut cx| async move {
10728            let location_task = editor.update(&mut cx, |_, cx| {
10729                project.update(cx, |project, cx| {
10730                    let language_server_name = project
10731                        .language_server_statuses(cx)
10732                        .find(|(id, _)| server_id == *id)
10733                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10734                    language_server_name.map(|language_server_name| {
10735                        project.open_local_buffer_via_lsp(
10736                            lsp_location.uri.clone(),
10737                            server_id,
10738                            language_server_name,
10739                            cx,
10740                        )
10741                    })
10742                })
10743            })?;
10744            let location = match location_task {
10745                Some(task) => Some({
10746                    let target_buffer_handle = task.await.context("open local buffer")?;
10747                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10748                        let target_start = target_buffer
10749                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10750                        let target_end = target_buffer
10751                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10752                        target_buffer.anchor_after(target_start)
10753                            ..target_buffer.anchor_before(target_end)
10754                    })?;
10755                    Location {
10756                        buffer: target_buffer_handle,
10757                        range,
10758                    }
10759                }),
10760                None => None,
10761            };
10762            Ok(location)
10763        })
10764    }
10765
10766    pub fn find_all_references(
10767        &mut self,
10768        _: &FindAllReferences,
10769        window: &mut Window,
10770        cx: &mut Context<Self>,
10771    ) -> Option<Task<Result<Navigated>>> {
10772        let selection = self.selections.newest::<usize>(cx);
10773        let multi_buffer = self.buffer.read(cx);
10774        let head = selection.head();
10775
10776        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10777        let head_anchor = multi_buffer_snapshot.anchor_at(
10778            head,
10779            if head < selection.tail() {
10780                Bias::Right
10781            } else {
10782                Bias::Left
10783            },
10784        );
10785
10786        match self
10787            .find_all_references_task_sources
10788            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10789        {
10790            Ok(_) => {
10791                log::info!(
10792                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10793                );
10794                return None;
10795            }
10796            Err(i) => {
10797                self.find_all_references_task_sources.insert(i, head_anchor);
10798            }
10799        }
10800
10801        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10802        let workspace = self.workspace()?;
10803        let project = workspace.read(cx).project().clone();
10804        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10805        Some(cx.spawn_in(window, |editor, mut cx| async move {
10806            let _cleanup = defer({
10807                let mut cx = cx.clone();
10808                move || {
10809                    let _ = editor.update(&mut cx, |editor, _| {
10810                        if let Ok(i) =
10811                            editor
10812                                .find_all_references_task_sources
10813                                .binary_search_by(|anchor| {
10814                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10815                                })
10816                        {
10817                            editor.find_all_references_task_sources.remove(i);
10818                        }
10819                    });
10820                }
10821            });
10822
10823            let locations = references.await?;
10824            if locations.is_empty() {
10825                return anyhow::Ok(Navigated::No);
10826            }
10827
10828            workspace.update_in(&mut cx, |workspace, window, cx| {
10829                let title = locations
10830                    .first()
10831                    .as_ref()
10832                    .map(|location| {
10833                        let buffer = location.buffer.read(cx);
10834                        format!(
10835                            "References to `{}`",
10836                            buffer
10837                                .text_for_range(location.range.clone())
10838                                .collect::<String>()
10839                        )
10840                    })
10841                    .unwrap();
10842                Self::open_locations_in_multibuffer(
10843                    workspace,
10844                    locations,
10845                    title,
10846                    false,
10847                    MultibufferSelectionMode::First,
10848                    window,
10849                    cx,
10850                );
10851                Navigated::Yes
10852            })
10853        }))
10854    }
10855
10856    /// Opens a multibuffer with the given project locations in it
10857    pub fn open_locations_in_multibuffer(
10858        workspace: &mut Workspace,
10859        mut locations: Vec<Location>,
10860        title: String,
10861        split: bool,
10862        multibuffer_selection_mode: MultibufferSelectionMode,
10863        window: &mut Window,
10864        cx: &mut Context<Workspace>,
10865    ) {
10866        // If there are multiple definitions, open them in a multibuffer
10867        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10868        let mut locations = locations.into_iter().peekable();
10869        let mut ranges = Vec::new();
10870        let capability = workspace.project().read(cx).capability();
10871
10872        let excerpt_buffer = cx.new(|cx| {
10873            let mut multibuffer = MultiBuffer::new(capability);
10874            while let Some(location) = locations.next() {
10875                let buffer = location.buffer.read(cx);
10876                let mut ranges_for_buffer = Vec::new();
10877                let range = location.range.to_offset(buffer);
10878                ranges_for_buffer.push(range.clone());
10879
10880                while let Some(next_location) = locations.peek() {
10881                    if next_location.buffer == location.buffer {
10882                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10883                        locations.next();
10884                    } else {
10885                        break;
10886                    }
10887                }
10888
10889                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10890                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10891                    location.buffer.clone(),
10892                    ranges_for_buffer,
10893                    DEFAULT_MULTIBUFFER_CONTEXT,
10894                    cx,
10895                ))
10896            }
10897
10898            multibuffer.with_title(title)
10899        });
10900
10901        let editor = cx.new(|cx| {
10902            Editor::for_multibuffer(
10903                excerpt_buffer,
10904                Some(workspace.project().clone()),
10905                true,
10906                window,
10907                cx,
10908            )
10909        });
10910        editor.update(cx, |editor, cx| {
10911            match multibuffer_selection_mode {
10912                MultibufferSelectionMode::First => {
10913                    if let Some(first_range) = ranges.first() {
10914                        editor.change_selections(None, window, cx, |selections| {
10915                            selections.clear_disjoint();
10916                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10917                        });
10918                    }
10919                    editor.highlight_background::<Self>(
10920                        &ranges,
10921                        |theme| theme.editor_highlighted_line_background,
10922                        cx,
10923                    );
10924                }
10925                MultibufferSelectionMode::All => {
10926                    editor.change_selections(None, window, cx, |selections| {
10927                        selections.clear_disjoint();
10928                        selections.select_anchor_ranges(ranges);
10929                    });
10930                }
10931            }
10932            editor.register_buffers_with_language_servers(cx);
10933        });
10934
10935        let item = Box::new(editor);
10936        let item_id = item.item_id();
10937
10938        if split {
10939            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10940        } else {
10941            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10942                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10943                    pane.close_current_preview_item(window, cx)
10944                } else {
10945                    None
10946                }
10947            });
10948            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10949        }
10950        workspace.active_pane().update(cx, |pane, cx| {
10951            pane.set_preview_item_id(Some(item_id), cx);
10952        });
10953    }
10954
10955    pub fn rename(
10956        &mut self,
10957        _: &Rename,
10958        window: &mut Window,
10959        cx: &mut Context<Self>,
10960    ) -> Option<Task<Result<()>>> {
10961        use language::ToOffset as _;
10962
10963        let provider = self.semantics_provider.clone()?;
10964        let selection = self.selections.newest_anchor().clone();
10965        let (cursor_buffer, cursor_buffer_position) = self
10966            .buffer
10967            .read(cx)
10968            .text_anchor_for_position(selection.head(), cx)?;
10969        let (tail_buffer, cursor_buffer_position_end) = self
10970            .buffer
10971            .read(cx)
10972            .text_anchor_for_position(selection.tail(), cx)?;
10973        if tail_buffer != cursor_buffer {
10974            return None;
10975        }
10976
10977        let snapshot = cursor_buffer.read(cx).snapshot();
10978        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10979        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10980        let prepare_rename = provider
10981            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10982            .unwrap_or_else(|| Task::ready(Ok(None)));
10983        drop(snapshot);
10984
10985        Some(cx.spawn_in(window, |this, mut cx| async move {
10986            let rename_range = if let Some(range) = prepare_rename.await? {
10987                Some(range)
10988            } else {
10989                this.update(&mut cx, |this, cx| {
10990                    let buffer = this.buffer.read(cx).snapshot(cx);
10991                    let mut buffer_highlights = this
10992                        .document_highlights_for_position(selection.head(), &buffer)
10993                        .filter(|highlight| {
10994                            highlight.start.excerpt_id == selection.head().excerpt_id
10995                                && highlight.end.excerpt_id == selection.head().excerpt_id
10996                        });
10997                    buffer_highlights
10998                        .next()
10999                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11000                })?
11001            };
11002            if let Some(rename_range) = rename_range {
11003                this.update_in(&mut cx, |this, window, cx| {
11004                    let snapshot = cursor_buffer.read(cx).snapshot();
11005                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11006                    let cursor_offset_in_rename_range =
11007                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11008                    let cursor_offset_in_rename_range_end =
11009                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11010
11011                    this.take_rename(false, window, cx);
11012                    let buffer = this.buffer.read(cx).read(cx);
11013                    let cursor_offset = selection.head().to_offset(&buffer);
11014                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11015                    let rename_end = rename_start + rename_buffer_range.len();
11016                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11017                    let mut old_highlight_id = None;
11018                    let old_name: Arc<str> = buffer
11019                        .chunks(rename_start..rename_end, true)
11020                        .map(|chunk| {
11021                            if old_highlight_id.is_none() {
11022                                old_highlight_id = chunk.syntax_highlight_id;
11023                            }
11024                            chunk.text
11025                        })
11026                        .collect::<String>()
11027                        .into();
11028
11029                    drop(buffer);
11030
11031                    // Position the selection in the rename editor so that it matches the current selection.
11032                    this.show_local_selections = false;
11033                    let rename_editor = cx.new(|cx| {
11034                        let mut editor = Editor::single_line(window, cx);
11035                        editor.buffer.update(cx, |buffer, cx| {
11036                            buffer.edit([(0..0, old_name.clone())], None, cx)
11037                        });
11038                        let rename_selection_range = match cursor_offset_in_rename_range
11039                            .cmp(&cursor_offset_in_rename_range_end)
11040                        {
11041                            Ordering::Equal => {
11042                                editor.select_all(&SelectAll, window, cx);
11043                                return editor;
11044                            }
11045                            Ordering::Less => {
11046                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11047                            }
11048                            Ordering::Greater => {
11049                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11050                            }
11051                        };
11052                        if rename_selection_range.end > old_name.len() {
11053                            editor.select_all(&SelectAll, window, cx);
11054                        } else {
11055                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11056                                s.select_ranges([rename_selection_range]);
11057                            });
11058                        }
11059                        editor
11060                    });
11061                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11062                        if e == &EditorEvent::Focused {
11063                            cx.emit(EditorEvent::FocusedIn)
11064                        }
11065                    })
11066                    .detach();
11067
11068                    let write_highlights =
11069                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11070                    let read_highlights =
11071                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11072                    let ranges = write_highlights
11073                        .iter()
11074                        .flat_map(|(_, ranges)| ranges.iter())
11075                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11076                        .cloned()
11077                        .collect();
11078
11079                    this.highlight_text::<Rename>(
11080                        ranges,
11081                        HighlightStyle {
11082                            fade_out: Some(0.6),
11083                            ..Default::default()
11084                        },
11085                        cx,
11086                    );
11087                    let rename_focus_handle = rename_editor.focus_handle(cx);
11088                    window.focus(&rename_focus_handle);
11089                    let block_id = this.insert_blocks(
11090                        [BlockProperties {
11091                            style: BlockStyle::Flex,
11092                            placement: BlockPlacement::Below(range.start),
11093                            height: 1,
11094                            render: Arc::new({
11095                                let rename_editor = rename_editor.clone();
11096                                move |cx: &mut BlockContext| {
11097                                    let mut text_style = cx.editor_style.text.clone();
11098                                    if let Some(highlight_style) = old_highlight_id
11099                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11100                                    {
11101                                        text_style = text_style.highlight(highlight_style);
11102                                    }
11103                                    div()
11104                                        .block_mouse_down()
11105                                        .pl(cx.anchor_x)
11106                                        .child(EditorElement::new(
11107                                            &rename_editor,
11108                                            EditorStyle {
11109                                                background: cx.theme().system().transparent,
11110                                                local_player: cx.editor_style.local_player,
11111                                                text: text_style,
11112                                                scrollbar_width: cx.editor_style.scrollbar_width,
11113                                                syntax: cx.editor_style.syntax.clone(),
11114                                                status: cx.editor_style.status.clone(),
11115                                                inlay_hints_style: HighlightStyle {
11116                                                    font_weight: Some(FontWeight::BOLD),
11117                                                    ..make_inlay_hints_style(cx.app)
11118                                                },
11119                                                inline_completion_styles: make_suggestion_styles(
11120                                                    cx.app,
11121                                                ),
11122                                                ..EditorStyle::default()
11123                                            },
11124                                        ))
11125                                        .into_any_element()
11126                                }
11127                            }),
11128                            priority: 0,
11129                        }],
11130                        Some(Autoscroll::fit()),
11131                        cx,
11132                    )[0];
11133                    this.pending_rename = Some(RenameState {
11134                        range,
11135                        old_name,
11136                        editor: rename_editor,
11137                        block_id,
11138                    });
11139                })?;
11140            }
11141
11142            Ok(())
11143        }))
11144    }
11145
11146    pub fn confirm_rename(
11147        &mut self,
11148        _: &ConfirmRename,
11149        window: &mut Window,
11150        cx: &mut Context<Self>,
11151    ) -> Option<Task<Result<()>>> {
11152        let rename = self.take_rename(false, window, cx)?;
11153        let workspace = self.workspace()?.downgrade();
11154        let (buffer, start) = self
11155            .buffer
11156            .read(cx)
11157            .text_anchor_for_position(rename.range.start, cx)?;
11158        let (end_buffer, _) = self
11159            .buffer
11160            .read(cx)
11161            .text_anchor_for_position(rename.range.end, cx)?;
11162        if buffer != end_buffer {
11163            return None;
11164        }
11165
11166        let old_name = rename.old_name;
11167        let new_name = rename.editor.read(cx).text(cx);
11168
11169        let rename = self.semantics_provider.as_ref()?.perform_rename(
11170            &buffer,
11171            start,
11172            new_name.clone(),
11173            cx,
11174        )?;
11175
11176        Some(cx.spawn_in(window, |editor, mut cx| async move {
11177            let project_transaction = rename.await?;
11178            Self::open_project_transaction(
11179                &editor,
11180                workspace,
11181                project_transaction,
11182                format!("Rename: {}{}", old_name, new_name),
11183                cx.clone(),
11184            )
11185            .await?;
11186
11187            editor.update(&mut cx, |editor, cx| {
11188                editor.refresh_document_highlights(cx);
11189            })?;
11190            Ok(())
11191        }))
11192    }
11193
11194    fn take_rename(
11195        &mut self,
11196        moving_cursor: bool,
11197        window: &mut Window,
11198        cx: &mut Context<Self>,
11199    ) -> Option<RenameState> {
11200        let rename = self.pending_rename.take()?;
11201        if rename.editor.focus_handle(cx).is_focused(window) {
11202            window.focus(&self.focus_handle);
11203        }
11204
11205        self.remove_blocks(
11206            [rename.block_id].into_iter().collect(),
11207            Some(Autoscroll::fit()),
11208            cx,
11209        );
11210        self.clear_highlights::<Rename>(cx);
11211        self.show_local_selections = true;
11212
11213        if moving_cursor {
11214            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11215                editor.selections.newest::<usize>(cx).head()
11216            });
11217
11218            // Update the selection to match the position of the selection inside
11219            // the rename editor.
11220            let snapshot = self.buffer.read(cx).read(cx);
11221            let rename_range = rename.range.to_offset(&snapshot);
11222            let cursor_in_editor = snapshot
11223                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11224                .min(rename_range.end);
11225            drop(snapshot);
11226
11227            self.change_selections(None, window, cx, |s| {
11228                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11229            });
11230        } else {
11231            self.refresh_document_highlights(cx);
11232        }
11233
11234        Some(rename)
11235    }
11236
11237    pub fn pending_rename(&self) -> Option<&RenameState> {
11238        self.pending_rename.as_ref()
11239    }
11240
11241    fn format(
11242        &mut self,
11243        _: &Format,
11244        window: &mut Window,
11245        cx: &mut Context<Self>,
11246    ) -> Option<Task<Result<()>>> {
11247        let project = match &self.project {
11248            Some(project) => project.clone(),
11249            None => return None,
11250        };
11251
11252        Some(self.perform_format(
11253            project,
11254            FormatTrigger::Manual,
11255            FormatTarget::Buffers,
11256            window,
11257            cx,
11258        ))
11259    }
11260
11261    fn format_selections(
11262        &mut self,
11263        _: &FormatSelections,
11264        window: &mut Window,
11265        cx: &mut Context<Self>,
11266    ) -> Option<Task<Result<()>>> {
11267        let project = match &self.project {
11268            Some(project) => project.clone(),
11269            None => return None,
11270        };
11271
11272        let ranges = self
11273            .selections
11274            .all_adjusted(cx)
11275            .into_iter()
11276            .map(|selection| selection.range())
11277            .collect_vec();
11278
11279        Some(self.perform_format(
11280            project,
11281            FormatTrigger::Manual,
11282            FormatTarget::Ranges(ranges),
11283            window,
11284            cx,
11285        ))
11286    }
11287
11288    fn perform_format(
11289        &mut self,
11290        project: Entity<Project>,
11291        trigger: FormatTrigger,
11292        target: FormatTarget,
11293        window: &mut Window,
11294        cx: &mut Context<Self>,
11295    ) -> Task<Result<()>> {
11296        let buffer = self.buffer.clone();
11297        let (buffers, target) = match target {
11298            FormatTarget::Buffers => {
11299                let mut buffers = buffer.read(cx).all_buffers();
11300                if trigger == FormatTrigger::Save {
11301                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11302                }
11303                (buffers, LspFormatTarget::Buffers)
11304            }
11305            FormatTarget::Ranges(selection_ranges) => {
11306                let multi_buffer = buffer.read(cx);
11307                let snapshot = multi_buffer.read(cx);
11308                let mut buffers = HashSet::default();
11309                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11310                    BTreeMap::new();
11311                for selection_range in selection_ranges {
11312                    for (buffer, buffer_range, _) in
11313                        snapshot.range_to_buffer_ranges(selection_range)
11314                    {
11315                        let buffer_id = buffer.remote_id();
11316                        let start = buffer.anchor_before(buffer_range.start);
11317                        let end = buffer.anchor_after(buffer_range.end);
11318                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11319                        buffer_id_to_ranges
11320                            .entry(buffer_id)
11321                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11322                            .or_insert_with(|| vec![start..end]);
11323                    }
11324                }
11325                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11326            }
11327        };
11328
11329        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11330        let format = project.update(cx, |project, cx| {
11331            project.format(buffers, target, true, trigger, cx)
11332        });
11333
11334        cx.spawn_in(window, |_, mut cx| async move {
11335            let transaction = futures::select_biased! {
11336                () = timeout => {
11337                    log::warn!("timed out waiting for formatting");
11338                    None
11339                }
11340                transaction = format.log_err().fuse() => transaction,
11341            };
11342
11343            buffer
11344                .update(&mut cx, |buffer, cx| {
11345                    if let Some(transaction) = transaction {
11346                        if !buffer.is_singleton() {
11347                            buffer.push_transaction(&transaction.0, cx);
11348                        }
11349                    }
11350
11351                    cx.notify();
11352                })
11353                .ok();
11354
11355            Ok(())
11356        })
11357    }
11358
11359    fn restart_language_server(
11360        &mut self,
11361        _: &RestartLanguageServer,
11362        _: &mut Window,
11363        cx: &mut Context<Self>,
11364    ) {
11365        if let Some(project) = self.project.clone() {
11366            self.buffer.update(cx, |multi_buffer, cx| {
11367                project.update(cx, |project, cx| {
11368                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11369                });
11370            })
11371        }
11372    }
11373
11374    fn cancel_language_server_work(
11375        workspace: &mut Workspace,
11376        _: &actions::CancelLanguageServerWork,
11377        _: &mut Window,
11378        cx: &mut Context<Workspace>,
11379    ) {
11380        let project = workspace.project();
11381        let buffers = workspace
11382            .active_item(cx)
11383            .and_then(|item| item.act_as::<Editor>(cx))
11384            .map_or(HashSet::default(), |editor| {
11385                editor.read(cx).buffer.read(cx).all_buffers()
11386            });
11387        project.update(cx, |project, cx| {
11388            project.cancel_language_server_work_for_buffers(buffers, cx);
11389        });
11390    }
11391
11392    fn show_character_palette(
11393        &mut self,
11394        _: &ShowCharacterPalette,
11395        window: &mut Window,
11396        _: &mut Context<Self>,
11397    ) {
11398        window.show_character_palette();
11399    }
11400
11401    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11402        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11403            let buffer = self.buffer.read(cx).snapshot(cx);
11404            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11405            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11406            let is_valid = buffer
11407                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11408                .any(|entry| {
11409                    entry.diagnostic.is_primary
11410                        && !entry.range.is_empty()
11411                        && entry.range.start == primary_range_start
11412                        && entry.diagnostic.message == active_diagnostics.primary_message
11413                });
11414
11415            if is_valid != active_diagnostics.is_valid {
11416                active_diagnostics.is_valid = is_valid;
11417                let mut new_styles = HashMap::default();
11418                for (block_id, diagnostic) in &active_diagnostics.blocks {
11419                    new_styles.insert(
11420                        *block_id,
11421                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11422                    );
11423                }
11424                self.display_map.update(cx, |display_map, _cx| {
11425                    display_map.replace_blocks(new_styles)
11426                });
11427            }
11428        }
11429    }
11430
11431    fn activate_diagnostics(
11432        &mut self,
11433        buffer_id: BufferId,
11434        group_id: usize,
11435        window: &mut Window,
11436        cx: &mut Context<Self>,
11437    ) {
11438        self.dismiss_diagnostics(cx);
11439        let snapshot = self.snapshot(window, cx);
11440        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11441            let buffer = self.buffer.read(cx).snapshot(cx);
11442
11443            let mut primary_range = None;
11444            let mut primary_message = None;
11445            let diagnostic_group = buffer
11446                .diagnostic_group(buffer_id, group_id)
11447                .filter_map(|entry| {
11448                    let start = entry.range.start;
11449                    let end = entry.range.end;
11450                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11451                        && (start.row == end.row
11452                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11453                    {
11454                        return None;
11455                    }
11456                    if entry.diagnostic.is_primary {
11457                        primary_range = Some(entry.range.clone());
11458                        primary_message = Some(entry.diagnostic.message.clone());
11459                    }
11460                    Some(entry)
11461                })
11462                .collect::<Vec<_>>();
11463            let primary_range = primary_range?;
11464            let primary_message = primary_message?;
11465
11466            let blocks = display_map
11467                .insert_blocks(
11468                    diagnostic_group.iter().map(|entry| {
11469                        let diagnostic = entry.diagnostic.clone();
11470                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11471                        BlockProperties {
11472                            style: BlockStyle::Fixed,
11473                            placement: BlockPlacement::Below(
11474                                buffer.anchor_after(entry.range.start),
11475                            ),
11476                            height: message_height,
11477                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11478                            priority: 0,
11479                        }
11480                    }),
11481                    cx,
11482                )
11483                .into_iter()
11484                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11485                .collect();
11486
11487            Some(ActiveDiagnosticGroup {
11488                primary_range: buffer.anchor_before(primary_range.start)
11489                    ..buffer.anchor_after(primary_range.end),
11490                primary_message,
11491                group_id,
11492                blocks,
11493                is_valid: true,
11494            })
11495        });
11496    }
11497
11498    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11499        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11500            self.display_map.update(cx, |display_map, cx| {
11501                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11502            });
11503            cx.notify();
11504        }
11505    }
11506
11507    pub fn set_selections_from_remote(
11508        &mut self,
11509        selections: Vec<Selection<Anchor>>,
11510        pending_selection: Option<Selection<Anchor>>,
11511        window: &mut Window,
11512        cx: &mut Context<Self>,
11513    ) {
11514        let old_cursor_position = self.selections.newest_anchor().head();
11515        self.selections.change_with(cx, |s| {
11516            s.select_anchors(selections);
11517            if let Some(pending_selection) = pending_selection {
11518                s.set_pending(pending_selection, SelectMode::Character);
11519            } else {
11520                s.clear_pending();
11521            }
11522        });
11523        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11524    }
11525
11526    fn push_to_selection_history(&mut self) {
11527        self.selection_history.push(SelectionHistoryEntry {
11528            selections: self.selections.disjoint_anchors(),
11529            select_next_state: self.select_next_state.clone(),
11530            select_prev_state: self.select_prev_state.clone(),
11531            add_selections_state: self.add_selections_state.clone(),
11532        });
11533    }
11534
11535    pub fn transact(
11536        &mut self,
11537        window: &mut Window,
11538        cx: &mut Context<Self>,
11539        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11540    ) -> Option<TransactionId> {
11541        self.start_transaction_at(Instant::now(), window, cx);
11542        update(self, window, cx);
11543        self.end_transaction_at(Instant::now(), cx)
11544    }
11545
11546    pub fn start_transaction_at(
11547        &mut self,
11548        now: Instant,
11549        window: &mut Window,
11550        cx: &mut Context<Self>,
11551    ) {
11552        self.end_selection(window, cx);
11553        if let Some(tx_id) = self
11554            .buffer
11555            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11556        {
11557            self.selection_history
11558                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11559            cx.emit(EditorEvent::TransactionBegun {
11560                transaction_id: tx_id,
11561            })
11562        }
11563    }
11564
11565    pub fn end_transaction_at(
11566        &mut self,
11567        now: Instant,
11568        cx: &mut Context<Self>,
11569    ) -> Option<TransactionId> {
11570        if let Some(transaction_id) = self
11571            .buffer
11572            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11573        {
11574            if let Some((_, end_selections)) =
11575                self.selection_history.transaction_mut(transaction_id)
11576            {
11577                *end_selections = Some(self.selections.disjoint_anchors());
11578            } else {
11579                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11580            }
11581
11582            cx.emit(EditorEvent::Edited { transaction_id });
11583            Some(transaction_id)
11584        } else {
11585            None
11586        }
11587    }
11588
11589    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11590        if self.selection_mark_mode {
11591            self.change_selections(None, window, cx, |s| {
11592                s.move_with(|_, sel| {
11593                    sel.collapse_to(sel.head(), SelectionGoal::None);
11594                });
11595            })
11596        }
11597        self.selection_mark_mode = true;
11598        cx.notify();
11599    }
11600
11601    pub fn swap_selection_ends(
11602        &mut self,
11603        _: &actions::SwapSelectionEnds,
11604        window: &mut Window,
11605        cx: &mut Context<Self>,
11606    ) {
11607        self.change_selections(None, window, cx, |s| {
11608            s.move_with(|_, sel| {
11609                if sel.start != sel.end {
11610                    sel.reversed = !sel.reversed
11611                }
11612            });
11613        });
11614        self.request_autoscroll(Autoscroll::newest(), cx);
11615        cx.notify();
11616    }
11617
11618    pub fn toggle_fold(
11619        &mut self,
11620        _: &actions::ToggleFold,
11621        window: &mut Window,
11622        cx: &mut Context<Self>,
11623    ) {
11624        if self.is_singleton(cx) {
11625            let selection = self.selections.newest::<Point>(cx);
11626
11627            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11628            let range = if selection.is_empty() {
11629                let point = selection.head().to_display_point(&display_map);
11630                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11631                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11632                    .to_point(&display_map);
11633                start..end
11634            } else {
11635                selection.range()
11636            };
11637            if display_map.folds_in_range(range).next().is_some() {
11638                self.unfold_lines(&Default::default(), window, cx)
11639            } else {
11640                self.fold(&Default::default(), window, cx)
11641            }
11642        } else {
11643            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11644            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11645                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11646                .map(|(snapshot, _, _)| snapshot.remote_id())
11647                .collect();
11648
11649            for buffer_id in buffer_ids {
11650                if self.is_buffer_folded(buffer_id, cx) {
11651                    self.unfold_buffer(buffer_id, cx);
11652                } else {
11653                    self.fold_buffer(buffer_id, cx);
11654                }
11655            }
11656        }
11657    }
11658
11659    pub fn toggle_fold_recursive(
11660        &mut self,
11661        _: &actions::ToggleFoldRecursive,
11662        window: &mut Window,
11663        cx: &mut Context<Self>,
11664    ) {
11665        let selection = self.selections.newest::<Point>(cx);
11666
11667        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11668        let range = if selection.is_empty() {
11669            let point = selection.head().to_display_point(&display_map);
11670            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11671            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11672                .to_point(&display_map);
11673            start..end
11674        } else {
11675            selection.range()
11676        };
11677        if display_map.folds_in_range(range).next().is_some() {
11678            self.unfold_recursive(&Default::default(), window, cx)
11679        } else {
11680            self.fold_recursive(&Default::default(), window, cx)
11681        }
11682    }
11683
11684    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11685        if self.is_singleton(cx) {
11686            let mut to_fold = Vec::new();
11687            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11688            let selections = self.selections.all_adjusted(cx);
11689
11690            for selection in selections {
11691                let range = selection.range().sorted();
11692                let buffer_start_row = range.start.row;
11693
11694                if range.start.row != range.end.row {
11695                    let mut found = false;
11696                    let mut row = range.start.row;
11697                    while row <= range.end.row {
11698                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11699                        {
11700                            found = true;
11701                            row = crease.range().end.row + 1;
11702                            to_fold.push(crease);
11703                        } else {
11704                            row += 1
11705                        }
11706                    }
11707                    if found {
11708                        continue;
11709                    }
11710                }
11711
11712                for row in (0..=range.start.row).rev() {
11713                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11714                        if crease.range().end.row >= buffer_start_row {
11715                            to_fold.push(crease);
11716                            if row <= range.start.row {
11717                                break;
11718                            }
11719                        }
11720                    }
11721                }
11722            }
11723
11724            self.fold_creases(to_fold, true, window, cx);
11725        } else {
11726            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11727
11728            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11729                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11730                .map(|(snapshot, _, _)| snapshot.remote_id())
11731                .collect();
11732            for buffer_id in buffer_ids {
11733                self.fold_buffer(buffer_id, cx);
11734            }
11735        }
11736    }
11737
11738    fn fold_at_level(
11739        &mut self,
11740        fold_at: &FoldAtLevel,
11741        window: &mut Window,
11742        cx: &mut Context<Self>,
11743    ) {
11744        if !self.buffer.read(cx).is_singleton() {
11745            return;
11746        }
11747
11748        let fold_at_level = fold_at.level;
11749        let snapshot = self.buffer.read(cx).snapshot(cx);
11750        let mut to_fold = Vec::new();
11751        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11752
11753        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11754            while start_row < end_row {
11755                match self
11756                    .snapshot(window, cx)
11757                    .crease_for_buffer_row(MultiBufferRow(start_row))
11758                {
11759                    Some(crease) => {
11760                        let nested_start_row = crease.range().start.row + 1;
11761                        let nested_end_row = crease.range().end.row;
11762
11763                        if current_level < fold_at_level {
11764                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11765                        } else if current_level == fold_at_level {
11766                            to_fold.push(crease);
11767                        }
11768
11769                        start_row = nested_end_row + 1;
11770                    }
11771                    None => start_row += 1,
11772                }
11773            }
11774        }
11775
11776        self.fold_creases(to_fold, true, window, cx);
11777    }
11778
11779    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11780        if self.buffer.read(cx).is_singleton() {
11781            let mut fold_ranges = Vec::new();
11782            let snapshot = self.buffer.read(cx).snapshot(cx);
11783
11784            for row in 0..snapshot.max_row().0 {
11785                if let Some(foldable_range) = self
11786                    .snapshot(window, cx)
11787                    .crease_for_buffer_row(MultiBufferRow(row))
11788                {
11789                    fold_ranges.push(foldable_range);
11790                }
11791            }
11792
11793            self.fold_creases(fold_ranges, true, window, cx);
11794        } else {
11795            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11796                editor
11797                    .update_in(&mut cx, |editor, _, cx| {
11798                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11799                            editor.fold_buffer(buffer_id, cx);
11800                        }
11801                    })
11802                    .ok();
11803            });
11804        }
11805    }
11806
11807    pub fn fold_function_bodies(
11808        &mut self,
11809        _: &actions::FoldFunctionBodies,
11810        window: &mut Window,
11811        cx: &mut Context<Self>,
11812    ) {
11813        let snapshot = self.buffer.read(cx).snapshot(cx);
11814
11815        let ranges = snapshot
11816            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11817            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11818            .collect::<Vec<_>>();
11819
11820        let creases = ranges
11821            .into_iter()
11822            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11823            .collect();
11824
11825        self.fold_creases(creases, true, window, cx);
11826    }
11827
11828    pub fn fold_recursive(
11829        &mut self,
11830        _: &actions::FoldRecursive,
11831        window: &mut Window,
11832        cx: &mut Context<Self>,
11833    ) {
11834        let mut to_fold = Vec::new();
11835        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11836        let selections = self.selections.all_adjusted(cx);
11837
11838        for selection in selections {
11839            let range = selection.range().sorted();
11840            let buffer_start_row = range.start.row;
11841
11842            if range.start.row != range.end.row {
11843                let mut found = false;
11844                for row in range.start.row..=range.end.row {
11845                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11846                        found = true;
11847                        to_fold.push(crease);
11848                    }
11849                }
11850                if found {
11851                    continue;
11852                }
11853            }
11854
11855            for row in (0..=range.start.row).rev() {
11856                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11857                    if crease.range().end.row >= buffer_start_row {
11858                        to_fold.push(crease);
11859                    } else {
11860                        break;
11861                    }
11862                }
11863            }
11864        }
11865
11866        self.fold_creases(to_fold, true, window, cx);
11867    }
11868
11869    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11870        let buffer_row = fold_at.buffer_row;
11871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11872
11873        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11874            let autoscroll = self
11875                .selections
11876                .all::<Point>(cx)
11877                .iter()
11878                .any(|selection| crease.range().overlaps(&selection.range()));
11879
11880            self.fold_creases(vec![crease], autoscroll, window, cx);
11881        }
11882    }
11883
11884    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11885        if self.is_singleton(cx) {
11886            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11887            let buffer = &display_map.buffer_snapshot;
11888            let selections = self.selections.all::<Point>(cx);
11889            let ranges = selections
11890                .iter()
11891                .map(|s| {
11892                    let range = s.display_range(&display_map).sorted();
11893                    let mut start = range.start.to_point(&display_map);
11894                    let mut end = range.end.to_point(&display_map);
11895                    start.column = 0;
11896                    end.column = buffer.line_len(MultiBufferRow(end.row));
11897                    start..end
11898                })
11899                .collect::<Vec<_>>();
11900
11901            self.unfold_ranges(&ranges, true, true, cx);
11902        } else {
11903            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11904            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11905                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11906                .map(|(snapshot, _, _)| snapshot.remote_id())
11907                .collect();
11908            for buffer_id in buffer_ids {
11909                self.unfold_buffer(buffer_id, cx);
11910            }
11911        }
11912    }
11913
11914    pub fn unfold_recursive(
11915        &mut self,
11916        _: &UnfoldRecursive,
11917        _window: &mut Window,
11918        cx: &mut Context<Self>,
11919    ) {
11920        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11921        let selections = self.selections.all::<Point>(cx);
11922        let ranges = selections
11923            .iter()
11924            .map(|s| {
11925                let mut range = s.display_range(&display_map).sorted();
11926                *range.start.column_mut() = 0;
11927                *range.end.column_mut() = display_map.line_len(range.end.row());
11928                let start = range.start.to_point(&display_map);
11929                let end = range.end.to_point(&display_map);
11930                start..end
11931            })
11932            .collect::<Vec<_>>();
11933
11934        self.unfold_ranges(&ranges, true, true, cx);
11935    }
11936
11937    pub fn unfold_at(
11938        &mut self,
11939        unfold_at: &UnfoldAt,
11940        _window: &mut Window,
11941        cx: &mut Context<Self>,
11942    ) {
11943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11944
11945        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11946            ..Point::new(
11947                unfold_at.buffer_row.0,
11948                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11949            );
11950
11951        let autoscroll = self
11952            .selections
11953            .all::<Point>(cx)
11954            .iter()
11955            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11956
11957        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11958    }
11959
11960    pub fn unfold_all(
11961        &mut self,
11962        _: &actions::UnfoldAll,
11963        _window: &mut Window,
11964        cx: &mut Context<Self>,
11965    ) {
11966        if self.buffer.read(cx).is_singleton() {
11967            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11968            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11969        } else {
11970            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11971                editor
11972                    .update(&mut cx, |editor, cx| {
11973                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11974                            editor.unfold_buffer(buffer_id, cx);
11975                        }
11976                    })
11977                    .ok();
11978            });
11979        }
11980    }
11981
11982    pub fn fold_selected_ranges(
11983        &mut self,
11984        _: &FoldSelectedRanges,
11985        window: &mut Window,
11986        cx: &mut Context<Self>,
11987    ) {
11988        let selections = self.selections.all::<Point>(cx);
11989        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11990        let line_mode = self.selections.line_mode;
11991        let ranges = selections
11992            .into_iter()
11993            .map(|s| {
11994                if line_mode {
11995                    let start = Point::new(s.start.row, 0);
11996                    let end = Point::new(
11997                        s.end.row,
11998                        display_map
11999                            .buffer_snapshot
12000                            .line_len(MultiBufferRow(s.end.row)),
12001                    );
12002                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12003                } else {
12004                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12005                }
12006            })
12007            .collect::<Vec<_>>();
12008        self.fold_creases(ranges, true, window, cx);
12009    }
12010
12011    pub fn fold_ranges<T: ToOffset + Clone>(
12012        &mut self,
12013        ranges: Vec<Range<T>>,
12014        auto_scroll: bool,
12015        window: &mut Window,
12016        cx: &mut Context<Self>,
12017    ) {
12018        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12019        let ranges = ranges
12020            .into_iter()
12021            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12022            .collect::<Vec<_>>();
12023        self.fold_creases(ranges, auto_scroll, window, cx);
12024    }
12025
12026    pub fn fold_creases<T: ToOffset + Clone>(
12027        &mut self,
12028        creases: Vec<Crease<T>>,
12029        auto_scroll: bool,
12030        window: &mut Window,
12031        cx: &mut Context<Self>,
12032    ) {
12033        if creases.is_empty() {
12034            return;
12035        }
12036
12037        let mut buffers_affected = HashSet::default();
12038        let multi_buffer = self.buffer().read(cx);
12039        for crease in &creases {
12040            if let Some((_, buffer, _)) =
12041                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12042            {
12043                buffers_affected.insert(buffer.read(cx).remote_id());
12044            };
12045        }
12046
12047        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12048
12049        if auto_scroll {
12050            self.request_autoscroll(Autoscroll::fit(), cx);
12051        }
12052
12053        cx.notify();
12054
12055        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12056            // Clear diagnostics block when folding a range that contains it.
12057            let snapshot = self.snapshot(window, cx);
12058            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12059                drop(snapshot);
12060                self.active_diagnostics = Some(active_diagnostics);
12061                self.dismiss_diagnostics(cx);
12062            } else {
12063                self.active_diagnostics = Some(active_diagnostics);
12064            }
12065        }
12066
12067        self.scrollbar_marker_state.dirty = true;
12068    }
12069
12070    /// Removes any folds whose ranges intersect any of the given ranges.
12071    pub fn unfold_ranges<T: ToOffset + Clone>(
12072        &mut self,
12073        ranges: &[Range<T>],
12074        inclusive: bool,
12075        auto_scroll: bool,
12076        cx: &mut Context<Self>,
12077    ) {
12078        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12079            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12080        });
12081    }
12082
12083    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12084        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12085            return;
12086        }
12087        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12088        self.display_map
12089            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12090        cx.emit(EditorEvent::BufferFoldToggled {
12091            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12092            folded: true,
12093        });
12094        cx.notify();
12095    }
12096
12097    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12098        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12099            return;
12100        }
12101        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12102        self.display_map.update(cx, |display_map, cx| {
12103            display_map.unfold_buffer(buffer_id, cx);
12104        });
12105        cx.emit(EditorEvent::BufferFoldToggled {
12106            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12107            folded: false,
12108        });
12109        cx.notify();
12110    }
12111
12112    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12113        self.display_map.read(cx).is_buffer_folded(buffer)
12114    }
12115
12116    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12117        self.display_map.read(cx).folded_buffers()
12118    }
12119
12120    /// Removes any folds with the given ranges.
12121    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12122        &mut self,
12123        ranges: &[Range<T>],
12124        type_id: TypeId,
12125        auto_scroll: bool,
12126        cx: &mut Context<Self>,
12127    ) {
12128        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12129            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12130        });
12131    }
12132
12133    fn remove_folds_with<T: ToOffset + Clone>(
12134        &mut self,
12135        ranges: &[Range<T>],
12136        auto_scroll: bool,
12137        cx: &mut Context<Self>,
12138        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12139    ) {
12140        if ranges.is_empty() {
12141            return;
12142        }
12143
12144        let mut buffers_affected = HashSet::default();
12145        let multi_buffer = self.buffer().read(cx);
12146        for range in ranges {
12147            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12148                buffers_affected.insert(buffer.read(cx).remote_id());
12149            };
12150        }
12151
12152        self.display_map.update(cx, update);
12153
12154        if auto_scroll {
12155            self.request_autoscroll(Autoscroll::fit(), cx);
12156        }
12157
12158        cx.notify();
12159        self.scrollbar_marker_state.dirty = true;
12160        self.active_indent_guides_state.dirty = true;
12161    }
12162
12163    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12164        self.display_map.read(cx).fold_placeholder.clone()
12165    }
12166
12167    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12168        self.buffer.update(cx, |buffer, cx| {
12169            buffer.set_all_diff_hunks_expanded(cx);
12170        });
12171    }
12172
12173    pub fn expand_all_diff_hunks(
12174        &mut self,
12175        _: &ExpandAllHunkDiffs,
12176        _window: &mut Window,
12177        cx: &mut Context<Self>,
12178    ) {
12179        self.buffer.update(cx, |buffer, cx| {
12180            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12181        });
12182    }
12183
12184    pub fn toggle_selected_diff_hunks(
12185        &mut self,
12186        _: &ToggleSelectedDiffHunks,
12187        _window: &mut Window,
12188        cx: &mut Context<Self>,
12189    ) {
12190        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12191        self.toggle_diff_hunks_in_ranges(ranges, cx);
12192    }
12193
12194    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12195        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12196        self.buffer
12197            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12198    }
12199
12200    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12201        self.buffer.update(cx, |buffer, cx| {
12202            let ranges = vec![Anchor::min()..Anchor::max()];
12203            if !buffer.all_diff_hunks_expanded()
12204                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12205            {
12206                buffer.collapse_diff_hunks(ranges, cx);
12207                true
12208            } else {
12209                false
12210            }
12211        })
12212    }
12213
12214    fn toggle_diff_hunks_in_ranges(
12215        &mut self,
12216        ranges: Vec<Range<Anchor>>,
12217        cx: &mut Context<'_, Editor>,
12218    ) {
12219        self.buffer.update(cx, |buffer, cx| {
12220            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12221                buffer.collapse_diff_hunks(ranges, cx)
12222            } else {
12223                buffer.expand_diff_hunks(ranges, cx)
12224            }
12225        })
12226    }
12227
12228    pub(crate) fn apply_all_diff_hunks(
12229        &mut self,
12230        _: &ApplyAllDiffHunks,
12231        window: &mut Window,
12232        cx: &mut Context<Self>,
12233    ) {
12234        let buffers = self.buffer.read(cx).all_buffers();
12235        for branch_buffer in buffers {
12236            branch_buffer.update(cx, |branch_buffer, cx| {
12237                branch_buffer.merge_into_base(Vec::new(), cx);
12238            });
12239        }
12240
12241        if let Some(project) = self.project.clone() {
12242            self.save(true, project, window, cx).detach_and_log_err(cx);
12243        }
12244    }
12245
12246    pub(crate) fn apply_selected_diff_hunks(
12247        &mut self,
12248        _: &ApplyDiffHunk,
12249        window: &mut Window,
12250        cx: &mut Context<Self>,
12251    ) {
12252        let snapshot = self.snapshot(window, cx);
12253        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12254        let mut ranges_by_buffer = HashMap::default();
12255        self.transact(window, cx, |editor, _window, cx| {
12256            for hunk in hunks {
12257                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12258                    ranges_by_buffer
12259                        .entry(buffer.clone())
12260                        .or_insert_with(Vec::new)
12261                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12262                }
12263            }
12264
12265            for (buffer, ranges) in ranges_by_buffer {
12266                buffer.update(cx, |buffer, cx| {
12267                    buffer.merge_into_base(ranges, cx);
12268                });
12269            }
12270        });
12271
12272        if let Some(project) = self.project.clone() {
12273            self.save(true, project, window, cx).detach_and_log_err(cx);
12274        }
12275    }
12276
12277    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12278        if hovered != self.gutter_hovered {
12279            self.gutter_hovered = hovered;
12280            cx.notify();
12281        }
12282    }
12283
12284    pub fn insert_blocks(
12285        &mut self,
12286        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12287        autoscroll: Option<Autoscroll>,
12288        cx: &mut Context<Self>,
12289    ) -> Vec<CustomBlockId> {
12290        let blocks = self
12291            .display_map
12292            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12293        if let Some(autoscroll) = autoscroll {
12294            self.request_autoscroll(autoscroll, cx);
12295        }
12296        cx.notify();
12297        blocks
12298    }
12299
12300    pub fn resize_blocks(
12301        &mut self,
12302        heights: HashMap<CustomBlockId, u32>,
12303        autoscroll: Option<Autoscroll>,
12304        cx: &mut Context<Self>,
12305    ) {
12306        self.display_map
12307            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12308        if let Some(autoscroll) = autoscroll {
12309            self.request_autoscroll(autoscroll, cx);
12310        }
12311        cx.notify();
12312    }
12313
12314    pub fn replace_blocks(
12315        &mut self,
12316        renderers: HashMap<CustomBlockId, RenderBlock>,
12317        autoscroll: Option<Autoscroll>,
12318        cx: &mut Context<Self>,
12319    ) {
12320        self.display_map
12321            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12322        if let Some(autoscroll) = autoscroll {
12323            self.request_autoscroll(autoscroll, cx);
12324        }
12325        cx.notify();
12326    }
12327
12328    pub fn remove_blocks(
12329        &mut self,
12330        block_ids: HashSet<CustomBlockId>,
12331        autoscroll: Option<Autoscroll>,
12332        cx: &mut Context<Self>,
12333    ) {
12334        self.display_map.update(cx, |display_map, cx| {
12335            display_map.remove_blocks(block_ids, cx)
12336        });
12337        if let Some(autoscroll) = autoscroll {
12338            self.request_autoscroll(autoscroll, cx);
12339        }
12340        cx.notify();
12341    }
12342
12343    pub fn row_for_block(
12344        &self,
12345        block_id: CustomBlockId,
12346        cx: &mut Context<Self>,
12347    ) -> Option<DisplayRow> {
12348        self.display_map
12349            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12350    }
12351
12352    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12353        self.focused_block = Some(focused_block);
12354    }
12355
12356    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12357        self.focused_block.take()
12358    }
12359
12360    pub fn insert_creases(
12361        &mut self,
12362        creases: impl IntoIterator<Item = Crease<Anchor>>,
12363        cx: &mut Context<Self>,
12364    ) -> Vec<CreaseId> {
12365        self.display_map
12366            .update(cx, |map, cx| map.insert_creases(creases, cx))
12367    }
12368
12369    pub fn remove_creases(
12370        &mut self,
12371        ids: impl IntoIterator<Item = CreaseId>,
12372        cx: &mut Context<Self>,
12373    ) {
12374        self.display_map
12375            .update(cx, |map, cx| map.remove_creases(ids, cx));
12376    }
12377
12378    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12379        self.display_map
12380            .update(cx, |map, cx| map.snapshot(cx))
12381            .longest_row()
12382    }
12383
12384    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12385        self.display_map
12386            .update(cx, |map, cx| map.snapshot(cx))
12387            .max_point()
12388    }
12389
12390    pub fn text(&self, cx: &App) -> String {
12391        self.buffer.read(cx).read(cx).text()
12392    }
12393
12394    pub fn is_empty(&self, cx: &App) -> bool {
12395        self.buffer.read(cx).read(cx).is_empty()
12396    }
12397
12398    pub fn text_option(&self, cx: &App) -> Option<String> {
12399        let text = self.text(cx);
12400        let text = text.trim();
12401
12402        if text.is_empty() {
12403            return None;
12404        }
12405
12406        Some(text.to_string())
12407    }
12408
12409    pub fn set_text(
12410        &mut self,
12411        text: impl Into<Arc<str>>,
12412        window: &mut Window,
12413        cx: &mut Context<Self>,
12414    ) {
12415        self.transact(window, cx, |this, _, cx| {
12416            this.buffer
12417                .read(cx)
12418                .as_singleton()
12419                .expect("you can only call set_text on editors for singleton buffers")
12420                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12421        });
12422    }
12423
12424    pub fn display_text(&self, cx: &mut App) -> String {
12425        self.display_map
12426            .update(cx, |map, cx| map.snapshot(cx))
12427            .text()
12428    }
12429
12430    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12431        let mut wrap_guides = smallvec::smallvec![];
12432
12433        if self.show_wrap_guides == Some(false) {
12434            return wrap_guides;
12435        }
12436
12437        let settings = self.buffer.read(cx).settings_at(0, cx);
12438        if settings.show_wrap_guides {
12439            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12440                wrap_guides.push((soft_wrap as usize, true));
12441            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12442                wrap_guides.push((soft_wrap as usize, true));
12443            }
12444            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12445        }
12446
12447        wrap_guides
12448    }
12449
12450    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12451        let settings = self.buffer.read(cx).settings_at(0, cx);
12452        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12453        match mode {
12454            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12455                SoftWrap::None
12456            }
12457            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12458            language_settings::SoftWrap::PreferredLineLength => {
12459                SoftWrap::Column(settings.preferred_line_length)
12460            }
12461            language_settings::SoftWrap::Bounded => {
12462                SoftWrap::Bounded(settings.preferred_line_length)
12463            }
12464        }
12465    }
12466
12467    pub fn set_soft_wrap_mode(
12468        &mut self,
12469        mode: language_settings::SoftWrap,
12470
12471        cx: &mut Context<Self>,
12472    ) {
12473        self.soft_wrap_mode_override = Some(mode);
12474        cx.notify();
12475    }
12476
12477    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12478        self.text_style_refinement = Some(style);
12479    }
12480
12481    /// called by the Element so we know what style we were most recently rendered with.
12482    pub(crate) fn set_style(
12483        &mut self,
12484        style: EditorStyle,
12485        window: &mut Window,
12486        cx: &mut Context<Self>,
12487    ) {
12488        let rem_size = window.rem_size();
12489        self.display_map.update(cx, |map, cx| {
12490            map.set_font(
12491                style.text.font(),
12492                style.text.font_size.to_pixels(rem_size),
12493                cx,
12494            )
12495        });
12496        self.style = Some(style);
12497    }
12498
12499    pub fn style(&self) -> Option<&EditorStyle> {
12500        self.style.as_ref()
12501    }
12502
12503    // Called by the element. This method is not designed to be called outside of the editor
12504    // element's layout code because it does not notify when rewrapping is computed synchronously.
12505    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12506        self.display_map
12507            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12508    }
12509
12510    pub fn set_soft_wrap(&mut self) {
12511        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12512    }
12513
12514    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12515        if self.soft_wrap_mode_override.is_some() {
12516            self.soft_wrap_mode_override.take();
12517        } else {
12518            let soft_wrap = match self.soft_wrap_mode(cx) {
12519                SoftWrap::GitDiff => return,
12520                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12521                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12522                    language_settings::SoftWrap::None
12523                }
12524            };
12525            self.soft_wrap_mode_override = Some(soft_wrap);
12526        }
12527        cx.notify();
12528    }
12529
12530    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12531        let Some(workspace) = self.workspace() else {
12532            return;
12533        };
12534        let fs = workspace.read(cx).app_state().fs.clone();
12535        let current_show = TabBarSettings::get_global(cx).show;
12536        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12537            setting.show = Some(!current_show);
12538        });
12539    }
12540
12541    pub fn toggle_indent_guides(
12542        &mut self,
12543        _: &ToggleIndentGuides,
12544        _: &mut Window,
12545        cx: &mut Context<Self>,
12546    ) {
12547        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12548            self.buffer
12549                .read(cx)
12550                .settings_at(0, cx)
12551                .indent_guides
12552                .enabled
12553        });
12554        self.show_indent_guides = Some(!currently_enabled);
12555        cx.notify();
12556    }
12557
12558    fn should_show_indent_guides(&self) -> Option<bool> {
12559        self.show_indent_guides
12560    }
12561
12562    pub fn toggle_line_numbers(
12563        &mut self,
12564        _: &ToggleLineNumbers,
12565        _: &mut Window,
12566        cx: &mut Context<Self>,
12567    ) {
12568        let mut editor_settings = EditorSettings::get_global(cx).clone();
12569        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12570        EditorSettings::override_global(editor_settings, cx);
12571    }
12572
12573    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12574        self.use_relative_line_numbers
12575            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12576    }
12577
12578    pub fn toggle_relative_line_numbers(
12579        &mut self,
12580        _: &ToggleRelativeLineNumbers,
12581        _: &mut Window,
12582        cx: &mut Context<Self>,
12583    ) {
12584        let is_relative = self.should_use_relative_line_numbers(cx);
12585        self.set_relative_line_number(Some(!is_relative), cx)
12586    }
12587
12588    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12589        self.use_relative_line_numbers = is_relative;
12590        cx.notify();
12591    }
12592
12593    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12594        self.show_gutter = show_gutter;
12595        cx.notify();
12596    }
12597
12598    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12599        self.show_scrollbars = show_scrollbars;
12600        cx.notify();
12601    }
12602
12603    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12604        self.show_line_numbers = Some(show_line_numbers);
12605        cx.notify();
12606    }
12607
12608    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12609        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12610        cx.notify();
12611    }
12612
12613    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12614        self.show_code_actions = Some(show_code_actions);
12615        cx.notify();
12616    }
12617
12618    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12619        self.show_runnables = Some(show_runnables);
12620        cx.notify();
12621    }
12622
12623    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12624        if self.display_map.read(cx).masked != masked {
12625            self.display_map.update(cx, |map, _| map.masked = masked);
12626        }
12627        cx.notify()
12628    }
12629
12630    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12631        self.show_wrap_guides = Some(show_wrap_guides);
12632        cx.notify();
12633    }
12634
12635    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12636        self.show_indent_guides = Some(show_indent_guides);
12637        cx.notify();
12638    }
12639
12640    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12641        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12642            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12643                if let Some(dir) = file.abs_path(cx).parent() {
12644                    return Some(dir.to_owned());
12645                }
12646            }
12647
12648            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12649                return Some(project_path.path.to_path_buf());
12650            }
12651        }
12652
12653        None
12654    }
12655
12656    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12657        self.active_excerpt(cx)?
12658            .1
12659            .read(cx)
12660            .file()
12661            .and_then(|f| f.as_local())
12662    }
12663
12664    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12665        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12666            let project_path = buffer.read(cx).project_path(cx)?;
12667            let project = self.project.as_ref()?.read(cx);
12668            project.absolute_path(&project_path, cx)
12669        })
12670    }
12671
12672    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12673        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12674            let project_path = buffer.read(cx).project_path(cx)?;
12675            let project = self.project.as_ref()?.read(cx);
12676            let entry = project.entry_for_path(&project_path, cx)?;
12677            let path = entry.path.to_path_buf();
12678            Some(path)
12679        })
12680    }
12681
12682    pub fn reveal_in_finder(
12683        &mut self,
12684        _: &RevealInFileManager,
12685        _window: &mut Window,
12686        cx: &mut Context<Self>,
12687    ) {
12688        if let Some(target) = self.target_file(cx) {
12689            cx.reveal_path(&target.abs_path(cx));
12690        }
12691    }
12692
12693    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12694        if let Some(path) = self.target_file_abs_path(cx) {
12695            if let Some(path) = path.to_str() {
12696                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12697            }
12698        }
12699    }
12700
12701    pub fn copy_relative_path(
12702        &mut self,
12703        _: &CopyRelativePath,
12704        _window: &mut Window,
12705        cx: &mut Context<Self>,
12706    ) {
12707        if let Some(path) = self.target_file_path(cx) {
12708            if let Some(path) = path.to_str() {
12709                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12710            }
12711        }
12712    }
12713
12714    pub fn toggle_git_blame(
12715        &mut self,
12716        _: &ToggleGitBlame,
12717        window: &mut Window,
12718        cx: &mut Context<Self>,
12719    ) {
12720        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12721
12722        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12723            self.start_git_blame(true, window, cx);
12724        }
12725
12726        cx.notify();
12727    }
12728
12729    pub fn toggle_git_blame_inline(
12730        &mut self,
12731        _: &ToggleGitBlameInline,
12732        window: &mut Window,
12733        cx: &mut Context<Self>,
12734    ) {
12735        self.toggle_git_blame_inline_internal(true, window, cx);
12736        cx.notify();
12737    }
12738
12739    pub fn git_blame_inline_enabled(&self) -> bool {
12740        self.git_blame_inline_enabled
12741    }
12742
12743    pub fn toggle_selection_menu(
12744        &mut self,
12745        _: &ToggleSelectionMenu,
12746        _: &mut Window,
12747        cx: &mut Context<Self>,
12748    ) {
12749        self.show_selection_menu = self
12750            .show_selection_menu
12751            .map(|show_selections_menu| !show_selections_menu)
12752            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12753
12754        cx.notify();
12755    }
12756
12757    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12758        self.show_selection_menu
12759            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12760    }
12761
12762    fn start_git_blame(
12763        &mut self,
12764        user_triggered: bool,
12765        window: &mut Window,
12766        cx: &mut Context<Self>,
12767    ) {
12768        if let Some(project) = self.project.as_ref() {
12769            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12770                return;
12771            };
12772
12773            if buffer.read(cx).file().is_none() {
12774                return;
12775            }
12776
12777            let focused = self.focus_handle(cx).contains_focused(window, cx);
12778
12779            let project = project.clone();
12780            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12781            self.blame_subscription =
12782                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12783            self.blame = Some(blame);
12784        }
12785    }
12786
12787    fn toggle_git_blame_inline_internal(
12788        &mut self,
12789        user_triggered: bool,
12790        window: &mut Window,
12791        cx: &mut Context<Self>,
12792    ) {
12793        if self.git_blame_inline_enabled {
12794            self.git_blame_inline_enabled = false;
12795            self.show_git_blame_inline = false;
12796            self.show_git_blame_inline_delay_task.take();
12797        } else {
12798            self.git_blame_inline_enabled = true;
12799            self.start_git_blame_inline(user_triggered, window, cx);
12800        }
12801
12802        cx.notify();
12803    }
12804
12805    fn start_git_blame_inline(
12806        &mut self,
12807        user_triggered: bool,
12808        window: &mut Window,
12809        cx: &mut Context<Self>,
12810    ) {
12811        self.start_git_blame(user_triggered, window, cx);
12812
12813        if ProjectSettings::get_global(cx)
12814            .git
12815            .inline_blame_delay()
12816            .is_some()
12817        {
12818            self.start_inline_blame_timer(window, cx);
12819        } else {
12820            self.show_git_blame_inline = true
12821        }
12822    }
12823
12824    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12825        self.blame.as_ref()
12826    }
12827
12828    pub fn show_git_blame_gutter(&self) -> bool {
12829        self.show_git_blame_gutter
12830    }
12831
12832    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12833        self.show_git_blame_gutter && self.has_blame_entries(cx)
12834    }
12835
12836    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12837        self.show_git_blame_inline
12838            && self.focus_handle.is_focused(window)
12839            && !self.newest_selection_head_on_empty_line(cx)
12840            && self.has_blame_entries(cx)
12841    }
12842
12843    fn has_blame_entries(&self, cx: &App) -> bool {
12844        self.blame()
12845            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12846    }
12847
12848    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12849        let cursor_anchor = self.selections.newest_anchor().head();
12850
12851        let snapshot = self.buffer.read(cx).snapshot(cx);
12852        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12853
12854        snapshot.line_len(buffer_row) == 0
12855    }
12856
12857    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12858        let buffer_and_selection = maybe!({
12859            let selection = self.selections.newest::<Point>(cx);
12860            let selection_range = selection.range();
12861
12862            let multi_buffer = self.buffer().read(cx);
12863            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12864            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12865
12866            let (buffer, range, _) = if selection.reversed {
12867                buffer_ranges.first()
12868            } else {
12869                buffer_ranges.last()
12870            }?;
12871
12872            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12873                ..text::ToPoint::to_point(&range.end, &buffer).row;
12874            Some((
12875                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12876                selection,
12877            ))
12878        });
12879
12880        let Some((buffer, selection)) = buffer_and_selection else {
12881            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12882        };
12883
12884        let Some(project) = self.project.as_ref() else {
12885            return Task::ready(Err(anyhow!("editor does not have project")));
12886        };
12887
12888        project.update(cx, |project, cx| {
12889            project.get_permalink_to_line(&buffer, selection, cx)
12890        })
12891    }
12892
12893    pub fn copy_permalink_to_line(
12894        &mut self,
12895        _: &CopyPermalinkToLine,
12896        window: &mut Window,
12897        cx: &mut Context<Self>,
12898    ) {
12899        let permalink_task = self.get_permalink_to_line(cx);
12900        let workspace = self.workspace();
12901
12902        cx.spawn_in(window, |_, mut cx| async move {
12903            match permalink_task.await {
12904                Ok(permalink) => {
12905                    cx.update(|_, cx| {
12906                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12907                    })
12908                    .ok();
12909                }
12910                Err(err) => {
12911                    let message = format!("Failed to copy permalink: {err}");
12912
12913                    Err::<(), anyhow::Error>(err).log_err();
12914
12915                    if let Some(workspace) = workspace {
12916                        workspace
12917                            .update_in(&mut cx, |workspace, _, cx| {
12918                                struct CopyPermalinkToLine;
12919
12920                                workspace.show_toast(
12921                                    Toast::new(
12922                                        NotificationId::unique::<CopyPermalinkToLine>(),
12923                                        message,
12924                                    ),
12925                                    cx,
12926                                )
12927                            })
12928                            .ok();
12929                    }
12930                }
12931            }
12932        })
12933        .detach();
12934    }
12935
12936    pub fn copy_file_location(
12937        &mut self,
12938        _: &CopyFileLocation,
12939        _: &mut Window,
12940        cx: &mut Context<Self>,
12941    ) {
12942        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12943        if let Some(file) = self.target_file(cx) {
12944            if let Some(path) = file.path().to_str() {
12945                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12946            }
12947        }
12948    }
12949
12950    pub fn open_permalink_to_line(
12951        &mut self,
12952        _: &OpenPermalinkToLine,
12953        window: &mut Window,
12954        cx: &mut Context<Self>,
12955    ) {
12956        let permalink_task = self.get_permalink_to_line(cx);
12957        let workspace = self.workspace();
12958
12959        cx.spawn_in(window, |_, mut cx| async move {
12960            match permalink_task.await {
12961                Ok(permalink) => {
12962                    cx.update(|_, cx| {
12963                        cx.open_url(permalink.as_ref());
12964                    })
12965                    .ok();
12966                }
12967                Err(err) => {
12968                    let message = format!("Failed to open permalink: {err}");
12969
12970                    Err::<(), anyhow::Error>(err).log_err();
12971
12972                    if let Some(workspace) = workspace {
12973                        workspace
12974                            .update(&mut cx, |workspace, cx| {
12975                                struct OpenPermalinkToLine;
12976
12977                                workspace.show_toast(
12978                                    Toast::new(
12979                                        NotificationId::unique::<OpenPermalinkToLine>(),
12980                                        message,
12981                                    ),
12982                                    cx,
12983                                )
12984                            })
12985                            .ok();
12986                    }
12987                }
12988            }
12989        })
12990        .detach();
12991    }
12992
12993    pub fn insert_uuid_v4(
12994        &mut self,
12995        _: &InsertUuidV4,
12996        window: &mut Window,
12997        cx: &mut Context<Self>,
12998    ) {
12999        self.insert_uuid(UuidVersion::V4, window, cx);
13000    }
13001
13002    pub fn insert_uuid_v7(
13003        &mut self,
13004        _: &InsertUuidV7,
13005        window: &mut Window,
13006        cx: &mut Context<Self>,
13007    ) {
13008        self.insert_uuid(UuidVersion::V7, window, cx);
13009    }
13010
13011    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13012        self.transact(window, cx, |this, window, cx| {
13013            let edits = this
13014                .selections
13015                .all::<Point>(cx)
13016                .into_iter()
13017                .map(|selection| {
13018                    let uuid = match version {
13019                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13020                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13021                    };
13022
13023                    (selection.range(), uuid.to_string())
13024                });
13025            this.edit(edits, cx);
13026            this.refresh_inline_completion(true, false, window, cx);
13027        });
13028    }
13029
13030    pub fn open_selections_in_multibuffer(
13031        &mut self,
13032        _: &OpenSelectionsInMultibuffer,
13033        window: &mut Window,
13034        cx: &mut Context<Self>,
13035    ) {
13036        let multibuffer = self.buffer.read(cx);
13037
13038        let Some(buffer) = multibuffer.as_singleton() else {
13039            return;
13040        };
13041
13042        let Some(workspace) = self.workspace() else {
13043            return;
13044        };
13045
13046        let locations = self
13047            .selections
13048            .disjoint_anchors()
13049            .iter()
13050            .map(|range| Location {
13051                buffer: buffer.clone(),
13052                range: range.start.text_anchor..range.end.text_anchor,
13053            })
13054            .collect::<Vec<_>>();
13055
13056        let title = multibuffer.title(cx).to_string();
13057
13058        cx.spawn_in(window, |_, mut cx| async move {
13059            workspace.update_in(&mut cx, |workspace, window, cx| {
13060                Self::open_locations_in_multibuffer(
13061                    workspace,
13062                    locations,
13063                    format!("Selections for '{title}'"),
13064                    false,
13065                    MultibufferSelectionMode::All,
13066                    window,
13067                    cx,
13068                );
13069            })
13070        })
13071        .detach();
13072    }
13073
13074    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13075    /// last highlight added will be used.
13076    ///
13077    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13078    pub fn highlight_rows<T: 'static>(
13079        &mut self,
13080        range: Range<Anchor>,
13081        color: Hsla,
13082        should_autoscroll: bool,
13083        cx: &mut Context<Self>,
13084    ) {
13085        let snapshot = self.buffer().read(cx).snapshot(cx);
13086        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13087        let ix = row_highlights.binary_search_by(|highlight| {
13088            Ordering::Equal
13089                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13090                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13091        });
13092
13093        if let Err(mut ix) = ix {
13094            let index = post_inc(&mut self.highlight_order);
13095
13096            // If this range intersects with the preceding highlight, then merge it with
13097            // the preceding highlight. Otherwise insert a new highlight.
13098            let mut merged = false;
13099            if ix > 0 {
13100                let prev_highlight = &mut row_highlights[ix - 1];
13101                if prev_highlight
13102                    .range
13103                    .end
13104                    .cmp(&range.start, &snapshot)
13105                    .is_ge()
13106                {
13107                    ix -= 1;
13108                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13109                        prev_highlight.range.end = range.end;
13110                    }
13111                    merged = true;
13112                    prev_highlight.index = index;
13113                    prev_highlight.color = color;
13114                    prev_highlight.should_autoscroll = should_autoscroll;
13115                }
13116            }
13117
13118            if !merged {
13119                row_highlights.insert(
13120                    ix,
13121                    RowHighlight {
13122                        range: range.clone(),
13123                        index,
13124                        color,
13125                        should_autoscroll,
13126                    },
13127                );
13128            }
13129
13130            // If any of the following highlights intersect with this one, merge them.
13131            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13132                let highlight = &row_highlights[ix];
13133                if next_highlight
13134                    .range
13135                    .start
13136                    .cmp(&highlight.range.end, &snapshot)
13137                    .is_le()
13138                {
13139                    if next_highlight
13140                        .range
13141                        .end
13142                        .cmp(&highlight.range.end, &snapshot)
13143                        .is_gt()
13144                    {
13145                        row_highlights[ix].range.end = next_highlight.range.end;
13146                    }
13147                    row_highlights.remove(ix + 1);
13148                } else {
13149                    break;
13150                }
13151            }
13152        }
13153    }
13154
13155    /// Remove any highlighted row ranges of the given type that intersect the
13156    /// given ranges.
13157    pub fn remove_highlighted_rows<T: 'static>(
13158        &mut self,
13159        ranges_to_remove: Vec<Range<Anchor>>,
13160        cx: &mut Context<Self>,
13161    ) {
13162        let snapshot = self.buffer().read(cx).snapshot(cx);
13163        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13164        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13165        row_highlights.retain(|highlight| {
13166            while let Some(range_to_remove) = ranges_to_remove.peek() {
13167                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13168                    Ordering::Less | Ordering::Equal => {
13169                        ranges_to_remove.next();
13170                    }
13171                    Ordering::Greater => {
13172                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13173                            Ordering::Less | Ordering::Equal => {
13174                                return false;
13175                            }
13176                            Ordering::Greater => break,
13177                        }
13178                    }
13179                }
13180            }
13181
13182            true
13183        })
13184    }
13185
13186    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13187    pub fn clear_row_highlights<T: 'static>(&mut self) {
13188        self.highlighted_rows.remove(&TypeId::of::<T>());
13189    }
13190
13191    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13192    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13193        self.highlighted_rows
13194            .get(&TypeId::of::<T>())
13195            .map_or(&[] as &[_], |vec| vec.as_slice())
13196            .iter()
13197            .map(|highlight| (highlight.range.clone(), highlight.color))
13198    }
13199
13200    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13201    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13202    /// Allows to ignore certain kinds of highlights.
13203    pub fn highlighted_display_rows(
13204        &self,
13205        window: &mut Window,
13206        cx: &mut App,
13207    ) -> BTreeMap<DisplayRow, Hsla> {
13208        let snapshot = self.snapshot(window, cx);
13209        let mut used_highlight_orders = HashMap::default();
13210        self.highlighted_rows
13211            .iter()
13212            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13213            .fold(
13214                BTreeMap::<DisplayRow, Hsla>::new(),
13215                |mut unique_rows, highlight| {
13216                    let start = highlight.range.start.to_display_point(&snapshot);
13217                    let end = highlight.range.end.to_display_point(&snapshot);
13218                    let start_row = start.row().0;
13219                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13220                        && end.column() == 0
13221                    {
13222                        end.row().0.saturating_sub(1)
13223                    } else {
13224                        end.row().0
13225                    };
13226                    for row in start_row..=end_row {
13227                        let used_index =
13228                            used_highlight_orders.entry(row).or_insert(highlight.index);
13229                        if highlight.index >= *used_index {
13230                            *used_index = highlight.index;
13231                            unique_rows.insert(DisplayRow(row), highlight.color);
13232                        }
13233                    }
13234                    unique_rows
13235                },
13236            )
13237    }
13238
13239    pub fn highlighted_display_row_for_autoscroll(
13240        &self,
13241        snapshot: &DisplaySnapshot,
13242    ) -> Option<DisplayRow> {
13243        self.highlighted_rows
13244            .values()
13245            .flat_map(|highlighted_rows| highlighted_rows.iter())
13246            .filter_map(|highlight| {
13247                if highlight.should_autoscroll {
13248                    Some(highlight.range.start.to_display_point(snapshot).row())
13249                } else {
13250                    None
13251                }
13252            })
13253            .min()
13254    }
13255
13256    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13257        self.highlight_background::<SearchWithinRange>(
13258            ranges,
13259            |colors| colors.editor_document_highlight_read_background,
13260            cx,
13261        )
13262    }
13263
13264    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13265        self.breadcrumb_header = Some(new_header);
13266    }
13267
13268    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13269        self.clear_background_highlights::<SearchWithinRange>(cx);
13270    }
13271
13272    pub fn highlight_background<T: 'static>(
13273        &mut self,
13274        ranges: &[Range<Anchor>],
13275        color_fetcher: fn(&ThemeColors) -> Hsla,
13276        cx: &mut Context<Self>,
13277    ) {
13278        self.background_highlights
13279            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13280        self.scrollbar_marker_state.dirty = true;
13281        cx.notify();
13282    }
13283
13284    pub fn clear_background_highlights<T: 'static>(
13285        &mut self,
13286        cx: &mut Context<Self>,
13287    ) -> Option<BackgroundHighlight> {
13288        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13289        if !text_highlights.1.is_empty() {
13290            self.scrollbar_marker_state.dirty = true;
13291            cx.notify();
13292        }
13293        Some(text_highlights)
13294    }
13295
13296    pub fn highlight_gutter<T: 'static>(
13297        &mut self,
13298        ranges: &[Range<Anchor>],
13299        color_fetcher: fn(&App) -> Hsla,
13300        cx: &mut Context<Self>,
13301    ) {
13302        self.gutter_highlights
13303            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13304        cx.notify();
13305    }
13306
13307    pub fn clear_gutter_highlights<T: 'static>(
13308        &mut self,
13309        cx: &mut Context<Self>,
13310    ) -> Option<GutterHighlight> {
13311        cx.notify();
13312        self.gutter_highlights.remove(&TypeId::of::<T>())
13313    }
13314
13315    #[cfg(feature = "test-support")]
13316    pub fn all_text_background_highlights(
13317        &self,
13318        window: &mut Window,
13319        cx: &mut Context<Self>,
13320    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13321        let snapshot = self.snapshot(window, cx);
13322        let buffer = &snapshot.buffer_snapshot;
13323        let start = buffer.anchor_before(0);
13324        let end = buffer.anchor_after(buffer.len());
13325        let theme = cx.theme().colors();
13326        self.background_highlights_in_range(start..end, &snapshot, theme)
13327    }
13328
13329    #[cfg(feature = "test-support")]
13330    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13331        let snapshot = self.buffer().read(cx).snapshot(cx);
13332
13333        let highlights = self
13334            .background_highlights
13335            .get(&TypeId::of::<items::BufferSearchHighlights>());
13336
13337        if let Some((_color, ranges)) = highlights {
13338            ranges
13339                .iter()
13340                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13341                .collect_vec()
13342        } else {
13343            vec![]
13344        }
13345    }
13346
13347    fn document_highlights_for_position<'a>(
13348        &'a self,
13349        position: Anchor,
13350        buffer: &'a MultiBufferSnapshot,
13351    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13352        let read_highlights = self
13353            .background_highlights
13354            .get(&TypeId::of::<DocumentHighlightRead>())
13355            .map(|h| &h.1);
13356        let write_highlights = self
13357            .background_highlights
13358            .get(&TypeId::of::<DocumentHighlightWrite>())
13359            .map(|h| &h.1);
13360        let left_position = position.bias_left(buffer);
13361        let right_position = position.bias_right(buffer);
13362        read_highlights
13363            .into_iter()
13364            .chain(write_highlights)
13365            .flat_map(move |ranges| {
13366                let start_ix = match ranges.binary_search_by(|probe| {
13367                    let cmp = probe.end.cmp(&left_position, buffer);
13368                    if cmp.is_ge() {
13369                        Ordering::Greater
13370                    } else {
13371                        Ordering::Less
13372                    }
13373                }) {
13374                    Ok(i) | Err(i) => i,
13375                };
13376
13377                ranges[start_ix..]
13378                    .iter()
13379                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13380            })
13381    }
13382
13383    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13384        self.background_highlights
13385            .get(&TypeId::of::<T>())
13386            .map_or(false, |(_, highlights)| !highlights.is_empty())
13387    }
13388
13389    pub fn background_highlights_in_range(
13390        &self,
13391        search_range: Range<Anchor>,
13392        display_snapshot: &DisplaySnapshot,
13393        theme: &ThemeColors,
13394    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13395        let mut results = Vec::new();
13396        for (color_fetcher, ranges) in self.background_highlights.values() {
13397            let color = color_fetcher(theme);
13398            let start_ix = match ranges.binary_search_by(|probe| {
13399                let cmp = probe
13400                    .end
13401                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13402                if cmp.is_gt() {
13403                    Ordering::Greater
13404                } else {
13405                    Ordering::Less
13406                }
13407            }) {
13408                Ok(i) | Err(i) => i,
13409            };
13410            for range in &ranges[start_ix..] {
13411                if range
13412                    .start
13413                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13414                    .is_ge()
13415                {
13416                    break;
13417                }
13418
13419                let start = range.start.to_display_point(display_snapshot);
13420                let end = range.end.to_display_point(display_snapshot);
13421                results.push((start..end, color))
13422            }
13423        }
13424        results
13425    }
13426
13427    pub fn background_highlight_row_ranges<T: 'static>(
13428        &self,
13429        search_range: Range<Anchor>,
13430        display_snapshot: &DisplaySnapshot,
13431        count: usize,
13432    ) -> Vec<RangeInclusive<DisplayPoint>> {
13433        let mut results = Vec::new();
13434        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13435            return vec![];
13436        };
13437
13438        let start_ix = match ranges.binary_search_by(|probe| {
13439            let cmp = probe
13440                .end
13441                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13442            if cmp.is_gt() {
13443                Ordering::Greater
13444            } else {
13445                Ordering::Less
13446            }
13447        }) {
13448            Ok(i) | Err(i) => i,
13449        };
13450        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13451            if let (Some(start_display), Some(end_display)) = (start, end) {
13452                results.push(
13453                    start_display.to_display_point(display_snapshot)
13454                        ..=end_display.to_display_point(display_snapshot),
13455                );
13456            }
13457        };
13458        let mut start_row: Option<Point> = None;
13459        let mut end_row: Option<Point> = None;
13460        if ranges.len() > count {
13461            return Vec::new();
13462        }
13463        for range in &ranges[start_ix..] {
13464            if range
13465                .start
13466                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13467                .is_ge()
13468            {
13469                break;
13470            }
13471            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13472            if let Some(current_row) = &end_row {
13473                if end.row == current_row.row {
13474                    continue;
13475                }
13476            }
13477            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13478            if start_row.is_none() {
13479                assert_eq!(end_row, None);
13480                start_row = Some(start);
13481                end_row = Some(end);
13482                continue;
13483            }
13484            if let Some(current_end) = end_row.as_mut() {
13485                if start.row > current_end.row + 1 {
13486                    push_region(start_row, end_row);
13487                    start_row = Some(start);
13488                    end_row = Some(end);
13489                } else {
13490                    // Merge two hunks.
13491                    *current_end = end;
13492                }
13493            } else {
13494                unreachable!();
13495            }
13496        }
13497        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13498        push_region(start_row, end_row);
13499        results
13500    }
13501
13502    pub fn gutter_highlights_in_range(
13503        &self,
13504        search_range: Range<Anchor>,
13505        display_snapshot: &DisplaySnapshot,
13506        cx: &App,
13507    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13508        let mut results = Vec::new();
13509        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13510            let color = color_fetcher(cx);
13511            let start_ix = match ranges.binary_search_by(|probe| {
13512                let cmp = probe
13513                    .end
13514                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13515                if cmp.is_gt() {
13516                    Ordering::Greater
13517                } else {
13518                    Ordering::Less
13519                }
13520            }) {
13521                Ok(i) | Err(i) => i,
13522            };
13523            for range in &ranges[start_ix..] {
13524                if range
13525                    .start
13526                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13527                    .is_ge()
13528                {
13529                    break;
13530                }
13531
13532                let start = range.start.to_display_point(display_snapshot);
13533                let end = range.end.to_display_point(display_snapshot);
13534                results.push((start..end, color))
13535            }
13536        }
13537        results
13538    }
13539
13540    /// Get the text ranges corresponding to the redaction query
13541    pub fn redacted_ranges(
13542        &self,
13543        search_range: Range<Anchor>,
13544        display_snapshot: &DisplaySnapshot,
13545        cx: &App,
13546    ) -> Vec<Range<DisplayPoint>> {
13547        display_snapshot
13548            .buffer_snapshot
13549            .redacted_ranges(search_range, |file| {
13550                if let Some(file) = file {
13551                    file.is_private()
13552                        && EditorSettings::get(
13553                            Some(SettingsLocation {
13554                                worktree_id: file.worktree_id(cx),
13555                                path: file.path().as_ref(),
13556                            }),
13557                            cx,
13558                        )
13559                        .redact_private_values
13560                } else {
13561                    false
13562                }
13563            })
13564            .map(|range| {
13565                range.start.to_display_point(display_snapshot)
13566                    ..range.end.to_display_point(display_snapshot)
13567            })
13568            .collect()
13569    }
13570
13571    pub fn highlight_text<T: 'static>(
13572        &mut self,
13573        ranges: Vec<Range<Anchor>>,
13574        style: HighlightStyle,
13575        cx: &mut Context<Self>,
13576    ) {
13577        self.display_map.update(cx, |map, _| {
13578            map.highlight_text(TypeId::of::<T>(), ranges, style)
13579        });
13580        cx.notify();
13581    }
13582
13583    pub(crate) fn highlight_inlays<T: 'static>(
13584        &mut self,
13585        highlights: Vec<InlayHighlight>,
13586        style: HighlightStyle,
13587        cx: &mut Context<Self>,
13588    ) {
13589        self.display_map.update(cx, |map, _| {
13590            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13591        });
13592        cx.notify();
13593    }
13594
13595    pub fn text_highlights<'a, T: 'static>(
13596        &'a self,
13597        cx: &'a App,
13598    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13599        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13600    }
13601
13602    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13603        let cleared = self
13604            .display_map
13605            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13606        if cleared {
13607            cx.notify();
13608        }
13609    }
13610
13611    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13612        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13613            && self.focus_handle.is_focused(window)
13614    }
13615
13616    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13617        self.show_cursor_when_unfocused = is_enabled;
13618        cx.notify();
13619    }
13620
13621    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13622        self.project
13623            .as_ref()
13624            .map(|project| project.read(cx).lsp_store())
13625    }
13626
13627    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13628        cx.notify();
13629    }
13630
13631    fn on_buffer_event(
13632        &mut self,
13633        multibuffer: &Entity<MultiBuffer>,
13634        event: &multi_buffer::Event,
13635        window: &mut Window,
13636        cx: &mut Context<Self>,
13637    ) {
13638        match event {
13639            multi_buffer::Event::Edited {
13640                singleton_buffer_edited,
13641                edited_buffer: buffer_edited,
13642            } => {
13643                self.scrollbar_marker_state.dirty = true;
13644                self.active_indent_guides_state.dirty = true;
13645                self.refresh_active_diagnostics(cx);
13646                self.refresh_code_actions(window, cx);
13647                if self.has_active_inline_completion() {
13648                    self.update_visible_inline_completion(window, cx);
13649                }
13650                if let Some(buffer) = buffer_edited {
13651                    let buffer_id = buffer.read(cx).remote_id();
13652                    if !self.registered_buffers.contains_key(&buffer_id) {
13653                        if let Some(lsp_store) = self.lsp_store(cx) {
13654                            lsp_store.update(cx, |lsp_store, cx| {
13655                                self.registered_buffers.insert(
13656                                    buffer_id,
13657                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13658                                );
13659                            })
13660                        }
13661                    }
13662                }
13663                cx.emit(EditorEvent::BufferEdited);
13664                cx.emit(SearchEvent::MatchesInvalidated);
13665                if *singleton_buffer_edited {
13666                    if let Some(project) = &self.project {
13667                        let project = project.read(cx);
13668                        #[allow(clippy::mutable_key_type)]
13669                        let languages_affected = multibuffer
13670                            .read(cx)
13671                            .all_buffers()
13672                            .into_iter()
13673                            .filter_map(|buffer| {
13674                                let buffer = buffer.read(cx);
13675                                let language = buffer.language()?;
13676                                if project.is_local()
13677                                    && project
13678                                        .language_servers_for_local_buffer(buffer, cx)
13679                                        .count()
13680                                        == 0
13681                                {
13682                                    None
13683                                } else {
13684                                    Some(language)
13685                                }
13686                            })
13687                            .cloned()
13688                            .collect::<HashSet<_>>();
13689                        if !languages_affected.is_empty() {
13690                            self.refresh_inlay_hints(
13691                                InlayHintRefreshReason::BufferEdited(languages_affected),
13692                                cx,
13693                            );
13694                        }
13695                    }
13696                }
13697
13698                let Some(project) = &self.project else { return };
13699                let (telemetry, is_via_ssh) = {
13700                    let project = project.read(cx);
13701                    let telemetry = project.client().telemetry().clone();
13702                    let is_via_ssh = project.is_via_ssh();
13703                    (telemetry, is_via_ssh)
13704                };
13705                refresh_linked_ranges(self, window, cx);
13706                telemetry.log_edit_event("editor", is_via_ssh);
13707            }
13708            multi_buffer::Event::ExcerptsAdded {
13709                buffer,
13710                predecessor,
13711                excerpts,
13712            } => {
13713                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13714                let buffer_id = buffer.read(cx).remote_id();
13715                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13716                    if let Some(project) = &self.project {
13717                        get_uncommitted_changes_for_buffer(
13718                            project,
13719                            [buffer.clone()],
13720                            self.buffer.clone(),
13721                            cx,
13722                        );
13723                    }
13724                }
13725                cx.emit(EditorEvent::ExcerptsAdded {
13726                    buffer: buffer.clone(),
13727                    predecessor: *predecessor,
13728                    excerpts: excerpts.clone(),
13729                });
13730                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13731            }
13732            multi_buffer::Event::ExcerptsRemoved { ids } => {
13733                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13734                let buffer = self.buffer.read(cx);
13735                self.registered_buffers
13736                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13737                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13738            }
13739            multi_buffer::Event::ExcerptsEdited { ids } => {
13740                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13741            }
13742            multi_buffer::Event::ExcerptsExpanded { ids } => {
13743                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13744                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13745            }
13746            multi_buffer::Event::Reparsed(buffer_id) => {
13747                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13748
13749                cx.emit(EditorEvent::Reparsed(*buffer_id));
13750            }
13751            multi_buffer::Event::DiffHunksToggled => {
13752                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13753            }
13754            multi_buffer::Event::LanguageChanged(buffer_id) => {
13755                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13756                cx.emit(EditorEvent::Reparsed(*buffer_id));
13757                cx.notify();
13758            }
13759            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13760            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13761            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13762                cx.emit(EditorEvent::TitleChanged)
13763            }
13764            // multi_buffer::Event::DiffBaseChanged => {
13765            //     self.scrollbar_marker_state.dirty = true;
13766            //     cx.emit(EditorEvent::DiffBaseChanged);
13767            //     cx.notify();
13768            // }
13769            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13770            multi_buffer::Event::DiagnosticsUpdated => {
13771                self.refresh_active_diagnostics(cx);
13772                self.scrollbar_marker_state.dirty = true;
13773                cx.notify();
13774            }
13775            _ => {}
13776        };
13777    }
13778
13779    fn on_display_map_changed(
13780        &mut self,
13781        _: Entity<DisplayMap>,
13782        _: &mut Window,
13783        cx: &mut Context<Self>,
13784    ) {
13785        cx.notify();
13786    }
13787
13788    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13789        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13790        self.refresh_inline_completion(true, false, window, cx);
13791        self.refresh_inlay_hints(
13792            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13793                self.selections.newest_anchor().head(),
13794                &self.buffer.read(cx).snapshot(cx),
13795                cx,
13796            )),
13797            cx,
13798        );
13799
13800        let old_cursor_shape = self.cursor_shape;
13801
13802        {
13803            let editor_settings = EditorSettings::get_global(cx);
13804            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13805            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13806            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13807        }
13808
13809        if old_cursor_shape != self.cursor_shape {
13810            cx.emit(EditorEvent::CursorShapeChanged);
13811        }
13812
13813        let project_settings = ProjectSettings::get_global(cx);
13814        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13815
13816        if self.mode == EditorMode::Full {
13817            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13818            if self.git_blame_inline_enabled != inline_blame_enabled {
13819                self.toggle_git_blame_inline_internal(false, window, cx);
13820            }
13821        }
13822
13823        cx.notify();
13824    }
13825
13826    pub fn set_searchable(&mut self, searchable: bool) {
13827        self.searchable = searchable;
13828    }
13829
13830    pub fn searchable(&self) -> bool {
13831        self.searchable
13832    }
13833
13834    fn open_proposed_changes_editor(
13835        &mut self,
13836        _: &OpenProposedChangesEditor,
13837        window: &mut Window,
13838        cx: &mut Context<Self>,
13839    ) {
13840        let Some(workspace) = self.workspace() else {
13841            cx.propagate();
13842            return;
13843        };
13844
13845        let selections = self.selections.all::<usize>(cx);
13846        let multi_buffer = self.buffer.read(cx);
13847        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13848        let mut new_selections_by_buffer = HashMap::default();
13849        for selection in selections {
13850            for (buffer, range, _) in
13851                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13852            {
13853                let mut range = range.to_point(buffer);
13854                range.start.column = 0;
13855                range.end.column = buffer.line_len(range.end.row);
13856                new_selections_by_buffer
13857                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13858                    .or_insert(Vec::new())
13859                    .push(range)
13860            }
13861        }
13862
13863        let proposed_changes_buffers = new_selections_by_buffer
13864            .into_iter()
13865            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13866            .collect::<Vec<_>>();
13867        let proposed_changes_editor = cx.new(|cx| {
13868            ProposedChangesEditor::new(
13869                "Proposed changes",
13870                proposed_changes_buffers,
13871                self.project.clone(),
13872                window,
13873                cx,
13874            )
13875        });
13876
13877        window.defer(cx, move |window, cx| {
13878            workspace.update(cx, |workspace, cx| {
13879                workspace.active_pane().update(cx, |pane, cx| {
13880                    pane.add_item(
13881                        Box::new(proposed_changes_editor),
13882                        true,
13883                        true,
13884                        None,
13885                        window,
13886                        cx,
13887                    );
13888                });
13889            });
13890        });
13891    }
13892
13893    pub fn open_excerpts_in_split(
13894        &mut self,
13895        _: &OpenExcerptsSplit,
13896        window: &mut Window,
13897        cx: &mut Context<Self>,
13898    ) {
13899        self.open_excerpts_common(None, true, window, cx)
13900    }
13901
13902    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13903        self.open_excerpts_common(None, false, window, cx)
13904    }
13905
13906    fn open_excerpts_common(
13907        &mut self,
13908        jump_data: Option<JumpData>,
13909        split: bool,
13910        window: &mut Window,
13911        cx: &mut Context<Self>,
13912    ) {
13913        let Some(workspace) = self.workspace() else {
13914            cx.propagate();
13915            return;
13916        };
13917
13918        if self.buffer.read(cx).is_singleton() {
13919            cx.propagate();
13920            return;
13921        }
13922
13923        let mut new_selections_by_buffer = HashMap::default();
13924        match &jump_data {
13925            Some(JumpData::MultiBufferPoint {
13926                excerpt_id,
13927                position,
13928                anchor,
13929                line_offset_from_top,
13930            }) => {
13931                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13932                if let Some(buffer) = multi_buffer_snapshot
13933                    .buffer_id_for_excerpt(*excerpt_id)
13934                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13935                {
13936                    let buffer_snapshot = buffer.read(cx).snapshot();
13937                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13938                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13939                    } else {
13940                        buffer_snapshot.clip_point(*position, Bias::Left)
13941                    };
13942                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13943                    new_selections_by_buffer.insert(
13944                        buffer,
13945                        (
13946                            vec![jump_to_offset..jump_to_offset],
13947                            Some(*line_offset_from_top),
13948                        ),
13949                    );
13950                }
13951            }
13952            Some(JumpData::MultiBufferRow {
13953                row,
13954                line_offset_from_top,
13955            }) => {
13956                let point = MultiBufferPoint::new(row.0, 0);
13957                if let Some((buffer, buffer_point, _)) =
13958                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13959                {
13960                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13961                    new_selections_by_buffer
13962                        .entry(buffer)
13963                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13964                        .0
13965                        .push(buffer_offset..buffer_offset)
13966                }
13967            }
13968            None => {
13969                let selections = self.selections.all::<usize>(cx);
13970                let multi_buffer = self.buffer.read(cx);
13971                for selection in selections {
13972                    for (buffer, mut range, _) in multi_buffer
13973                        .snapshot(cx)
13974                        .range_to_buffer_ranges(selection.range())
13975                    {
13976                        // When editing branch buffers, jump to the corresponding location
13977                        // in their base buffer.
13978                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13979                        let buffer = buffer_handle.read(cx);
13980                        if let Some(base_buffer) = buffer.base_buffer() {
13981                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13982                            buffer_handle = base_buffer;
13983                        }
13984
13985                        if selection.reversed {
13986                            mem::swap(&mut range.start, &mut range.end);
13987                        }
13988                        new_selections_by_buffer
13989                            .entry(buffer_handle)
13990                            .or_insert((Vec::new(), None))
13991                            .0
13992                            .push(range)
13993                    }
13994                }
13995            }
13996        }
13997
13998        if new_selections_by_buffer.is_empty() {
13999            return;
14000        }
14001
14002        // We defer the pane interaction because we ourselves are a workspace item
14003        // and activating a new item causes the pane to call a method on us reentrantly,
14004        // which panics if we're on the stack.
14005        window.defer(cx, move |window, cx| {
14006            workspace.update(cx, |workspace, cx| {
14007                let pane = if split {
14008                    workspace.adjacent_pane(window, cx)
14009                } else {
14010                    workspace.active_pane().clone()
14011                };
14012
14013                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14014                    let editor = buffer
14015                        .read(cx)
14016                        .file()
14017                        .is_none()
14018                        .then(|| {
14019                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14020                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14021                            // Instead, we try to activate the existing editor in the pane first.
14022                            let (editor, pane_item_index) =
14023                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14024                                    let editor = item.downcast::<Editor>()?;
14025                                    let singleton_buffer =
14026                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14027                                    if singleton_buffer == buffer {
14028                                        Some((editor, i))
14029                                    } else {
14030                                        None
14031                                    }
14032                                })?;
14033                            pane.update(cx, |pane, cx| {
14034                                pane.activate_item(pane_item_index, true, true, window, cx)
14035                            });
14036                            Some(editor)
14037                        })
14038                        .flatten()
14039                        .unwrap_or_else(|| {
14040                            workspace.open_project_item::<Self>(
14041                                pane.clone(),
14042                                buffer,
14043                                true,
14044                                true,
14045                                window,
14046                                cx,
14047                            )
14048                        });
14049
14050                    editor.update(cx, |editor, cx| {
14051                        let autoscroll = match scroll_offset {
14052                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14053                            None => Autoscroll::newest(),
14054                        };
14055                        let nav_history = editor.nav_history.take();
14056                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14057                            s.select_ranges(ranges);
14058                        });
14059                        editor.nav_history = nav_history;
14060                    });
14061                }
14062            })
14063        });
14064    }
14065
14066    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14067        let snapshot = self.buffer.read(cx).read(cx);
14068        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14069        Some(
14070            ranges
14071                .iter()
14072                .map(move |range| {
14073                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14074                })
14075                .collect(),
14076        )
14077    }
14078
14079    fn selection_replacement_ranges(
14080        &self,
14081        range: Range<OffsetUtf16>,
14082        cx: &mut App,
14083    ) -> Vec<Range<OffsetUtf16>> {
14084        let selections = self.selections.all::<OffsetUtf16>(cx);
14085        let newest_selection = selections
14086            .iter()
14087            .max_by_key(|selection| selection.id)
14088            .unwrap();
14089        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14090        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14091        let snapshot = self.buffer.read(cx).read(cx);
14092        selections
14093            .into_iter()
14094            .map(|mut selection| {
14095                selection.start.0 =
14096                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14097                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14098                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14099                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14100            })
14101            .collect()
14102    }
14103
14104    fn report_editor_event(
14105        &self,
14106        event_type: &'static str,
14107        file_extension: Option<String>,
14108        cx: &App,
14109    ) {
14110        if cfg!(any(test, feature = "test-support")) {
14111            return;
14112        }
14113
14114        let Some(project) = &self.project else { return };
14115
14116        // If None, we are in a file without an extension
14117        let file = self
14118            .buffer
14119            .read(cx)
14120            .as_singleton()
14121            .and_then(|b| b.read(cx).file());
14122        let file_extension = file_extension.or(file
14123            .as_ref()
14124            .and_then(|file| Path::new(file.file_name(cx)).extension())
14125            .and_then(|e| e.to_str())
14126            .map(|a| a.to_string()));
14127
14128        let vim_mode = cx
14129            .global::<SettingsStore>()
14130            .raw_user_settings()
14131            .get("vim_mode")
14132            == Some(&serde_json::Value::Bool(true));
14133
14134        let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14135        let copilot_enabled = edit_predictions_provider
14136            == language::language_settings::InlineCompletionProvider::Copilot;
14137        let copilot_enabled_for_language = self
14138            .buffer
14139            .read(cx)
14140            .settings_at(0, cx)
14141            .show_inline_completions;
14142
14143        let project = project.read(cx);
14144        telemetry::event!(
14145            event_type,
14146            file_extension,
14147            vim_mode,
14148            copilot_enabled,
14149            copilot_enabled_for_language,
14150            edit_predictions_provider,
14151            is_via_ssh = project.is_via_ssh(),
14152        );
14153    }
14154
14155    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14156    /// with each line being an array of {text, highlight} objects.
14157    fn copy_highlight_json(
14158        &mut self,
14159        _: &CopyHighlightJson,
14160        window: &mut Window,
14161        cx: &mut Context<Self>,
14162    ) {
14163        #[derive(Serialize)]
14164        struct Chunk<'a> {
14165            text: String,
14166            highlight: Option<&'a str>,
14167        }
14168
14169        let snapshot = self.buffer.read(cx).snapshot(cx);
14170        let range = self
14171            .selected_text_range(false, window, cx)
14172            .and_then(|selection| {
14173                if selection.range.is_empty() {
14174                    None
14175                } else {
14176                    Some(selection.range)
14177                }
14178            })
14179            .unwrap_or_else(|| 0..snapshot.len());
14180
14181        let chunks = snapshot.chunks(range, true);
14182        let mut lines = Vec::new();
14183        let mut line: VecDeque<Chunk> = VecDeque::new();
14184
14185        let Some(style) = self.style.as_ref() else {
14186            return;
14187        };
14188
14189        for chunk in chunks {
14190            let highlight = chunk
14191                .syntax_highlight_id
14192                .and_then(|id| id.name(&style.syntax));
14193            let mut chunk_lines = chunk.text.split('\n').peekable();
14194            while let Some(text) = chunk_lines.next() {
14195                let mut merged_with_last_token = false;
14196                if let Some(last_token) = line.back_mut() {
14197                    if last_token.highlight == highlight {
14198                        last_token.text.push_str(text);
14199                        merged_with_last_token = true;
14200                    }
14201                }
14202
14203                if !merged_with_last_token {
14204                    line.push_back(Chunk {
14205                        text: text.into(),
14206                        highlight,
14207                    });
14208                }
14209
14210                if chunk_lines.peek().is_some() {
14211                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14212                        line.pop_front();
14213                    }
14214                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14215                        line.pop_back();
14216                    }
14217
14218                    lines.push(mem::take(&mut line));
14219                }
14220            }
14221        }
14222
14223        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14224            return;
14225        };
14226        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14227    }
14228
14229    pub fn open_context_menu(
14230        &mut self,
14231        _: &OpenContextMenu,
14232        window: &mut Window,
14233        cx: &mut Context<Self>,
14234    ) {
14235        self.request_autoscroll(Autoscroll::newest(), cx);
14236        let position = self.selections.newest_display(cx).start;
14237        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14238    }
14239
14240    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14241        &self.inlay_hint_cache
14242    }
14243
14244    pub fn replay_insert_event(
14245        &mut self,
14246        text: &str,
14247        relative_utf16_range: Option<Range<isize>>,
14248        window: &mut Window,
14249        cx: &mut Context<Self>,
14250    ) {
14251        if !self.input_enabled {
14252            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14253            return;
14254        }
14255        if let Some(relative_utf16_range) = relative_utf16_range {
14256            let selections = self.selections.all::<OffsetUtf16>(cx);
14257            self.change_selections(None, window, cx, |s| {
14258                let new_ranges = selections.into_iter().map(|range| {
14259                    let start = OffsetUtf16(
14260                        range
14261                            .head()
14262                            .0
14263                            .saturating_add_signed(relative_utf16_range.start),
14264                    );
14265                    let end = OffsetUtf16(
14266                        range
14267                            .head()
14268                            .0
14269                            .saturating_add_signed(relative_utf16_range.end),
14270                    );
14271                    start..end
14272                });
14273                s.select_ranges(new_ranges);
14274            });
14275        }
14276
14277        self.handle_input(text, window, cx);
14278    }
14279
14280    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14281        let Some(provider) = self.semantics_provider.as_ref() else {
14282            return false;
14283        };
14284
14285        let mut supports = false;
14286        self.buffer().read(cx).for_each_buffer(|buffer| {
14287            supports |= provider.supports_inlay_hints(buffer, cx);
14288        });
14289        supports
14290    }
14291    pub fn is_focused(&self, window: &mut Window) -> bool {
14292        self.focus_handle.is_focused(window)
14293    }
14294
14295    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14296        cx.emit(EditorEvent::Focused);
14297
14298        if let Some(descendant) = self
14299            .last_focused_descendant
14300            .take()
14301            .and_then(|descendant| descendant.upgrade())
14302        {
14303            window.focus(&descendant);
14304        } else {
14305            if let Some(blame) = self.blame.as_ref() {
14306                blame.update(cx, GitBlame::focus)
14307            }
14308
14309            self.blink_manager.update(cx, BlinkManager::enable);
14310            self.show_cursor_names(window, cx);
14311            self.buffer.update(cx, |buffer, cx| {
14312                buffer.finalize_last_transaction(cx);
14313                if self.leader_peer_id.is_none() {
14314                    buffer.set_active_selections(
14315                        &self.selections.disjoint_anchors(),
14316                        self.selections.line_mode,
14317                        self.cursor_shape,
14318                        cx,
14319                    );
14320                }
14321            });
14322        }
14323    }
14324
14325    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14326        cx.emit(EditorEvent::FocusedIn)
14327    }
14328
14329    fn handle_focus_out(
14330        &mut self,
14331        event: FocusOutEvent,
14332        _window: &mut Window,
14333        _cx: &mut Context<Self>,
14334    ) {
14335        if event.blurred != self.focus_handle {
14336            self.last_focused_descendant = Some(event.blurred);
14337        }
14338    }
14339
14340    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14341        self.blink_manager.update(cx, BlinkManager::disable);
14342        self.buffer
14343            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14344
14345        if let Some(blame) = self.blame.as_ref() {
14346            blame.update(cx, GitBlame::blur)
14347        }
14348        if !self.hover_state.focused(window, cx) {
14349            hide_hover(self, cx);
14350        }
14351
14352        self.hide_context_menu(window, cx);
14353        cx.emit(EditorEvent::Blurred);
14354        cx.notify();
14355    }
14356
14357    pub fn register_action<A: Action>(
14358        &mut self,
14359        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14360    ) -> Subscription {
14361        let id = self.next_editor_action_id.post_inc();
14362        let listener = Arc::new(listener);
14363        self.editor_actions.borrow_mut().insert(
14364            id,
14365            Box::new(move |window, _| {
14366                let listener = listener.clone();
14367                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14368                    let action = action.downcast_ref().unwrap();
14369                    if phase == DispatchPhase::Bubble {
14370                        listener(action, window, cx)
14371                    }
14372                })
14373            }),
14374        );
14375
14376        let editor_actions = self.editor_actions.clone();
14377        Subscription::new(move || {
14378            editor_actions.borrow_mut().remove(&id);
14379        })
14380    }
14381
14382    pub fn file_header_size(&self) -> u32 {
14383        FILE_HEADER_HEIGHT
14384    }
14385
14386    pub fn revert(
14387        &mut self,
14388        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14389        window: &mut Window,
14390        cx: &mut Context<Self>,
14391    ) {
14392        self.buffer().update(cx, |multi_buffer, cx| {
14393            for (buffer_id, changes) in revert_changes {
14394                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14395                    buffer.update(cx, |buffer, cx| {
14396                        buffer.edit(
14397                            changes.into_iter().map(|(range, text)| {
14398                                (range, text.to_string().map(Arc::<str>::from))
14399                            }),
14400                            None,
14401                            cx,
14402                        );
14403                    });
14404                }
14405            }
14406        });
14407        self.change_selections(None, window, cx, |selections| selections.refresh());
14408    }
14409
14410    pub fn to_pixel_point(
14411        &self,
14412        source: multi_buffer::Anchor,
14413        editor_snapshot: &EditorSnapshot,
14414        window: &mut Window,
14415    ) -> Option<gpui::Point<Pixels>> {
14416        let source_point = source.to_display_point(editor_snapshot);
14417        self.display_to_pixel_point(source_point, editor_snapshot, window)
14418    }
14419
14420    pub fn display_to_pixel_point(
14421        &self,
14422        source: DisplayPoint,
14423        editor_snapshot: &EditorSnapshot,
14424        window: &mut Window,
14425    ) -> Option<gpui::Point<Pixels>> {
14426        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14427        let text_layout_details = self.text_layout_details(window);
14428        let scroll_top = text_layout_details
14429            .scroll_anchor
14430            .scroll_position(editor_snapshot)
14431            .y;
14432
14433        if source.row().as_f32() < scroll_top.floor() {
14434            return None;
14435        }
14436        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14437        let source_y = line_height * (source.row().as_f32() - scroll_top);
14438        Some(gpui::Point::new(source_x, source_y))
14439    }
14440
14441    pub fn has_active_completions_menu(&self) -> bool {
14442        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14443            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14444        })
14445    }
14446
14447    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14448        self.addons
14449            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14450    }
14451
14452    pub fn unregister_addon<T: Addon>(&mut self) {
14453        self.addons.remove(&std::any::TypeId::of::<T>());
14454    }
14455
14456    pub fn addon<T: Addon>(&self) -> Option<&T> {
14457        let type_id = std::any::TypeId::of::<T>();
14458        self.addons
14459            .get(&type_id)
14460            .and_then(|item| item.to_any().downcast_ref::<T>())
14461    }
14462
14463    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14464        let text_layout_details = self.text_layout_details(window);
14465        let style = &text_layout_details.editor_style;
14466        let font_id = window.text_system().resolve_font(&style.text.font());
14467        let font_size = style.text.font_size.to_pixels(window.rem_size());
14468        let line_height = style.text.line_height_in_pixels(window.rem_size());
14469        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14470
14471        gpui::Size::new(em_width, line_height)
14472    }
14473}
14474
14475fn get_uncommitted_changes_for_buffer(
14476    project: &Entity<Project>,
14477    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14478    buffer: Entity<MultiBuffer>,
14479    cx: &mut App,
14480) {
14481    let mut tasks = Vec::new();
14482    project.update(cx, |project, cx| {
14483        for buffer in buffers {
14484            tasks.push(project.open_uncommitted_changes(buffer.clone(), cx))
14485        }
14486    });
14487    cx.spawn(|mut cx| async move {
14488        let change_sets = futures::future::join_all(tasks).await;
14489        buffer
14490            .update(&mut cx, |buffer, cx| {
14491                for change_set in change_sets.into_iter().flatten() {
14492                    buffer.add_change_set(change_set, cx);
14493                }
14494            })
14495            .ok();
14496    })
14497    .detach();
14498}
14499
14500fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14501    let tab_size = tab_size.get() as usize;
14502    let mut width = offset;
14503
14504    for ch in text.chars() {
14505        width += if ch == '\t' {
14506            tab_size - (width % tab_size)
14507        } else {
14508            1
14509        };
14510    }
14511
14512    width - offset
14513}
14514
14515#[cfg(test)]
14516mod tests {
14517    use super::*;
14518
14519    #[test]
14520    fn test_string_size_with_expanded_tabs() {
14521        let nz = |val| NonZeroU32::new(val).unwrap();
14522        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14523        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14524        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14525        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14526        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14527        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14528        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14529        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14530    }
14531}
14532
14533/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14534struct WordBreakingTokenizer<'a> {
14535    input: &'a str,
14536}
14537
14538impl<'a> WordBreakingTokenizer<'a> {
14539    fn new(input: &'a str) -> Self {
14540        Self { input }
14541    }
14542}
14543
14544fn is_char_ideographic(ch: char) -> bool {
14545    use unicode_script::Script::*;
14546    use unicode_script::UnicodeScript;
14547    matches!(ch.script(), Han | Tangut | Yi)
14548}
14549
14550fn is_grapheme_ideographic(text: &str) -> bool {
14551    text.chars().any(is_char_ideographic)
14552}
14553
14554fn is_grapheme_whitespace(text: &str) -> bool {
14555    text.chars().any(|x| x.is_whitespace())
14556}
14557
14558fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14559    text.chars().next().map_or(false, |ch| {
14560        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14561    })
14562}
14563
14564#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14565struct WordBreakToken<'a> {
14566    token: &'a str,
14567    grapheme_len: usize,
14568    is_whitespace: bool,
14569}
14570
14571impl<'a> Iterator for WordBreakingTokenizer<'a> {
14572    /// Yields a span, the count of graphemes in the token, and whether it was
14573    /// whitespace. Note that it also breaks at word boundaries.
14574    type Item = WordBreakToken<'a>;
14575
14576    fn next(&mut self) -> Option<Self::Item> {
14577        use unicode_segmentation::UnicodeSegmentation;
14578        if self.input.is_empty() {
14579            return None;
14580        }
14581
14582        let mut iter = self.input.graphemes(true).peekable();
14583        let mut offset = 0;
14584        let mut graphemes = 0;
14585        if let Some(first_grapheme) = iter.next() {
14586            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14587            offset += first_grapheme.len();
14588            graphemes += 1;
14589            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14590                if let Some(grapheme) = iter.peek().copied() {
14591                    if should_stay_with_preceding_ideograph(grapheme) {
14592                        offset += grapheme.len();
14593                        graphemes += 1;
14594                    }
14595                }
14596            } else {
14597                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14598                let mut next_word_bound = words.peek().copied();
14599                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14600                    next_word_bound = words.next();
14601                }
14602                while let Some(grapheme) = iter.peek().copied() {
14603                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14604                        break;
14605                    };
14606                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14607                        break;
14608                    };
14609                    offset += grapheme.len();
14610                    graphemes += 1;
14611                    iter.next();
14612                }
14613            }
14614            let token = &self.input[..offset];
14615            self.input = &self.input[offset..];
14616            if is_whitespace {
14617                Some(WordBreakToken {
14618                    token: " ",
14619                    grapheme_len: 1,
14620                    is_whitespace: true,
14621                })
14622            } else {
14623                Some(WordBreakToken {
14624                    token,
14625                    grapheme_len: graphemes,
14626                    is_whitespace: false,
14627                })
14628            }
14629        } else {
14630            None
14631        }
14632    }
14633}
14634
14635#[test]
14636fn test_word_breaking_tokenizer() {
14637    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14638        ("", &[]),
14639        ("  ", &[(" ", 1, true)]),
14640        ("Ʒ", &[("Ʒ", 1, false)]),
14641        ("Ǽ", &[("Ǽ", 1, false)]),
14642        ("", &[("", 1, false)]),
14643        ("⋑⋑", &[("⋑⋑", 2, false)]),
14644        (
14645            "原理,进而",
14646            &[
14647                ("", 1, false),
14648                ("理,", 2, false),
14649                ("", 1, false),
14650                ("", 1, false),
14651            ],
14652        ),
14653        (
14654            "hello world",
14655            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14656        ),
14657        (
14658            "hello, world",
14659            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14660        ),
14661        (
14662            "  hello world",
14663            &[
14664                (" ", 1, true),
14665                ("hello", 5, false),
14666                (" ", 1, true),
14667                ("world", 5, false),
14668            ],
14669        ),
14670        (
14671            "这是什么 \n 钢笔",
14672            &[
14673                ("", 1, false),
14674                ("", 1, false),
14675                ("", 1, false),
14676                ("", 1, false),
14677                (" ", 1, true),
14678                ("", 1, false),
14679                ("", 1, false),
14680            ],
14681        ),
14682        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14683    ];
14684
14685    for (input, result) in tests {
14686        assert_eq!(
14687            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14688            result
14689                .iter()
14690                .copied()
14691                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14692                    token,
14693                    grapheme_len,
14694                    is_whitespace,
14695                })
14696                .collect::<Vec<_>>()
14697        );
14698    }
14699}
14700
14701fn wrap_with_prefix(
14702    line_prefix: String,
14703    unwrapped_text: String,
14704    wrap_column: usize,
14705    tab_size: NonZeroU32,
14706) -> String {
14707    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14708    let mut wrapped_text = String::new();
14709    let mut current_line = line_prefix.clone();
14710
14711    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14712    let mut current_line_len = line_prefix_len;
14713    for WordBreakToken {
14714        token,
14715        grapheme_len,
14716        is_whitespace,
14717    } in tokenizer
14718    {
14719        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14720            wrapped_text.push_str(current_line.trim_end());
14721            wrapped_text.push('\n');
14722            current_line.truncate(line_prefix.len());
14723            current_line_len = line_prefix_len;
14724            if !is_whitespace {
14725                current_line.push_str(token);
14726                current_line_len += grapheme_len;
14727            }
14728        } else if !is_whitespace {
14729            current_line.push_str(token);
14730            current_line_len += grapheme_len;
14731        } else if current_line_len != line_prefix_len {
14732            current_line.push(' ');
14733            current_line_len += 1;
14734        }
14735    }
14736
14737    if !current_line.is_empty() {
14738        wrapped_text.push_str(&current_line);
14739    }
14740    wrapped_text
14741}
14742
14743#[test]
14744fn test_wrap_with_prefix() {
14745    assert_eq!(
14746        wrap_with_prefix(
14747            "# ".to_string(),
14748            "abcdefg".to_string(),
14749            4,
14750            NonZeroU32::new(4).unwrap()
14751        ),
14752        "# abcdefg"
14753    );
14754    assert_eq!(
14755        wrap_with_prefix(
14756            "".to_string(),
14757            "\thello world".to_string(),
14758            8,
14759            NonZeroU32::new(4).unwrap()
14760        ),
14761        "hello\nworld"
14762    );
14763    assert_eq!(
14764        wrap_with_prefix(
14765            "// ".to_string(),
14766            "xx \nyy zz aa bb cc".to_string(),
14767            12,
14768            NonZeroU32::new(4).unwrap()
14769        ),
14770        "// xx yy zz\n// aa bb cc"
14771    );
14772    assert_eq!(
14773        wrap_with_prefix(
14774            String::new(),
14775            "这是什么 \n 钢笔".to_string(),
14776            3,
14777            NonZeroU32::new(4).unwrap()
14778        ),
14779        "这是什\n么 钢\n"
14780    );
14781}
14782
14783pub trait CollaborationHub {
14784    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14785    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14786    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14787}
14788
14789impl CollaborationHub for Entity<Project> {
14790    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14791        self.read(cx).collaborators()
14792    }
14793
14794    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14795        self.read(cx).user_store().read(cx).participant_indices()
14796    }
14797
14798    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14799        let this = self.read(cx);
14800        let user_ids = this.collaborators().values().map(|c| c.user_id);
14801        this.user_store().read_with(cx, |user_store, cx| {
14802            user_store.participant_names(user_ids, cx)
14803        })
14804    }
14805}
14806
14807pub trait SemanticsProvider {
14808    fn hover(
14809        &self,
14810        buffer: &Entity<Buffer>,
14811        position: text::Anchor,
14812        cx: &mut App,
14813    ) -> Option<Task<Vec<project::Hover>>>;
14814
14815    fn inlay_hints(
14816        &self,
14817        buffer_handle: Entity<Buffer>,
14818        range: Range<text::Anchor>,
14819        cx: &mut App,
14820    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14821
14822    fn resolve_inlay_hint(
14823        &self,
14824        hint: InlayHint,
14825        buffer_handle: Entity<Buffer>,
14826        server_id: LanguageServerId,
14827        cx: &mut App,
14828    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14829
14830    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14831
14832    fn document_highlights(
14833        &self,
14834        buffer: &Entity<Buffer>,
14835        position: text::Anchor,
14836        cx: &mut App,
14837    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14838
14839    fn definitions(
14840        &self,
14841        buffer: &Entity<Buffer>,
14842        position: text::Anchor,
14843        kind: GotoDefinitionKind,
14844        cx: &mut App,
14845    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14846
14847    fn range_for_rename(
14848        &self,
14849        buffer: &Entity<Buffer>,
14850        position: text::Anchor,
14851        cx: &mut App,
14852    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14853
14854    fn perform_rename(
14855        &self,
14856        buffer: &Entity<Buffer>,
14857        position: text::Anchor,
14858        new_name: String,
14859        cx: &mut App,
14860    ) -> Option<Task<Result<ProjectTransaction>>>;
14861}
14862
14863pub trait CompletionProvider {
14864    fn completions(
14865        &self,
14866        buffer: &Entity<Buffer>,
14867        buffer_position: text::Anchor,
14868        trigger: CompletionContext,
14869        window: &mut Window,
14870        cx: &mut Context<Editor>,
14871    ) -> Task<Result<Vec<Completion>>>;
14872
14873    fn resolve_completions(
14874        &self,
14875        buffer: Entity<Buffer>,
14876        completion_indices: Vec<usize>,
14877        completions: Rc<RefCell<Box<[Completion]>>>,
14878        cx: &mut Context<Editor>,
14879    ) -> Task<Result<bool>>;
14880
14881    fn apply_additional_edits_for_completion(
14882        &self,
14883        _buffer: Entity<Buffer>,
14884        _completions: Rc<RefCell<Box<[Completion]>>>,
14885        _completion_index: usize,
14886        _push_to_history: bool,
14887        _cx: &mut Context<Editor>,
14888    ) -> Task<Result<Option<language::Transaction>>> {
14889        Task::ready(Ok(None))
14890    }
14891
14892    fn is_completion_trigger(
14893        &self,
14894        buffer: &Entity<Buffer>,
14895        position: language::Anchor,
14896        text: &str,
14897        trigger_in_words: bool,
14898        cx: &mut Context<Editor>,
14899    ) -> bool;
14900
14901    fn sort_completions(&self) -> bool {
14902        true
14903    }
14904}
14905
14906pub trait CodeActionProvider {
14907    fn id(&self) -> Arc<str>;
14908
14909    fn code_actions(
14910        &self,
14911        buffer: &Entity<Buffer>,
14912        range: Range<text::Anchor>,
14913        window: &mut Window,
14914        cx: &mut App,
14915    ) -> Task<Result<Vec<CodeAction>>>;
14916
14917    fn apply_code_action(
14918        &self,
14919        buffer_handle: Entity<Buffer>,
14920        action: CodeAction,
14921        excerpt_id: ExcerptId,
14922        push_to_history: bool,
14923        window: &mut Window,
14924        cx: &mut App,
14925    ) -> Task<Result<ProjectTransaction>>;
14926}
14927
14928impl CodeActionProvider for Entity<Project> {
14929    fn id(&self) -> Arc<str> {
14930        "project".into()
14931    }
14932
14933    fn code_actions(
14934        &self,
14935        buffer: &Entity<Buffer>,
14936        range: Range<text::Anchor>,
14937        _window: &mut Window,
14938        cx: &mut App,
14939    ) -> Task<Result<Vec<CodeAction>>> {
14940        self.update(cx, |project, cx| {
14941            project.code_actions(buffer, range, None, cx)
14942        })
14943    }
14944
14945    fn apply_code_action(
14946        &self,
14947        buffer_handle: Entity<Buffer>,
14948        action: CodeAction,
14949        _excerpt_id: ExcerptId,
14950        push_to_history: bool,
14951        _window: &mut Window,
14952        cx: &mut App,
14953    ) -> Task<Result<ProjectTransaction>> {
14954        self.update(cx, |project, cx| {
14955            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14956        })
14957    }
14958}
14959
14960fn snippet_completions(
14961    project: &Project,
14962    buffer: &Entity<Buffer>,
14963    buffer_position: text::Anchor,
14964    cx: &mut App,
14965) -> Task<Result<Vec<Completion>>> {
14966    let language = buffer.read(cx).language_at(buffer_position);
14967    let language_name = language.as_ref().map(|language| language.lsp_id());
14968    let snippet_store = project.snippets().read(cx);
14969    let snippets = snippet_store.snippets_for(language_name, cx);
14970
14971    if snippets.is_empty() {
14972        return Task::ready(Ok(vec![]));
14973    }
14974    let snapshot = buffer.read(cx).text_snapshot();
14975    let chars: String = snapshot
14976        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14977        .collect();
14978
14979    let scope = language.map(|language| language.default_scope());
14980    let executor = cx.background_executor().clone();
14981
14982    cx.background_executor().spawn(async move {
14983        let classifier = CharClassifier::new(scope).for_completion(true);
14984        let mut last_word = chars
14985            .chars()
14986            .take_while(|c| classifier.is_word(*c))
14987            .collect::<String>();
14988        last_word = last_word.chars().rev().collect();
14989
14990        if last_word.is_empty() {
14991            return Ok(vec![]);
14992        }
14993
14994        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14995        let to_lsp = |point: &text::Anchor| {
14996            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14997            point_to_lsp(end)
14998        };
14999        let lsp_end = to_lsp(&buffer_position);
15000
15001        let candidates = snippets
15002            .iter()
15003            .enumerate()
15004            .flat_map(|(ix, snippet)| {
15005                snippet
15006                    .prefix
15007                    .iter()
15008                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15009            })
15010            .collect::<Vec<StringMatchCandidate>>();
15011
15012        let mut matches = fuzzy::match_strings(
15013            &candidates,
15014            &last_word,
15015            last_word.chars().any(|c| c.is_uppercase()),
15016            100,
15017            &Default::default(),
15018            executor,
15019        )
15020        .await;
15021
15022        // Remove all candidates where the query's start does not match the start of any word in the candidate
15023        if let Some(query_start) = last_word.chars().next() {
15024            matches.retain(|string_match| {
15025                split_words(&string_match.string).any(|word| {
15026                    // Check that the first codepoint of the word as lowercase matches the first
15027                    // codepoint of the query as lowercase
15028                    word.chars()
15029                        .flat_map(|codepoint| codepoint.to_lowercase())
15030                        .zip(query_start.to_lowercase())
15031                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15032                })
15033            });
15034        }
15035
15036        let matched_strings = matches
15037            .into_iter()
15038            .map(|m| m.string)
15039            .collect::<HashSet<_>>();
15040
15041        let result: Vec<Completion> = snippets
15042            .into_iter()
15043            .filter_map(|snippet| {
15044                let matching_prefix = snippet
15045                    .prefix
15046                    .iter()
15047                    .find(|prefix| matched_strings.contains(*prefix))?;
15048                let start = as_offset - last_word.len();
15049                let start = snapshot.anchor_before(start);
15050                let range = start..buffer_position;
15051                let lsp_start = to_lsp(&start);
15052                let lsp_range = lsp::Range {
15053                    start: lsp_start,
15054                    end: lsp_end,
15055                };
15056                Some(Completion {
15057                    old_range: range,
15058                    new_text: snippet.body.clone(),
15059                    resolved: false,
15060                    label: CodeLabel {
15061                        text: matching_prefix.clone(),
15062                        runs: vec![],
15063                        filter_range: 0..matching_prefix.len(),
15064                    },
15065                    server_id: LanguageServerId(usize::MAX),
15066                    documentation: snippet
15067                        .description
15068                        .clone()
15069                        .map(CompletionDocumentation::SingleLine),
15070                    lsp_completion: lsp::CompletionItem {
15071                        label: snippet.prefix.first().unwrap().clone(),
15072                        kind: Some(CompletionItemKind::SNIPPET),
15073                        label_details: snippet.description.as_ref().map(|description| {
15074                            lsp::CompletionItemLabelDetails {
15075                                detail: Some(description.clone()),
15076                                description: None,
15077                            }
15078                        }),
15079                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15080                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15081                            lsp::InsertReplaceEdit {
15082                                new_text: snippet.body.clone(),
15083                                insert: lsp_range,
15084                                replace: lsp_range,
15085                            },
15086                        )),
15087                        filter_text: Some(snippet.body.clone()),
15088                        sort_text: Some(char::MAX.to_string()),
15089                        ..Default::default()
15090                    },
15091                    confirm: None,
15092                })
15093            })
15094            .collect();
15095
15096        Ok(result)
15097    })
15098}
15099
15100impl CompletionProvider for Entity<Project> {
15101    fn completions(
15102        &self,
15103        buffer: &Entity<Buffer>,
15104        buffer_position: text::Anchor,
15105        options: CompletionContext,
15106        _window: &mut Window,
15107        cx: &mut Context<Editor>,
15108    ) -> Task<Result<Vec<Completion>>> {
15109        self.update(cx, |project, cx| {
15110            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15111            let project_completions = project.completions(buffer, buffer_position, options, cx);
15112            cx.background_executor().spawn(async move {
15113                let mut completions = project_completions.await?;
15114                let snippets_completions = snippets.await?;
15115                completions.extend(snippets_completions);
15116                Ok(completions)
15117            })
15118        })
15119    }
15120
15121    fn resolve_completions(
15122        &self,
15123        buffer: Entity<Buffer>,
15124        completion_indices: Vec<usize>,
15125        completions: Rc<RefCell<Box<[Completion]>>>,
15126        cx: &mut Context<Editor>,
15127    ) -> Task<Result<bool>> {
15128        self.update(cx, |project, cx| {
15129            project.lsp_store().update(cx, |lsp_store, cx| {
15130                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15131            })
15132        })
15133    }
15134
15135    fn apply_additional_edits_for_completion(
15136        &self,
15137        buffer: Entity<Buffer>,
15138        completions: Rc<RefCell<Box<[Completion]>>>,
15139        completion_index: usize,
15140        push_to_history: bool,
15141        cx: &mut Context<Editor>,
15142    ) -> Task<Result<Option<language::Transaction>>> {
15143        self.update(cx, |project, cx| {
15144            project.lsp_store().update(cx, |lsp_store, cx| {
15145                lsp_store.apply_additional_edits_for_completion(
15146                    buffer,
15147                    completions,
15148                    completion_index,
15149                    push_to_history,
15150                    cx,
15151                )
15152            })
15153        })
15154    }
15155
15156    fn is_completion_trigger(
15157        &self,
15158        buffer: &Entity<Buffer>,
15159        position: language::Anchor,
15160        text: &str,
15161        trigger_in_words: bool,
15162        cx: &mut Context<Editor>,
15163    ) -> bool {
15164        let mut chars = text.chars();
15165        let char = if let Some(char) = chars.next() {
15166            char
15167        } else {
15168            return false;
15169        };
15170        if chars.next().is_some() {
15171            return false;
15172        }
15173
15174        let buffer = buffer.read(cx);
15175        let snapshot = buffer.snapshot();
15176        if !snapshot.settings_at(position, cx).show_completions_on_input {
15177            return false;
15178        }
15179        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15180        if trigger_in_words && classifier.is_word(char) {
15181            return true;
15182        }
15183
15184        buffer.completion_triggers().contains(text)
15185    }
15186}
15187
15188impl SemanticsProvider for Entity<Project> {
15189    fn hover(
15190        &self,
15191        buffer: &Entity<Buffer>,
15192        position: text::Anchor,
15193        cx: &mut App,
15194    ) -> Option<Task<Vec<project::Hover>>> {
15195        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15196    }
15197
15198    fn document_highlights(
15199        &self,
15200        buffer: &Entity<Buffer>,
15201        position: text::Anchor,
15202        cx: &mut App,
15203    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15204        Some(self.update(cx, |project, cx| {
15205            project.document_highlights(buffer, position, cx)
15206        }))
15207    }
15208
15209    fn definitions(
15210        &self,
15211        buffer: &Entity<Buffer>,
15212        position: text::Anchor,
15213        kind: GotoDefinitionKind,
15214        cx: &mut App,
15215    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15216        Some(self.update(cx, |project, cx| match kind {
15217            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15218            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15219            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15220            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15221        }))
15222    }
15223
15224    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15225        // TODO: make this work for remote projects
15226        self.read(cx)
15227            .language_servers_for_local_buffer(buffer.read(cx), cx)
15228            .any(
15229                |(_, server)| match server.capabilities().inlay_hint_provider {
15230                    Some(lsp::OneOf::Left(enabled)) => enabled,
15231                    Some(lsp::OneOf::Right(_)) => true,
15232                    None => false,
15233                },
15234            )
15235    }
15236
15237    fn inlay_hints(
15238        &self,
15239        buffer_handle: Entity<Buffer>,
15240        range: Range<text::Anchor>,
15241        cx: &mut App,
15242    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15243        Some(self.update(cx, |project, cx| {
15244            project.inlay_hints(buffer_handle, range, cx)
15245        }))
15246    }
15247
15248    fn resolve_inlay_hint(
15249        &self,
15250        hint: InlayHint,
15251        buffer_handle: Entity<Buffer>,
15252        server_id: LanguageServerId,
15253        cx: &mut App,
15254    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15255        Some(self.update(cx, |project, cx| {
15256            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15257        }))
15258    }
15259
15260    fn range_for_rename(
15261        &self,
15262        buffer: &Entity<Buffer>,
15263        position: text::Anchor,
15264        cx: &mut App,
15265    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15266        Some(self.update(cx, |project, cx| {
15267            let buffer = buffer.clone();
15268            let task = project.prepare_rename(buffer.clone(), position, cx);
15269            cx.spawn(|_, mut cx| async move {
15270                Ok(match task.await? {
15271                    PrepareRenameResponse::Success(range) => Some(range),
15272                    PrepareRenameResponse::InvalidPosition => None,
15273                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15274                        // Fallback on using TreeSitter info to determine identifier range
15275                        buffer.update(&mut cx, |buffer, _| {
15276                            let snapshot = buffer.snapshot();
15277                            let (range, kind) = snapshot.surrounding_word(position);
15278                            if kind != Some(CharKind::Word) {
15279                                return None;
15280                            }
15281                            Some(
15282                                snapshot.anchor_before(range.start)
15283                                    ..snapshot.anchor_after(range.end),
15284                            )
15285                        })?
15286                    }
15287                })
15288            })
15289        }))
15290    }
15291
15292    fn perform_rename(
15293        &self,
15294        buffer: &Entity<Buffer>,
15295        position: text::Anchor,
15296        new_name: String,
15297        cx: &mut App,
15298    ) -> Option<Task<Result<ProjectTransaction>>> {
15299        Some(self.update(cx, |project, cx| {
15300            project.perform_rename(buffer.clone(), position, new_name, cx)
15301        }))
15302    }
15303}
15304
15305fn inlay_hint_settings(
15306    location: Anchor,
15307    snapshot: &MultiBufferSnapshot,
15308    cx: &mut Context<Editor>,
15309) -> InlayHintSettings {
15310    let file = snapshot.file_at(location);
15311    let language = snapshot.language_at(location).map(|l| l.name());
15312    language_settings(language, file, cx).inlay_hints
15313}
15314
15315fn consume_contiguous_rows(
15316    contiguous_row_selections: &mut Vec<Selection<Point>>,
15317    selection: &Selection<Point>,
15318    display_map: &DisplaySnapshot,
15319    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15320) -> (MultiBufferRow, MultiBufferRow) {
15321    contiguous_row_selections.push(selection.clone());
15322    let start_row = MultiBufferRow(selection.start.row);
15323    let mut end_row = ending_row(selection, display_map);
15324
15325    while let Some(next_selection) = selections.peek() {
15326        if next_selection.start.row <= end_row.0 {
15327            end_row = ending_row(next_selection, display_map);
15328            contiguous_row_selections.push(selections.next().unwrap().clone());
15329        } else {
15330            break;
15331        }
15332    }
15333    (start_row, end_row)
15334}
15335
15336fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15337    if next_selection.end.column > 0 || next_selection.is_empty() {
15338        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15339    } else {
15340        MultiBufferRow(next_selection.end.row)
15341    }
15342}
15343
15344impl EditorSnapshot {
15345    pub fn remote_selections_in_range<'a>(
15346        &'a self,
15347        range: &'a Range<Anchor>,
15348        collaboration_hub: &dyn CollaborationHub,
15349        cx: &'a App,
15350    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15351        let participant_names = collaboration_hub.user_names(cx);
15352        let participant_indices = collaboration_hub.user_participant_indices(cx);
15353        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15354        let collaborators_by_replica_id = collaborators_by_peer_id
15355            .iter()
15356            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15357            .collect::<HashMap<_, _>>();
15358        self.buffer_snapshot
15359            .selections_in_range(range, false)
15360            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15361                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15362                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15363                let user_name = participant_names.get(&collaborator.user_id).cloned();
15364                Some(RemoteSelection {
15365                    replica_id,
15366                    selection,
15367                    cursor_shape,
15368                    line_mode,
15369                    participant_index,
15370                    peer_id: collaborator.peer_id,
15371                    user_name,
15372                })
15373            })
15374    }
15375
15376    pub fn hunks_for_ranges(
15377        &self,
15378        ranges: impl Iterator<Item = Range<Point>>,
15379    ) -> Vec<MultiBufferDiffHunk> {
15380        let mut hunks = Vec::new();
15381        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15382            HashMap::default();
15383        for query_range in ranges {
15384            let query_rows =
15385                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15386            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15387                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15388            ) {
15389                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15390                // when the caret is just above or just below the deleted hunk.
15391                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15392                let related_to_selection = if allow_adjacent {
15393                    hunk.row_range.overlaps(&query_rows)
15394                        || hunk.row_range.start == query_rows.end
15395                        || hunk.row_range.end == query_rows.start
15396                } else {
15397                    hunk.row_range.overlaps(&query_rows)
15398                };
15399                if related_to_selection {
15400                    if !processed_buffer_rows
15401                        .entry(hunk.buffer_id)
15402                        .or_default()
15403                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15404                    {
15405                        continue;
15406                    }
15407                    hunks.push(hunk);
15408                }
15409            }
15410        }
15411
15412        hunks
15413    }
15414
15415    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15416        self.display_snapshot.buffer_snapshot.language_at(position)
15417    }
15418
15419    pub fn is_focused(&self) -> bool {
15420        self.is_focused
15421    }
15422
15423    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15424        self.placeholder_text.as_ref()
15425    }
15426
15427    pub fn scroll_position(&self) -> gpui::Point<f32> {
15428        self.scroll_anchor.scroll_position(&self.display_snapshot)
15429    }
15430
15431    fn gutter_dimensions(
15432        &self,
15433        font_id: FontId,
15434        font_size: Pixels,
15435        max_line_number_width: Pixels,
15436        cx: &App,
15437    ) -> Option<GutterDimensions> {
15438        if !self.show_gutter {
15439            return None;
15440        }
15441
15442        let descent = cx.text_system().descent(font_id, font_size);
15443        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15444        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15445
15446        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15447            matches!(
15448                ProjectSettings::get_global(cx).git.git_gutter,
15449                Some(GitGutterSetting::TrackedFiles)
15450            )
15451        });
15452        let gutter_settings = EditorSettings::get_global(cx).gutter;
15453        let show_line_numbers = self
15454            .show_line_numbers
15455            .unwrap_or(gutter_settings.line_numbers);
15456        let line_gutter_width = if show_line_numbers {
15457            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15458            let min_width_for_number_on_gutter = em_advance * 4.0;
15459            max_line_number_width.max(min_width_for_number_on_gutter)
15460        } else {
15461            0.0.into()
15462        };
15463
15464        let show_code_actions = self
15465            .show_code_actions
15466            .unwrap_or(gutter_settings.code_actions);
15467
15468        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15469
15470        let git_blame_entries_width =
15471            self.git_blame_gutter_max_author_length
15472                .map(|max_author_length| {
15473                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15474
15475                    /// The number of characters to dedicate to gaps and margins.
15476                    const SPACING_WIDTH: usize = 4;
15477
15478                    let max_char_count = max_author_length
15479                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15480                        + ::git::SHORT_SHA_LENGTH
15481                        + MAX_RELATIVE_TIMESTAMP.len()
15482                        + SPACING_WIDTH;
15483
15484                    em_advance * max_char_count
15485                });
15486
15487        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15488        left_padding += if show_code_actions || show_runnables {
15489            em_width * 3.0
15490        } else if show_git_gutter && show_line_numbers {
15491            em_width * 2.0
15492        } else if show_git_gutter || show_line_numbers {
15493            em_width
15494        } else {
15495            px(0.)
15496        };
15497
15498        let right_padding = if gutter_settings.folds && show_line_numbers {
15499            em_width * 4.0
15500        } else if gutter_settings.folds {
15501            em_width * 3.0
15502        } else if show_line_numbers {
15503            em_width
15504        } else {
15505            px(0.)
15506        };
15507
15508        Some(GutterDimensions {
15509            left_padding,
15510            right_padding,
15511            width: line_gutter_width + left_padding + right_padding,
15512            margin: -descent,
15513            git_blame_entries_width,
15514        })
15515    }
15516
15517    pub fn render_crease_toggle(
15518        &self,
15519        buffer_row: MultiBufferRow,
15520        row_contains_cursor: bool,
15521        editor: Entity<Editor>,
15522        window: &mut Window,
15523        cx: &mut App,
15524    ) -> Option<AnyElement> {
15525        let folded = self.is_line_folded(buffer_row);
15526        let mut is_foldable = false;
15527
15528        if let Some(crease) = self
15529            .crease_snapshot
15530            .query_row(buffer_row, &self.buffer_snapshot)
15531        {
15532            is_foldable = true;
15533            match crease {
15534                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15535                    if let Some(render_toggle) = render_toggle {
15536                        let toggle_callback =
15537                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15538                                if folded {
15539                                    editor.update(cx, |editor, cx| {
15540                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15541                                    });
15542                                } else {
15543                                    editor.update(cx, |editor, cx| {
15544                                        editor.unfold_at(
15545                                            &crate::UnfoldAt { buffer_row },
15546                                            window,
15547                                            cx,
15548                                        )
15549                                    });
15550                                }
15551                            });
15552                        return Some((render_toggle)(
15553                            buffer_row,
15554                            folded,
15555                            toggle_callback,
15556                            window,
15557                            cx,
15558                        ));
15559                    }
15560                }
15561            }
15562        }
15563
15564        is_foldable |= self.starts_indent(buffer_row);
15565
15566        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15567            Some(
15568                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15569                    .toggle_state(folded)
15570                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15571                        if folded {
15572                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15573                        } else {
15574                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15575                        }
15576                    }))
15577                    .into_any_element(),
15578            )
15579        } else {
15580            None
15581        }
15582    }
15583
15584    pub fn render_crease_trailer(
15585        &self,
15586        buffer_row: MultiBufferRow,
15587        window: &mut Window,
15588        cx: &mut App,
15589    ) -> Option<AnyElement> {
15590        let folded = self.is_line_folded(buffer_row);
15591        if let Crease::Inline { render_trailer, .. } = self
15592            .crease_snapshot
15593            .query_row(buffer_row, &self.buffer_snapshot)?
15594        {
15595            let render_trailer = render_trailer.as_ref()?;
15596            Some(render_trailer(buffer_row, folded, window, cx))
15597        } else {
15598            None
15599        }
15600    }
15601}
15602
15603impl Deref for EditorSnapshot {
15604    type Target = DisplaySnapshot;
15605
15606    fn deref(&self) -> &Self::Target {
15607        &self.display_snapshot
15608    }
15609}
15610
15611#[derive(Clone, Debug, PartialEq, Eq)]
15612pub enum EditorEvent {
15613    InputIgnored {
15614        text: Arc<str>,
15615    },
15616    InputHandled {
15617        utf16_range_to_replace: Option<Range<isize>>,
15618        text: Arc<str>,
15619    },
15620    ExcerptsAdded {
15621        buffer: Entity<Buffer>,
15622        predecessor: ExcerptId,
15623        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15624    },
15625    ExcerptsRemoved {
15626        ids: Vec<ExcerptId>,
15627    },
15628    BufferFoldToggled {
15629        ids: Vec<ExcerptId>,
15630        folded: bool,
15631    },
15632    ExcerptsEdited {
15633        ids: Vec<ExcerptId>,
15634    },
15635    ExcerptsExpanded {
15636        ids: Vec<ExcerptId>,
15637    },
15638    BufferEdited,
15639    Edited {
15640        transaction_id: clock::Lamport,
15641    },
15642    Reparsed(BufferId),
15643    Focused,
15644    FocusedIn,
15645    Blurred,
15646    DirtyChanged,
15647    Saved,
15648    TitleChanged,
15649    DiffBaseChanged,
15650    SelectionsChanged {
15651        local: bool,
15652    },
15653    ScrollPositionChanged {
15654        local: bool,
15655        autoscroll: bool,
15656    },
15657    Closed,
15658    TransactionUndone {
15659        transaction_id: clock::Lamport,
15660    },
15661    TransactionBegun {
15662        transaction_id: clock::Lamport,
15663    },
15664    Reloaded,
15665    CursorShapeChanged,
15666}
15667
15668impl EventEmitter<EditorEvent> for Editor {}
15669
15670impl Focusable for Editor {
15671    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15672        self.focus_handle.clone()
15673    }
15674}
15675
15676impl Render for Editor {
15677    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15678        let settings = ThemeSettings::get_global(cx);
15679
15680        let mut text_style = match self.mode {
15681            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15682                color: cx.theme().colors().editor_foreground,
15683                font_family: settings.ui_font.family.clone(),
15684                font_features: settings.ui_font.features.clone(),
15685                font_fallbacks: settings.ui_font.fallbacks.clone(),
15686                font_size: rems(0.875).into(),
15687                font_weight: settings.ui_font.weight,
15688                line_height: relative(settings.buffer_line_height.value()),
15689                ..Default::default()
15690            },
15691            EditorMode::Full => TextStyle {
15692                color: cx.theme().colors().editor_foreground,
15693                font_family: settings.buffer_font.family.clone(),
15694                font_features: settings.buffer_font.features.clone(),
15695                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15696                font_size: settings.buffer_font_size().into(),
15697                font_weight: settings.buffer_font.weight,
15698                line_height: relative(settings.buffer_line_height.value()),
15699                ..Default::default()
15700            },
15701        };
15702        if let Some(text_style_refinement) = &self.text_style_refinement {
15703            text_style.refine(text_style_refinement)
15704        }
15705
15706        let background = match self.mode {
15707            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15708            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15709            EditorMode::Full => cx.theme().colors().editor_background,
15710        };
15711
15712        EditorElement::new(
15713            &cx.entity(),
15714            EditorStyle {
15715                background,
15716                local_player: cx.theme().players().local(),
15717                text: text_style,
15718                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15719                syntax: cx.theme().syntax().clone(),
15720                status: cx.theme().status().clone(),
15721                inlay_hints_style: make_inlay_hints_style(cx),
15722                inline_completion_styles: make_suggestion_styles(cx),
15723                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15724            },
15725        )
15726    }
15727}
15728
15729impl EntityInputHandler for Editor {
15730    fn text_for_range(
15731        &mut self,
15732        range_utf16: Range<usize>,
15733        adjusted_range: &mut Option<Range<usize>>,
15734        _: &mut Window,
15735        cx: &mut Context<Self>,
15736    ) -> Option<String> {
15737        let snapshot = self.buffer.read(cx).read(cx);
15738        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15739        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15740        if (start.0..end.0) != range_utf16 {
15741            adjusted_range.replace(start.0..end.0);
15742        }
15743        Some(snapshot.text_for_range(start..end).collect())
15744    }
15745
15746    fn selected_text_range(
15747        &mut self,
15748        ignore_disabled_input: bool,
15749        _: &mut Window,
15750        cx: &mut Context<Self>,
15751    ) -> Option<UTF16Selection> {
15752        // Prevent the IME menu from appearing when holding down an alphabetic key
15753        // while input is disabled.
15754        if !ignore_disabled_input && !self.input_enabled {
15755            return None;
15756        }
15757
15758        let selection = self.selections.newest::<OffsetUtf16>(cx);
15759        let range = selection.range();
15760
15761        Some(UTF16Selection {
15762            range: range.start.0..range.end.0,
15763            reversed: selection.reversed,
15764        })
15765    }
15766
15767    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15768        let snapshot = self.buffer.read(cx).read(cx);
15769        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15770        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15771    }
15772
15773    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15774        self.clear_highlights::<InputComposition>(cx);
15775        self.ime_transaction.take();
15776    }
15777
15778    fn replace_text_in_range(
15779        &mut self,
15780        range_utf16: Option<Range<usize>>,
15781        text: &str,
15782        window: &mut Window,
15783        cx: &mut Context<Self>,
15784    ) {
15785        if !self.input_enabled {
15786            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15787            return;
15788        }
15789
15790        self.transact(window, cx, |this, window, cx| {
15791            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15792                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15793                Some(this.selection_replacement_ranges(range_utf16, cx))
15794            } else {
15795                this.marked_text_ranges(cx)
15796            };
15797
15798            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15799                let newest_selection_id = this.selections.newest_anchor().id;
15800                this.selections
15801                    .all::<OffsetUtf16>(cx)
15802                    .iter()
15803                    .zip(ranges_to_replace.iter())
15804                    .find_map(|(selection, range)| {
15805                        if selection.id == newest_selection_id {
15806                            Some(
15807                                (range.start.0 as isize - selection.head().0 as isize)
15808                                    ..(range.end.0 as isize - selection.head().0 as isize),
15809                            )
15810                        } else {
15811                            None
15812                        }
15813                    })
15814            });
15815
15816            cx.emit(EditorEvent::InputHandled {
15817                utf16_range_to_replace: range_to_replace,
15818                text: text.into(),
15819            });
15820
15821            if let Some(new_selected_ranges) = new_selected_ranges {
15822                this.change_selections(None, window, cx, |selections| {
15823                    selections.select_ranges(new_selected_ranges)
15824                });
15825                this.backspace(&Default::default(), window, cx);
15826            }
15827
15828            this.handle_input(text, window, cx);
15829        });
15830
15831        if let Some(transaction) = self.ime_transaction {
15832            self.buffer.update(cx, |buffer, cx| {
15833                buffer.group_until_transaction(transaction, cx);
15834            });
15835        }
15836
15837        self.unmark_text(window, cx);
15838    }
15839
15840    fn replace_and_mark_text_in_range(
15841        &mut self,
15842        range_utf16: Option<Range<usize>>,
15843        text: &str,
15844        new_selected_range_utf16: Option<Range<usize>>,
15845        window: &mut Window,
15846        cx: &mut Context<Self>,
15847    ) {
15848        if !self.input_enabled {
15849            return;
15850        }
15851
15852        let transaction = self.transact(window, cx, |this, window, cx| {
15853            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15854                let snapshot = this.buffer.read(cx).read(cx);
15855                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15856                    for marked_range in &mut marked_ranges {
15857                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15858                        marked_range.start.0 += relative_range_utf16.start;
15859                        marked_range.start =
15860                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15861                        marked_range.end =
15862                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15863                    }
15864                }
15865                Some(marked_ranges)
15866            } else if let Some(range_utf16) = range_utf16 {
15867                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15868                Some(this.selection_replacement_ranges(range_utf16, cx))
15869            } else {
15870                None
15871            };
15872
15873            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15874                let newest_selection_id = this.selections.newest_anchor().id;
15875                this.selections
15876                    .all::<OffsetUtf16>(cx)
15877                    .iter()
15878                    .zip(ranges_to_replace.iter())
15879                    .find_map(|(selection, range)| {
15880                        if selection.id == newest_selection_id {
15881                            Some(
15882                                (range.start.0 as isize - selection.head().0 as isize)
15883                                    ..(range.end.0 as isize - selection.head().0 as isize),
15884                            )
15885                        } else {
15886                            None
15887                        }
15888                    })
15889            });
15890
15891            cx.emit(EditorEvent::InputHandled {
15892                utf16_range_to_replace: range_to_replace,
15893                text: text.into(),
15894            });
15895
15896            if let Some(ranges) = ranges_to_replace {
15897                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15898            }
15899
15900            let marked_ranges = {
15901                let snapshot = this.buffer.read(cx).read(cx);
15902                this.selections
15903                    .disjoint_anchors()
15904                    .iter()
15905                    .map(|selection| {
15906                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15907                    })
15908                    .collect::<Vec<_>>()
15909            };
15910
15911            if text.is_empty() {
15912                this.unmark_text(window, cx);
15913            } else {
15914                this.highlight_text::<InputComposition>(
15915                    marked_ranges.clone(),
15916                    HighlightStyle {
15917                        underline: Some(UnderlineStyle {
15918                            thickness: px(1.),
15919                            color: None,
15920                            wavy: false,
15921                        }),
15922                        ..Default::default()
15923                    },
15924                    cx,
15925                );
15926            }
15927
15928            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15929            let use_autoclose = this.use_autoclose;
15930            let use_auto_surround = this.use_auto_surround;
15931            this.set_use_autoclose(false);
15932            this.set_use_auto_surround(false);
15933            this.handle_input(text, window, cx);
15934            this.set_use_autoclose(use_autoclose);
15935            this.set_use_auto_surround(use_auto_surround);
15936
15937            if let Some(new_selected_range) = new_selected_range_utf16 {
15938                let snapshot = this.buffer.read(cx).read(cx);
15939                let new_selected_ranges = marked_ranges
15940                    .into_iter()
15941                    .map(|marked_range| {
15942                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15943                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15944                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15945                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15946                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15947                    })
15948                    .collect::<Vec<_>>();
15949
15950                drop(snapshot);
15951                this.change_selections(None, window, cx, |selections| {
15952                    selections.select_ranges(new_selected_ranges)
15953                });
15954            }
15955        });
15956
15957        self.ime_transaction = self.ime_transaction.or(transaction);
15958        if let Some(transaction) = self.ime_transaction {
15959            self.buffer.update(cx, |buffer, cx| {
15960                buffer.group_until_transaction(transaction, cx);
15961            });
15962        }
15963
15964        if self.text_highlights::<InputComposition>(cx).is_none() {
15965            self.ime_transaction.take();
15966        }
15967    }
15968
15969    fn bounds_for_range(
15970        &mut self,
15971        range_utf16: Range<usize>,
15972        element_bounds: gpui::Bounds<Pixels>,
15973        window: &mut Window,
15974        cx: &mut Context<Self>,
15975    ) -> Option<gpui::Bounds<Pixels>> {
15976        let text_layout_details = self.text_layout_details(window);
15977        let gpui::Size {
15978            width: em_width,
15979            height: line_height,
15980        } = self.character_size(window);
15981
15982        let snapshot = self.snapshot(window, cx);
15983        let scroll_position = snapshot.scroll_position();
15984        let scroll_left = scroll_position.x * em_width;
15985
15986        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15987        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15988            + self.gutter_dimensions.width
15989            + self.gutter_dimensions.margin;
15990        let y = line_height * (start.row().as_f32() - scroll_position.y);
15991
15992        Some(Bounds {
15993            origin: element_bounds.origin + point(x, y),
15994            size: size(em_width, line_height),
15995        })
15996    }
15997
15998    fn character_index_for_point(
15999        &mut self,
16000        point: gpui::Point<Pixels>,
16001        _window: &mut Window,
16002        _cx: &mut Context<Self>,
16003    ) -> Option<usize> {
16004        let position_map = self.last_position_map.as_ref()?;
16005        if !position_map.text_hitbox.contains(&point) {
16006            return None;
16007        }
16008        let display_point = position_map.point_for_position(point).previous_valid;
16009        let anchor = position_map
16010            .snapshot
16011            .display_point_to_anchor(display_point, Bias::Left);
16012        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16013        Some(utf16_offset.0)
16014    }
16015}
16016
16017trait SelectionExt {
16018    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16019    fn spanned_rows(
16020        &self,
16021        include_end_if_at_line_start: bool,
16022        map: &DisplaySnapshot,
16023    ) -> Range<MultiBufferRow>;
16024}
16025
16026impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16027    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16028        let start = self
16029            .start
16030            .to_point(&map.buffer_snapshot)
16031            .to_display_point(map);
16032        let end = self
16033            .end
16034            .to_point(&map.buffer_snapshot)
16035            .to_display_point(map);
16036        if self.reversed {
16037            end..start
16038        } else {
16039            start..end
16040        }
16041    }
16042
16043    fn spanned_rows(
16044        &self,
16045        include_end_if_at_line_start: bool,
16046        map: &DisplaySnapshot,
16047    ) -> Range<MultiBufferRow> {
16048        let start = self.start.to_point(&map.buffer_snapshot);
16049        let mut end = self.end.to_point(&map.buffer_snapshot);
16050        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16051            end.row -= 1;
16052        }
16053
16054        let buffer_start = map.prev_line_boundary(start).0;
16055        let buffer_end = map.next_line_boundary(end).0;
16056        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16057    }
16058}
16059
16060impl<T: InvalidationRegion> InvalidationStack<T> {
16061    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16062    where
16063        S: Clone + ToOffset,
16064    {
16065        while let Some(region) = self.last() {
16066            let all_selections_inside_invalidation_ranges =
16067                if selections.len() == region.ranges().len() {
16068                    selections
16069                        .iter()
16070                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16071                        .all(|(selection, invalidation_range)| {
16072                            let head = selection.head().to_offset(buffer);
16073                            invalidation_range.start <= head && invalidation_range.end >= head
16074                        })
16075                } else {
16076                    false
16077                };
16078
16079            if all_selections_inside_invalidation_ranges {
16080                break;
16081            } else {
16082                self.pop();
16083            }
16084        }
16085    }
16086}
16087
16088impl<T> Default for InvalidationStack<T> {
16089    fn default() -> Self {
16090        Self(Default::default())
16091    }
16092}
16093
16094impl<T> Deref for InvalidationStack<T> {
16095    type Target = Vec<T>;
16096
16097    fn deref(&self) -> &Self::Target {
16098        &self.0
16099    }
16100}
16101
16102impl<T> DerefMut for InvalidationStack<T> {
16103    fn deref_mut(&mut self) -> &mut Self::Target {
16104        &mut self.0
16105    }
16106}
16107
16108impl InvalidationRegion for SnippetState {
16109    fn ranges(&self) -> &[Range<Anchor>] {
16110        &self.ranges[self.active_index]
16111    }
16112}
16113
16114pub fn diagnostic_block_renderer(
16115    diagnostic: Diagnostic,
16116    max_message_rows: Option<u8>,
16117    allow_closing: bool,
16118    _is_valid: bool,
16119) -> RenderBlock {
16120    let (text_without_backticks, code_ranges) =
16121        highlight_diagnostic_message(&diagnostic, max_message_rows);
16122
16123    Arc::new(move |cx: &mut BlockContext| {
16124        let group_id: SharedString = cx.block_id.to_string().into();
16125
16126        let mut text_style = cx.window.text_style().clone();
16127        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16128        let theme_settings = ThemeSettings::get_global(cx);
16129        text_style.font_family = theme_settings.buffer_font.family.clone();
16130        text_style.font_style = theme_settings.buffer_font.style;
16131        text_style.font_features = theme_settings.buffer_font.features.clone();
16132        text_style.font_weight = theme_settings.buffer_font.weight;
16133
16134        let multi_line_diagnostic = diagnostic.message.contains('\n');
16135
16136        let buttons = |diagnostic: &Diagnostic| {
16137            if multi_line_diagnostic {
16138                v_flex()
16139            } else {
16140                h_flex()
16141            }
16142            .when(allow_closing, |div| {
16143                div.children(diagnostic.is_primary.then(|| {
16144                    IconButton::new("close-block", IconName::XCircle)
16145                        .icon_color(Color::Muted)
16146                        .size(ButtonSize::Compact)
16147                        .style(ButtonStyle::Transparent)
16148                        .visible_on_hover(group_id.clone())
16149                        .on_click(move |_click, window, cx| {
16150                            window.dispatch_action(Box::new(Cancel), cx)
16151                        })
16152                        .tooltip(|window, cx| {
16153                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16154                        })
16155                }))
16156            })
16157            .child(
16158                IconButton::new("copy-block", IconName::Copy)
16159                    .icon_color(Color::Muted)
16160                    .size(ButtonSize::Compact)
16161                    .style(ButtonStyle::Transparent)
16162                    .visible_on_hover(group_id.clone())
16163                    .on_click({
16164                        let message = diagnostic.message.clone();
16165                        move |_click, _, cx| {
16166                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16167                        }
16168                    })
16169                    .tooltip(Tooltip::text("Copy diagnostic message")),
16170            )
16171        };
16172
16173        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16174            AvailableSpace::min_size(),
16175            cx.window,
16176            cx.app,
16177        );
16178
16179        h_flex()
16180            .id(cx.block_id)
16181            .group(group_id.clone())
16182            .relative()
16183            .size_full()
16184            .block_mouse_down()
16185            .pl(cx.gutter_dimensions.width)
16186            .w(cx.max_width - cx.gutter_dimensions.full_width())
16187            .child(
16188                div()
16189                    .flex()
16190                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16191                    .flex_shrink(),
16192            )
16193            .child(buttons(&diagnostic))
16194            .child(div().flex().flex_shrink_0().child(
16195                StyledText::new(text_without_backticks.clone()).with_highlights(
16196                    &text_style,
16197                    code_ranges.iter().map(|range| {
16198                        (
16199                            range.clone(),
16200                            HighlightStyle {
16201                                font_weight: Some(FontWeight::BOLD),
16202                                ..Default::default()
16203                            },
16204                        )
16205                    }),
16206                ),
16207            ))
16208            .into_any_element()
16209    })
16210}
16211
16212fn inline_completion_edit_text(
16213    current_snapshot: &BufferSnapshot,
16214    edits: &[(Range<Anchor>, String)],
16215    edit_preview: &EditPreview,
16216    include_deletions: bool,
16217    cx: &App,
16218) -> HighlightedText {
16219    let edits = edits
16220        .iter()
16221        .map(|(anchor, text)| {
16222            (
16223                anchor.start.text_anchor..anchor.end.text_anchor,
16224                text.clone(),
16225            )
16226        })
16227        .collect::<Vec<_>>();
16228
16229    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16230}
16231
16232pub fn highlight_diagnostic_message(
16233    diagnostic: &Diagnostic,
16234    mut max_message_rows: Option<u8>,
16235) -> (SharedString, Vec<Range<usize>>) {
16236    let mut text_without_backticks = String::new();
16237    let mut code_ranges = Vec::new();
16238
16239    if let Some(source) = &diagnostic.source {
16240        text_without_backticks.push_str(source);
16241        code_ranges.push(0..source.len());
16242        text_without_backticks.push_str(": ");
16243    }
16244
16245    let mut prev_offset = 0;
16246    let mut in_code_block = false;
16247    let has_row_limit = max_message_rows.is_some();
16248    let mut newline_indices = diagnostic
16249        .message
16250        .match_indices('\n')
16251        .filter(|_| has_row_limit)
16252        .map(|(ix, _)| ix)
16253        .fuse()
16254        .peekable();
16255
16256    for (quote_ix, _) in diagnostic
16257        .message
16258        .match_indices('`')
16259        .chain([(diagnostic.message.len(), "")])
16260    {
16261        let mut first_newline_ix = None;
16262        let mut last_newline_ix = None;
16263        while let Some(newline_ix) = newline_indices.peek() {
16264            if *newline_ix < quote_ix {
16265                if first_newline_ix.is_none() {
16266                    first_newline_ix = Some(*newline_ix);
16267                }
16268                last_newline_ix = Some(*newline_ix);
16269
16270                if let Some(rows_left) = &mut max_message_rows {
16271                    if *rows_left == 0 {
16272                        break;
16273                    } else {
16274                        *rows_left -= 1;
16275                    }
16276                }
16277                let _ = newline_indices.next();
16278            } else {
16279                break;
16280            }
16281        }
16282        let prev_len = text_without_backticks.len();
16283        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16284        text_without_backticks.push_str(new_text);
16285        if in_code_block {
16286            code_ranges.push(prev_len..text_without_backticks.len());
16287        }
16288        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16289        in_code_block = !in_code_block;
16290        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16291            text_without_backticks.push_str("...");
16292            break;
16293        }
16294    }
16295
16296    (text_without_backticks.into(), code_ranges)
16297}
16298
16299fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16300    match severity {
16301        DiagnosticSeverity::ERROR => colors.error,
16302        DiagnosticSeverity::WARNING => colors.warning,
16303        DiagnosticSeverity::INFORMATION => colors.info,
16304        DiagnosticSeverity::HINT => colors.info,
16305        _ => colors.ignored,
16306    }
16307}
16308
16309pub fn styled_runs_for_code_label<'a>(
16310    label: &'a CodeLabel,
16311    syntax_theme: &'a theme::SyntaxTheme,
16312) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16313    let fade_out = HighlightStyle {
16314        fade_out: Some(0.35),
16315        ..Default::default()
16316    };
16317
16318    let mut prev_end = label.filter_range.end;
16319    label
16320        .runs
16321        .iter()
16322        .enumerate()
16323        .flat_map(move |(ix, (range, highlight_id))| {
16324            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16325                style
16326            } else {
16327                return Default::default();
16328            };
16329            let mut muted_style = style;
16330            muted_style.highlight(fade_out);
16331
16332            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16333            if range.start >= label.filter_range.end {
16334                if range.start > prev_end {
16335                    runs.push((prev_end..range.start, fade_out));
16336                }
16337                runs.push((range.clone(), muted_style));
16338            } else if range.end <= label.filter_range.end {
16339                runs.push((range.clone(), style));
16340            } else {
16341                runs.push((range.start..label.filter_range.end, style));
16342                runs.push((label.filter_range.end..range.end, muted_style));
16343            }
16344            prev_end = cmp::max(prev_end, range.end);
16345
16346            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16347                runs.push((prev_end..label.text.len(), fade_out));
16348            }
16349
16350            runs
16351        })
16352}
16353
16354pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16355    let mut prev_index = 0;
16356    let mut prev_codepoint: Option<char> = None;
16357    text.char_indices()
16358        .chain([(text.len(), '\0')])
16359        .filter_map(move |(index, codepoint)| {
16360            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16361            let is_boundary = index == text.len()
16362                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16363                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16364            if is_boundary {
16365                let chunk = &text[prev_index..index];
16366                prev_index = index;
16367                Some(chunk)
16368            } else {
16369                None
16370            }
16371        })
16372}
16373
16374pub trait RangeToAnchorExt: Sized {
16375    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16376
16377    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16378        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16379        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16380    }
16381}
16382
16383impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16384    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16385        let start_offset = self.start.to_offset(snapshot);
16386        let end_offset = self.end.to_offset(snapshot);
16387        if start_offset == end_offset {
16388            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16389        } else {
16390            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16391        }
16392    }
16393}
16394
16395pub trait RowExt {
16396    fn as_f32(&self) -> f32;
16397
16398    fn next_row(&self) -> Self;
16399
16400    fn previous_row(&self) -> Self;
16401
16402    fn minus(&self, other: Self) -> u32;
16403}
16404
16405impl RowExt for DisplayRow {
16406    fn as_f32(&self) -> f32 {
16407        self.0 as f32
16408    }
16409
16410    fn next_row(&self) -> Self {
16411        Self(self.0 + 1)
16412    }
16413
16414    fn previous_row(&self) -> Self {
16415        Self(self.0.saturating_sub(1))
16416    }
16417
16418    fn minus(&self, other: Self) -> u32 {
16419        self.0 - other.0
16420    }
16421}
16422
16423impl RowExt for MultiBufferRow {
16424    fn as_f32(&self) -> f32 {
16425        self.0 as f32
16426    }
16427
16428    fn next_row(&self) -> Self {
16429        Self(self.0 + 1)
16430    }
16431
16432    fn previous_row(&self) -> Self {
16433        Self(self.0.saturating_sub(1))
16434    }
16435
16436    fn minus(&self, other: Self) -> u32 {
16437        self.0 - other.0
16438    }
16439}
16440
16441trait RowRangeExt {
16442    type Row;
16443
16444    fn len(&self) -> usize;
16445
16446    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16447}
16448
16449impl RowRangeExt for Range<MultiBufferRow> {
16450    type Row = MultiBufferRow;
16451
16452    fn len(&self) -> usize {
16453        (self.end.0 - self.start.0) as usize
16454    }
16455
16456    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16457        (self.start.0..self.end.0).map(MultiBufferRow)
16458    }
16459}
16460
16461impl RowRangeExt for Range<DisplayRow> {
16462    type Row = DisplayRow;
16463
16464    fn len(&self) -> usize {
16465        (self.end.0 - self.start.0) as usize
16466    }
16467
16468    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16469        (self.start.0..self.end.0).map(DisplayRow)
16470    }
16471}
16472
16473/// If select range has more than one line, we
16474/// just point the cursor to range.start.
16475fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16476    if range.start.row == range.end.row {
16477        range
16478    } else {
16479        range.start..range.start
16480    }
16481}
16482pub struct KillRing(ClipboardItem);
16483impl Global for KillRing {}
16484
16485const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16486
16487fn all_edits_insertions_or_deletions(
16488    edits: &Vec<(Range<Anchor>, String)>,
16489    snapshot: &MultiBufferSnapshot,
16490) -> bool {
16491    let mut all_insertions = true;
16492    let mut all_deletions = true;
16493
16494    for (range, new_text) in edits.iter() {
16495        let range_is_empty = range.to_offset(&snapshot).is_empty();
16496        let text_is_empty = new_text.is_empty();
16497
16498        if range_is_empty != text_is_empty {
16499            if range_is_empty {
16500                all_deletions = false;
16501            } else {
16502                all_insertions = false;
16503            }
16504        } else {
16505            return false;
16506        }
16507
16508        if !all_insertions && !all_deletions {
16509            return false;
16510        }
16511    }
16512    all_insertions || all_deletions
16513}