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 blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   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::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   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, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   80    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   81    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   82    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   83    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   84    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   85    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   86    WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
  100    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  101    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  128    ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  194pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
  195    "edit_prediction_requires_modifier";
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakEntity<Workspace>>,
  202    cx: &mut App,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(
  247        link_ranges,
  248        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  249            markdown::Link::Web { url } => cx.open_url(url),
  250            markdown::Link::Path { path } => {
  251                if let Some(workspace) = &workspace {
  252                    _ = workspace.update(cx, |workspace, cx| {
  253                        workspace
  254                            .open_abs_path(path.clone(), false, window, cx)
  255                            .detach();
  256                    });
  257                }
  258            }
  259        },
  260    )
  261}
  262
  263#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  264pub enum InlayId {
  265    InlineCompletion(usize),
  266    Hint(usize),
  267}
  268
  269impl InlayId {
  270    fn id(&self) -> usize {
  271        match self {
  272            Self::InlineCompletion(id) => *id,
  273            Self::Hint(id) => *id,
  274        }
  275    }
  276}
  277
  278enum DocumentHighlightRead {}
  279enum DocumentHighlightWrite {}
  280enum InputComposition {}
  281
  282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  283pub enum Navigated {
  284    Yes,
  285    No,
  286}
  287
  288impl Navigated {
  289    pub fn from_bool(yes: bool) -> Navigated {
  290        if yes {
  291            Navigated::Yes
  292        } else {
  293            Navigated::No
  294        }
  295    }
  296}
  297
  298pub fn init_settings(cx: &mut App) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut App) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new(
  310        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314            workspace.register_action(Editor::cancel_language_server_work);
  315        },
  316    )
  317    .detach();
  318
  319    cx.on_action(move |_: &workspace::NewFile, cx| {
  320        let app_state = workspace::AppState::global(cx);
  321        if let Some(app_state) = app_state.upgrade() {
  322            workspace::open_new(
  323                Default::default(),
  324                app_state,
  325                cx,
  326                |workspace, window, cx| {
  327                    Editor::new_file(workspace, &Default::default(), window, cx)
  328                },
  329            )
  330            .detach();
  331        }
  332    });
  333    cx.on_action(move |_: &workspace::NewWindow, cx| {
  334        let app_state = workspace::AppState::global(cx);
  335        if let Some(app_state) = app_state.upgrade() {
  336            workspace::open_new(
  337                Default::default(),
  338                app_state,
  339                cx,
  340                |workspace, window, cx| {
  341                    cx.activate(true);
  342                    Editor::new_file(workspace, &Default::default(), window, cx)
  343                },
  344            )
  345            .detach();
  346        }
  347    });
  348}
  349
  350pub struct SearchWithinRange;
  351
  352trait InvalidationRegion {
  353    fn ranges(&self) -> &[Range<Anchor>];
  354}
  355
  356#[derive(Clone, Debug, PartialEq)]
  357pub enum SelectPhase {
  358    Begin {
  359        position: DisplayPoint,
  360        add: bool,
  361        click_count: usize,
  362    },
  363    BeginColumnar {
  364        position: DisplayPoint,
  365        reset: bool,
  366        goal_column: u32,
  367    },
  368    Extend {
  369        position: DisplayPoint,
  370        click_count: usize,
  371    },
  372    Update {
  373        position: DisplayPoint,
  374        goal_column: u32,
  375        scroll_delta: gpui::Point<f32>,
  376    },
  377    End,
  378}
  379
  380#[derive(Clone, Debug)]
  381pub enum SelectMode {
  382    Character,
  383    Word(Range<Anchor>),
  384    Line(Range<Anchor>),
  385    All,
  386}
  387
  388#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  389pub enum EditorMode {
  390    SingleLine { auto_width: bool },
  391    AutoHeight { max_lines: usize },
  392    Full,
  393}
  394
  395#[derive(Copy, Clone, Debug)]
  396pub enum SoftWrap {
  397    /// Prefer not to wrap at all.
  398    ///
  399    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  400    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  401    GitDiff,
  402    /// Prefer a single line generally, unless an overly long line is encountered.
  403    None,
  404    /// Soft wrap lines that exceed the editor width.
  405    EditorWidth,
  406    /// Soft wrap lines at the preferred line length.
  407    Column(u32),
  408    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  409    Bounded(u32),
  410}
  411
  412#[derive(Clone)]
  413pub struct EditorStyle {
  414    pub background: Hsla,
  415    pub local_player: PlayerColor,
  416    pub text: TextStyle,
  417    pub scrollbar_width: Pixels,
  418    pub syntax: Arc<SyntaxTheme>,
  419    pub status: StatusColors,
  420    pub inlay_hints_style: HighlightStyle,
  421    pub inline_completion_styles: InlineCompletionStyles,
  422    pub unnecessary_code_fade: f32,
  423}
  424
  425impl Default for EditorStyle {
  426    fn default() -> Self {
  427        Self {
  428            background: Hsla::default(),
  429            local_player: PlayerColor::default(),
  430            text: TextStyle::default(),
  431            scrollbar_width: Pixels::default(),
  432            syntax: Default::default(),
  433            // HACK: Status colors don't have a real default.
  434            // We should look into removing the status colors from the editor
  435            // style and retrieve them directly from the theme.
  436            status: StatusColors::dark(),
  437            inlay_hints_style: HighlightStyle::default(),
  438            inline_completion_styles: InlineCompletionStyles {
  439                insertion: HighlightStyle::default(),
  440                whitespace: HighlightStyle::default(),
  441            },
  442            unnecessary_code_fade: Default::default(),
  443        }
  444    }
  445}
  446
  447pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  448    let show_background = language_settings::language_settings(None, None, cx)
  449        .inlay_hints
  450        .show_background;
  451
  452    HighlightStyle {
  453        color: Some(cx.theme().status().hint),
  454        background_color: show_background.then(|| cx.theme().status().hint_background),
  455        ..HighlightStyle::default()
  456    }
  457}
  458
  459pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  460    InlineCompletionStyles {
  461        insertion: HighlightStyle {
  462            color: Some(cx.theme().status().predictive),
  463            ..HighlightStyle::default()
  464        },
  465        whitespace: HighlightStyle {
  466            background_color: Some(cx.theme().status().created_background),
  467            ..HighlightStyle::default()
  468        },
  469    }
  470}
  471
  472type CompletionId = usize;
  473
  474pub(crate) enum EditDisplayMode {
  475    TabAccept,
  476    DiffPopover,
  477    Inline,
  478}
  479
  480enum InlineCompletion {
  481    Edit {
  482        edits: Vec<(Range<Anchor>, String)>,
  483        edit_preview: Option<EditPreview>,
  484        display_mode: EditDisplayMode,
  485        snapshot: BufferSnapshot,
  486    },
  487    Move {
  488        target: Anchor,
  489        snapshot: BufferSnapshot,
  490    },
  491}
  492
  493struct InlineCompletionState {
  494    inlay_ids: Vec<InlayId>,
  495    completion: InlineCompletion,
  496    completion_id: Option<SharedString>,
  497    invalidation_range: Range<Anchor>,
  498}
  499
  500enum EditPredictionSettings {
  501    Disabled,
  502    Enabled {
  503        show_in_menu: bool,
  504        preview_requires_modifier: bool,
  505    },
  506}
  507
  508impl EditPredictionSettings {
  509    pub fn is_enabled(&self) -> bool {
  510        match self {
  511            EditPredictionSettings::Disabled => false,
  512            EditPredictionSettings::Enabled { .. } => true,
  513        }
  514    }
  515}
  516
  517enum InlineCompletionHighlight {}
  518
  519pub enum MenuInlineCompletionsPolicy {
  520    Never,
  521    ByProvider,
  522}
  523
  524pub enum EditPredictionPreview {
  525    /// Modifier is not pressed
  526    Inactive,
  527    /// Modifier pressed
  528    Active {
  529        previous_scroll_position: Option<ScrollAnchor>,
  530    },
  531}
  532
  533#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  534struct EditorActionId(usize);
  535
  536impl EditorActionId {
  537    pub fn post_inc(&mut self) -> Self {
  538        let answer = self.0;
  539
  540        *self = Self(answer + 1);
  541
  542        Self(answer)
  543    }
  544}
  545
  546// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  547// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  548
  549type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  550type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  551
  552#[derive(Default)]
  553struct ScrollbarMarkerState {
  554    scrollbar_size: Size<Pixels>,
  555    dirty: bool,
  556    markers: Arc<[PaintQuad]>,
  557    pending_refresh: Option<Task<Result<()>>>,
  558}
  559
  560impl ScrollbarMarkerState {
  561    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  562        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  563    }
  564}
  565
  566#[derive(Clone, Debug)]
  567struct RunnableTasks {
  568    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  569    offset: MultiBufferOffset,
  570    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  571    column: u32,
  572    // Values of all named captures, including those starting with '_'
  573    extra_variables: HashMap<String, String>,
  574    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  575    context_range: Range<BufferOffset>,
  576}
  577
  578impl RunnableTasks {
  579    fn resolve<'a>(
  580        &'a self,
  581        cx: &'a task::TaskContext,
  582    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  583        self.templates.iter().filter_map(|(kind, template)| {
  584            template
  585                .resolve_task(&kind.to_id_base(), cx)
  586                .map(|task| (kind.clone(), task))
  587        })
  588    }
  589}
  590
  591#[derive(Clone)]
  592struct ResolvedTasks {
  593    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  594    position: Anchor,
  595}
  596#[derive(Copy, Clone, Debug)]
  597struct MultiBufferOffset(usize);
  598#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  599struct BufferOffset(usize);
  600
  601// Addons allow storing per-editor state in other crates (e.g. Vim)
  602pub trait Addon: 'static {
  603    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  604
  605    fn render_buffer_header_controls(
  606        &self,
  607        _: &ExcerptInfo,
  608        _: &Window,
  609        _: &App,
  610    ) -> Option<AnyElement> {
  611        None
  612    }
  613
  614    fn to_any(&self) -> &dyn std::any::Any;
  615}
  616
  617#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  618pub enum IsVimMode {
  619    Yes,
  620    No,
  621}
  622
  623/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  624///
  625/// See the [module level documentation](self) for more information.
  626pub struct Editor {
  627    focus_handle: FocusHandle,
  628    last_focused_descendant: Option<WeakFocusHandle>,
  629    /// The text buffer being edited
  630    buffer: Entity<MultiBuffer>,
  631    /// Map of how text in the buffer should be displayed.
  632    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  633    pub display_map: Entity<DisplayMap>,
  634    pub selections: SelectionsCollection,
  635    pub scroll_manager: ScrollManager,
  636    /// When inline assist editors are linked, they all render cursors because
  637    /// typing enters text into each of them, even the ones that aren't focused.
  638    pub(crate) show_cursor_when_unfocused: bool,
  639    columnar_selection_tail: Option<Anchor>,
  640    add_selections_state: Option<AddSelectionsState>,
  641    select_next_state: Option<SelectNextState>,
  642    select_prev_state: Option<SelectNextState>,
  643    selection_history: SelectionHistory,
  644    autoclose_regions: Vec<AutocloseRegion>,
  645    snippet_stack: InvalidationStack<SnippetState>,
  646    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  647    ime_transaction: Option<TransactionId>,
  648    active_diagnostics: Option<ActiveDiagnosticGroup>,
  649    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  650
  651    // TODO: make this a access method
  652    pub project: Option<Entity<Project>>,
  653    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  654    completion_provider: Option<Box<dyn CompletionProvider>>,
  655    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  656    blink_manager: Entity<BlinkManager>,
  657    show_cursor_names: bool,
  658    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  659    pub show_local_selections: bool,
  660    mode: EditorMode,
  661    show_breadcrumbs: bool,
  662    show_gutter: bool,
  663    show_scrollbars: bool,
  664    show_line_numbers: Option<bool>,
  665    use_relative_line_numbers: Option<bool>,
  666    show_git_diff_gutter: Option<bool>,
  667    show_code_actions: Option<bool>,
  668    show_runnables: Option<bool>,
  669    show_wrap_guides: Option<bool>,
  670    show_indent_guides: Option<bool>,
  671    placeholder_text: Option<Arc<str>>,
  672    highlight_order: usize,
  673    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  674    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  675    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  676    scrollbar_marker_state: ScrollbarMarkerState,
  677    active_indent_guides_state: ActiveIndentGuidesState,
  678    nav_history: Option<ItemNavHistory>,
  679    context_menu: RefCell<Option<CodeContextMenu>>,
  680    mouse_context_menu: Option<MouseContextMenu>,
  681    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  682    signature_help_state: SignatureHelpState,
  683    auto_signature_help: Option<bool>,
  684    find_all_references_task_sources: Vec<Anchor>,
  685    next_completion_id: CompletionId,
  686    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  687    code_actions_task: Option<Task<Result<()>>>,
  688    document_highlights_task: Option<Task<()>>,
  689    linked_editing_range_task: Option<Task<Option<()>>>,
  690    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  691    pending_rename: Option<RenameState>,
  692    searchable: bool,
  693    cursor_shape: CursorShape,
  694    current_line_highlight: Option<CurrentLineHighlight>,
  695    collapse_matches: bool,
  696    autoindent_mode: Option<AutoindentMode>,
  697    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  698    input_enabled: bool,
  699    use_modal_editing: bool,
  700    read_only: bool,
  701    leader_peer_id: Option<PeerId>,
  702    remote_id: Option<ViewId>,
  703    hover_state: HoverState,
  704    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  705    gutter_hovered: bool,
  706    hovered_link_state: Option<HoveredLinkState>,
  707    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  708    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  709    active_inline_completion: Option<InlineCompletionState>,
  710    /// Used to prevent flickering as the user types while the menu is open
  711    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  712    edit_prediction_settings: EditPredictionSettings,
  713    inline_completions_hidden_for_vim_mode: bool,
  714    show_inline_completions_override: Option<bool>,
  715    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  716    edit_prediction_preview: EditPredictionPreview,
  717    edit_prediction_cursor_on_leading_whitespace: bool,
  718    edit_prediction_requires_modifier_in_leading_space: bool,
  719    inlay_hint_cache: InlayHintCache,
  720    next_inlay_id: usize,
  721    _subscriptions: Vec<Subscription>,
  722    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  723    gutter_dimensions: GutterDimensions,
  724    style: Option<EditorStyle>,
  725    text_style_refinement: Option<TextStyleRefinement>,
  726    next_editor_action_id: EditorActionId,
  727    editor_actions:
  728        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  729    use_autoclose: bool,
  730    use_auto_surround: bool,
  731    auto_replace_emoji_shortcode: bool,
  732    show_git_blame_gutter: bool,
  733    show_git_blame_inline: bool,
  734    show_git_blame_inline_delay_task: Option<Task<()>>,
  735    distinguish_unstaged_diff_hunks: bool,
  736    git_blame_inline_enabled: bool,
  737    serialize_dirty_buffers: bool,
  738    show_selection_menu: Option<bool>,
  739    blame: Option<Entity<GitBlame>>,
  740    blame_subscription: Option<Subscription>,
  741    custom_context_menu: Option<
  742        Box<
  743            dyn 'static
  744                + Fn(
  745                    &mut Self,
  746                    DisplayPoint,
  747                    &mut Window,
  748                    &mut Context<Self>,
  749                ) -> Option<Entity<ui::ContextMenu>>,
  750        >,
  751    >,
  752    last_bounds: Option<Bounds<Pixels>>,
  753    last_position_map: Option<Rc<PositionMap>>,
  754    expect_bounds_change: Option<Bounds<Pixels>>,
  755    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  756    tasks_update_task: Option<Task<()>>,
  757    in_project_search: bool,
  758    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  759    breadcrumb_header: Option<String>,
  760    focused_block: Option<FocusedBlock>,
  761    next_scroll_position: NextScrollCursorCenterTopBottom,
  762    addons: HashMap<TypeId, Box<dyn Addon>>,
  763    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  764    selection_mark_mode: bool,
  765    toggle_fold_multiple_buffers: Task<()>,
  766    _scroll_cursor_center_top_bottom_task: Task<()>,
  767}
  768
  769#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  770enum NextScrollCursorCenterTopBottom {
  771    #[default]
  772    Center,
  773    Top,
  774    Bottom,
  775}
  776
  777impl NextScrollCursorCenterTopBottom {
  778    fn next(&self) -> Self {
  779        match self {
  780            Self::Center => Self::Top,
  781            Self::Top => Self::Bottom,
  782            Self::Bottom => Self::Center,
  783        }
  784    }
  785}
  786
  787#[derive(Clone)]
  788pub struct EditorSnapshot {
  789    pub mode: EditorMode,
  790    show_gutter: bool,
  791    show_line_numbers: Option<bool>,
  792    show_git_diff_gutter: Option<bool>,
  793    show_code_actions: Option<bool>,
  794    show_runnables: Option<bool>,
  795    git_blame_gutter_max_author_length: Option<usize>,
  796    pub display_snapshot: DisplaySnapshot,
  797    pub placeholder_text: Option<Arc<str>>,
  798    is_focused: bool,
  799    scroll_anchor: ScrollAnchor,
  800    ongoing_scroll: OngoingScroll,
  801    current_line_highlight: CurrentLineHighlight,
  802    gutter_hovered: bool,
  803}
  804
  805const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  806
  807#[derive(Default, Debug, Clone, Copy)]
  808pub struct GutterDimensions {
  809    pub left_padding: Pixels,
  810    pub right_padding: Pixels,
  811    pub width: Pixels,
  812    pub margin: Pixels,
  813    pub git_blame_entries_width: Option<Pixels>,
  814}
  815
  816impl GutterDimensions {
  817    /// The full width of the space taken up by the gutter.
  818    pub fn full_width(&self) -> Pixels {
  819        self.margin + self.width
  820    }
  821
  822    /// The width of the space reserved for the fold indicators,
  823    /// use alongside 'justify_end' and `gutter_width` to
  824    /// right align content with the line numbers
  825    pub fn fold_area_width(&self) -> Pixels {
  826        self.margin + self.right_padding
  827    }
  828}
  829
  830#[derive(Debug)]
  831pub struct RemoteSelection {
  832    pub replica_id: ReplicaId,
  833    pub selection: Selection<Anchor>,
  834    pub cursor_shape: CursorShape,
  835    pub peer_id: PeerId,
  836    pub line_mode: bool,
  837    pub participant_index: Option<ParticipantIndex>,
  838    pub user_name: Option<SharedString>,
  839}
  840
  841#[derive(Clone, Debug)]
  842struct SelectionHistoryEntry {
  843    selections: Arc<[Selection<Anchor>]>,
  844    select_next_state: Option<SelectNextState>,
  845    select_prev_state: Option<SelectNextState>,
  846    add_selections_state: Option<AddSelectionsState>,
  847}
  848
  849enum SelectionHistoryMode {
  850    Normal,
  851    Undoing,
  852    Redoing,
  853}
  854
  855#[derive(Clone, PartialEq, Eq, Hash)]
  856struct HoveredCursor {
  857    replica_id: u16,
  858    selection_id: usize,
  859}
  860
  861impl Default for SelectionHistoryMode {
  862    fn default() -> Self {
  863        Self::Normal
  864    }
  865}
  866
  867#[derive(Default)]
  868struct SelectionHistory {
  869    #[allow(clippy::type_complexity)]
  870    selections_by_transaction:
  871        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  872    mode: SelectionHistoryMode,
  873    undo_stack: VecDeque<SelectionHistoryEntry>,
  874    redo_stack: VecDeque<SelectionHistoryEntry>,
  875}
  876
  877impl SelectionHistory {
  878    fn insert_transaction(
  879        &mut self,
  880        transaction_id: TransactionId,
  881        selections: Arc<[Selection<Anchor>]>,
  882    ) {
  883        self.selections_by_transaction
  884            .insert(transaction_id, (selections, None));
  885    }
  886
  887    #[allow(clippy::type_complexity)]
  888    fn transaction(
  889        &self,
  890        transaction_id: TransactionId,
  891    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  892        self.selections_by_transaction.get(&transaction_id)
  893    }
  894
  895    #[allow(clippy::type_complexity)]
  896    fn transaction_mut(
  897        &mut self,
  898        transaction_id: TransactionId,
  899    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  900        self.selections_by_transaction.get_mut(&transaction_id)
  901    }
  902
  903    fn push(&mut self, entry: SelectionHistoryEntry) {
  904        if !entry.selections.is_empty() {
  905            match self.mode {
  906                SelectionHistoryMode::Normal => {
  907                    self.push_undo(entry);
  908                    self.redo_stack.clear();
  909                }
  910                SelectionHistoryMode::Undoing => self.push_redo(entry),
  911                SelectionHistoryMode::Redoing => self.push_undo(entry),
  912            }
  913        }
  914    }
  915
  916    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  917        if self
  918            .undo_stack
  919            .back()
  920            .map_or(true, |e| e.selections != entry.selections)
  921        {
  922            self.undo_stack.push_back(entry);
  923            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  924                self.undo_stack.pop_front();
  925            }
  926        }
  927    }
  928
  929    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  930        if self
  931            .redo_stack
  932            .back()
  933            .map_or(true, |e| e.selections != entry.selections)
  934        {
  935            self.redo_stack.push_back(entry);
  936            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  937                self.redo_stack.pop_front();
  938            }
  939        }
  940    }
  941}
  942
  943struct RowHighlight {
  944    index: usize,
  945    range: Range<Anchor>,
  946    color: Hsla,
  947    should_autoscroll: bool,
  948}
  949
  950#[derive(Clone, Debug)]
  951struct AddSelectionsState {
  952    above: bool,
  953    stack: Vec<usize>,
  954}
  955
  956#[derive(Clone)]
  957struct SelectNextState {
  958    query: AhoCorasick,
  959    wordwise: bool,
  960    done: bool,
  961}
  962
  963impl std::fmt::Debug for SelectNextState {
  964    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  965        f.debug_struct(std::any::type_name::<Self>())
  966            .field("wordwise", &self.wordwise)
  967            .field("done", &self.done)
  968            .finish()
  969    }
  970}
  971
  972#[derive(Debug)]
  973struct AutocloseRegion {
  974    selection_id: usize,
  975    range: Range<Anchor>,
  976    pair: BracketPair,
  977}
  978
  979#[derive(Debug)]
  980struct SnippetState {
  981    ranges: Vec<Vec<Range<Anchor>>>,
  982    active_index: usize,
  983    choices: Vec<Option<Vec<String>>>,
  984}
  985
  986#[doc(hidden)]
  987pub struct RenameState {
  988    pub range: Range<Anchor>,
  989    pub old_name: Arc<str>,
  990    pub editor: Entity<Editor>,
  991    block_id: CustomBlockId,
  992}
  993
  994struct InvalidationStack<T>(Vec<T>);
  995
  996struct RegisteredInlineCompletionProvider {
  997    provider: Arc<dyn InlineCompletionProviderHandle>,
  998    _subscription: Subscription,
  999}
 1000
 1001#[derive(Debug)]
 1002struct ActiveDiagnosticGroup {
 1003    primary_range: Range<Anchor>,
 1004    primary_message: String,
 1005    group_id: usize,
 1006    blocks: HashMap<CustomBlockId, Diagnostic>,
 1007    is_valid: bool,
 1008}
 1009
 1010#[derive(Serialize, Deserialize, Clone, Debug)]
 1011pub struct ClipboardSelection {
 1012    pub len: usize,
 1013    pub is_entire_line: bool,
 1014    pub first_line_indent: u32,
 1015}
 1016
 1017#[derive(Debug)]
 1018pub(crate) struct NavigationData {
 1019    cursor_anchor: Anchor,
 1020    cursor_position: Point,
 1021    scroll_anchor: ScrollAnchor,
 1022    scroll_top_row: u32,
 1023}
 1024
 1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1026pub enum GotoDefinitionKind {
 1027    Symbol,
 1028    Declaration,
 1029    Type,
 1030    Implementation,
 1031}
 1032
 1033#[derive(Debug, Clone)]
 1034enum InlayHintRefreshReason {
 1035    Toggle(bool),
 1036    SettingsChange(InlayHintSettings),
 1037    NewLinesShown,
 1038    BufferEdited(HashSet<Arc<Language>>),
 1039    RefreshRequested,
 1040    ExcerptsRemoved(Vec<ExcerptId>),
 1041}
 1042
 1043impl InlayHintRefreshReason {
 1044    fn description(&self) -> &'static str {
 1045        match self {
 1046            Self::Toggle(_) => "toggle",
 1047            Self::SettingsChange(_) => "settings change",
 1048            Self::NewLinesShown => "new lines shown",
 1049            Self::BufferEdited(_) => "buffer edited",
 1050            Self::RefreshRequested => "refresh requested",
 1051            Self::ExcerptsRemoved(_) => "excerpts removed",
 1052        }
 1053    }
 1054}
 1055
 1056pub enum FormatTarget {
 1057    Buffers,
 1058    Ranges(Vec<Range<MultiBufferPoint>>),
 1059}
 1060
 1061pub(crate) struct FocusedBlock {
 1062    id: BlockId,
 1063    focus_handle: WeakFocusHandle,
 1064}
 1065
 1066#[derive(Clone)]
 1067enum JumpData {
 1068    MultiBufferRow {
 1069        row: MultiBufferRow,
 1070        line_offset_from_top: u32,
 1071    },
 1072    MultiBufferPoint {
 1073        excerpt_id: ExcerptId,
 1074        position: Point,
 1075        anchor: text::Anchor,
 1076        line_offset_from_top: u32,
 1077    },
 1078}
 1079
 1080pub enum MultibufferSelectionMode {
 1081    First,
 1082    All,
 1083}
 1084
 1085impl Editor {
 1086    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1087        let buffer = cx.new(|cx| Buffer::local("", cx));
 1088        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1089        Self::new(
 1090            EditorMode::SingleLine { auto_width: false },
 1091            buffer,
 1092            None,
 1093            false,
 1094            window,
 1095            cx,
 1096        )
 1097    }
 1098
 1099    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1100        let buffer = cx.new(|cx| Buffer::local("", cx));
 1101        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1102        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1103    }
 1104
 1105    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1106        let buffer = cx.new(|cx| Buffer::local("", cx));
 1107        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1108        Self::new(
 1109            EditorMode::SingleLine { auto_width: true },
 1110            buffer,
 1111            None,
 1112            false,
 1113            window,
 1114            cx,
 1115        )
 1116    }
 1117
 1118    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1119        let buffer = cx.new(|cx| Buffer::local("", cx));
 1120        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1121        Self::new(
 1122            EditorMode::AutoHeight { max_lines },
 1123            buffer,
 1124            None,
 1125            false,
 1126            window,
 1127            cx,
 1128        )
 1129    }
 1130
 1131    pub fn for_buffer(
 1132        buffer: Entity<Buffer>,
 1133        project: Option<Entity<Project>>,
 1134        window: &mut Window,
 1135        cx: &mut Context<Self>,
 1136    ) -> Self {
 1137        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1138        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1139    }
 1140
 1141    pub fn for_multibuffer(
 1142        buffer: Entity<MultiBuffer>,
 1143        project: Option<Entity<Project>>,
 1144        show_excerpt_controls: bool,
 1145        window: &mut Window,
 1146        cx: &mut Context<Self>,
 1147    ) -> Self {
 1148        Self::new(
 1149            EditorMode::Full,
 1150            buffer,
 1151            project,
 1152            show_excerpt_controls,
 1153            window,
 1154            cx,
 1155        )
 1156    }
 1157
 1158    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1159        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1160        let mut clone = Self::new(
 1161            self.mode,
 1162            self.buffer.clone(),
 1163            self.project.clone(),
 1164            show_excerpt_controls,
 1165            window,
 1166            cx,
 1167        );
 1168        self.display_map.update(cx, |display_map, cx| {
 1169            let snapshot = display_map.snapshot(cx);
 1170            clone.display_map.update(cx, |display_map, cx| {
 1171                display_map.set_state(&snapshot, cx);
 1172            });
 1173        });
 1174        clone.selections.clone_state(&self.selections);
 1175        clone.scroll_manager.clone_state(&self.scroll_manager);
 1176        clone.searchable = self.searchable;
 1177        clone
 1178    }
 1179
 1180    pub fn new(
 1181        mode: EditorMode,
 1182        buffer: Entity<MultiBuffer>,
 1183        project: Option<Entity<Project>>,
 1184        show_excerpt_controls: bool,
 1185        window: &mut Window,
 1186        cx: &mut Context<Self>,
 1187    ) -> Self {
 1188        let style = window.text_style();
 1189        let font_size = style.font_size.to_pixels(window.rem_size());
 1190        let editor = cx.entity().downgrade();
 1191        let fold_placeholder = FoldPlaceholder {
 1192            constrain_width: true,
 1193            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1194                let editor = editor.clone();
 1195                div()
 1196                    .id(fold_id)
 1197                    .bg(cx.theme().colors().ghost_element_background)
 1198                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1199                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1200                    .rounded_sm()
 1201                    .size_full()
 1202                    .cursor_pointer()
 1203                    .child("")
 1204                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1205                    .on_click(move |_, _window, cx| {
 1206                        editor
 1207                            .update(cx, |editor, cx| {
 1208                                editor.unfold_ranges(
 1209                                    &[fold_range.start..fold_range.end],
 1210                                    true,
 1211                                    false,
 1212                                    cx,
 1213                                );
 1214                                cx.stop_propagation();
 1215                            })
 1216                            .ok();
 1217                    })
 1218                    .into_any()
 1219            }),
 1220            merge_adjacent: true,
 1221            ..Default::default()
 1222        };
 1223        let display_map = cx.new(|cx| {
 1224            DisplayMap::new(
 1225                buffer.clone(),
 1226                style.font(),
 1227                font_size,
 1228                None,
 1229                show_excerpt_controls,
 1230                FILE_HEADER_HEIGHT,
 1231                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1232                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1233                fold_placeholder,
 1234                cx,
 1235            )
 1236        });
 1237
 1238        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1239
 1240        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1241
 1242        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1243            .then(|| language_settings::SoftWrap::None);
 1244
 1245        let mut project_subscriptions = Vec::new();
 1246        if mode == EditorMode::Full {
 1247            if let Some(project) = project.as_ref() {
 1248                if buffer.read(cx).is_singleton() {
 1249                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1250                        cx.emit(EditorEvent::TitleChanged);
 1251                    }));
 1252                }
 1253                project_subscriptions.push(cx.subscribe_in(
 1254                    project,
 1255                    window,
 1256                    |editor, _, event, window, cx| {
 1257                        if let project::Event::RefreshInlayHints = event {
 1258                            editor
 1259                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1260                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1261                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1262                                let focus_handle = editor.focus_handle(cx);
 1263                                if focus_handle.is_focused(window) {
 1264                                    let snapshot = buffer.read(cx).snapshot();
 1265                                    for (range, snippet) in snippet_edits {
 1266                                        let editor_range =
 1267                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1268                                        editor
 1269                                            .insert_snippet(
 1270                                                &[editor_range],
 1271                                                snippet.clone(),
 1272                                                window,
 1273                                                cx,
 1274                                            )
 1275                                            .ok();
 1276                                    }
 1277                                }
 1278                            }
 1279                        }
 1280                    },
 1281                ));
 1282                if let Some(task_inventory) = project
 1283                    .read(cx)
 1284                    .task_store()
 1285                    .read(cx)
 1286                    .task_inventory()
 1287                    .cloned()
 1288                {
 1289                    project_subscriptions.push(cx.observe_in(
 1290                        &task_inventory,
 1291                        window,
 1292                        |editor, _, window, cx| {
 1293                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1294                        },
 1295                    ));
 1296                }
 1297            }
 1298        }
 1299
 1300        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1301
 1302        let inlay_hint_settings =
 1303            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1304        let focus_handle = cx.focus_handle();
 1305        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1306            .detach();
 1307        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1308            .detach();
 1309        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1310            .detach();
 1311        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1312            .detach();
 1313
 1314        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1315            Some(false)
 1316        } else {
 1317            None
 1318        };
 1319
 1320        let mut code_action_providers = Vec::new();
 1321        if let Some(project) = project.clone() {
 1322            get_uncommitted_diff_for_buffer(
 1323                &project,
 1324                buffer.read(cx).all_buffers(),
 1325                buffer.clone(),
 1326                cx,
 1327            );
 1328            code_action_providers.push(Rc::new(project) as Rc<_>);
 1329        }
 1330
 1331        let mut this = Self {
 1332            focus_handle,
 1333            show_cursor_when_unfocused: false,
 1334            last_focused_descendant: None,
 1335            buffer: buffer.clone(),
 1336            display_map: display_map.clone(),
 1337            selections,
 1338            scroll_manager: ScrollManager::new(cx),
 1339            columnar_selection_tail: None,
 1340            add_selections_state: None,
 1341            select_next_state: None,
 1342            select_prev_state: None,
 1343            selection_history: Default::default(),
 1344            autoclose_regions: Default::default(),
 1345            snippet_stack: Default::default(),
 1346            select_larger_syntax_node_stack: Vec::new(),
 1347            ime_transaction: Default::default(),
 1348            active_diagnostics: None,
 1349            soft_wrap_mode_override,
 1350            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1351            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1352            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1353            project,
 1354            blink_manager: blink_manager.clone(),
 1355            show_local_selections: true,
 1356            show_scrollbars: true,
 1357            mode,
 1358            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1359            show_gutter: mode == EditorMode::Full,
 1360            show_line_numbers: None,
 1361            use_relative_line_numbers: None,
 1362            show_git_diff_gutter: None,
 1363            show_code_actions: None,
 1364            show_runnables: None,
 1365            show_wrap_guides: None,
 1366            show_indent_guides,
 1367            placeholder_text: None,
 1368            highlight_order: 0,
 1369            highlighted_rows: HashMap::default(),
 1370            background_highlights: Default::default(),
 1371            gutter_highlights: TreeMap::default(),
 1372            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1373            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1374            nav_history: None,
 1375            context_menu: RefCell::new(None),
 1376            mouse_context_menu: None,
 1377            completion_tasks: Default::default(),
 1378            signature_help_state: SignatureHelpState::default(),
 1379            auto_signature_help: None,
 1380            find_all_references_task_sources: Vec::new(),
 1381            next_completion_id: 0,
 1382            next_inlay_id: 0,
 1383            code_action_providers,
 1384            available_code_actions: Default::default(),
 1385            code_actions_task: Default::default(),
 1386            document_highlights_task: Default::default(),
 1387            linked_editing_range_task: Default::default(),
 1388            pending_rename: Default::default(),
 1389            searchable: true,
 1390            cursor_shape: EditorSettings::get_global(cx)
 1391                .cursor_shape
 1392                .unwrap_or_default(),
 1393            current_line_highlight: None,
 1394            autoindent_mode: Some(AutoindentMode::EachLine),
 1395            collapse_matches: false,
 1396            workspace: None,
 1397            input_enabled: true,
 1398            use_modal_editing: mode == EditorMode::Full,
 1399            read_only: false,
 1400            use_autoclose: true,
 1401            use_auto_surround: true,
 1402            auto_replace_emoji_shortcode: false,
 1403            leader_peer_id: None,
 1404            remote_id: None,
 1405            hover_state: Default::default(),
 1406            pending_mouse_down: None,
 1407            hovered_link_state: Default::default(),
 1408            edit_prediction_provider: None,
 1409            active_inline_completion: None,
 1410            stale_inline_completion_in_menu: None,
 1411            edit_prediction_preview: EditPredictionPreview::Inactive,
 1412            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1413
 1414            gutter_hovered: false,
 1415            pixel_position_of_newest_cursor: None,
 1416            last_bounds: None,
 1417            last_position_map: None,
 1418            expect_bounds_change: None,
 1419            gutter_dimensions: GutterDimensions::default(),
 1420            style: None,
 1421            show_cursor_names: false,
 1422            hovered_cursors: Default::default(),
 1423            next_editor_action_id: EditorActionId::default(),
 1424            editor_actions: Rc::default(),
 1425            inline_completions_hidden_for_vim_mode: false,
 1426            show_inline_completions_override: None,
 1427            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1428            edit_prediction_settings: EditPredictionSettings::Disabled,
 1429            edit_prediction_cursor_on_leading_whitespace: false,
 1430            edit_prediction_requires_modifier_in_leading_space: true,
 1431            custom_context_menu: None,
 1432            show_git_blame_gutter: false,
 1433            show_git_blame_inline: false,
 1434            distinguish_unstaged_diff_hunks: false,
 1435            show_selection_menu: None,
 1436            show_git_blame_inline_delay_task: None,
 1437            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1438            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1439                .session
 1440                .restore_unsaved_buffers,
 1441            blame: None,
 1442            blame_subscription: None,
 1443            tasks: Default::default(),
 1444            _subscriptions: vec![
 1445                cx.observe(&buffer, Self::on_buffer_changed),
 1446                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1447                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1448                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1449                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1450                cx.observe_window_activation(window, |editor, window, cx| {
 1451                    let active = window.is_window_active();
 1452                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1453                        if active {
 1454                            blink_manager.enable(cx);
 1455                        } else {
 1456                            blink_manager.disable(cx);
 1457                        }
 1458                    });
 1459                }),
 1460            ],
 1461            tasks_update_task: None,
 1462            linked_edit_ranges: Default::default(),
 1463            in_project_search: false,
 1464            previous_search_ranges: None,
 1465            breadcrumb_header: None,
 1466            focused_block: None,
 1467            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1468            addons: HashMap::default(),
 1469            registered_buffers: HashMap::default(),
 1470            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1471            selection_mark_mode: false,
 1472            toggle_fold_multiple_buffers: Task::ready(()),
 1473            text_style_refinement: None,
 1474        };
 1475        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1476        this._subscriptions.extend(project_subscriptions);
 1477
 1478        this.end_selection(window, cx);
 1479        this.scroll_manager.show_scrollbar(window, cx);
 1480
 1481        if mode == EditorMode::Full {
 1482            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1483            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1484
 1485            if this.git_blame_inline_enabled {
 1486                this.git_blame_inline_enabled = true;
 1487                this.start_git_blame_inline(false, window, cx);
 1488            }
 1489
 1490            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1491                if let Some(project) = this.project.as_ref() {
 1492                    let lsp_store = project.read(cx).lsp_store();
 1493                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1494                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1495                    });
 1496                    this.registered_buffers
 1497                        .insert(buffer.read(cx).remote_id(), handle);
 1498                }
 1499            }
 1500        }
 1501
 1502        this.report_editor_event("Editor Opened", None, cx);
 1503        this
 1504    }
 1505
 1506    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1507        self.mouse_context_menu
 1508            .as_ref()
 1509            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1510    }
 1511
 1512    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1513        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1514    }
 1515
 1516    fn key_context_internal(
 1517        &self,
 1518        has_active_edit_prediction: bool,
 1519        window: &Window,
 1520        cx: &App,
 1521    ) -> KeyContext {
 1522        let mut key_context = KeyContext::new_with_defaults();
 1523        key_context.add("Editor");
 1524        let mode = match self.mode {
 1525            EditorMode::SingleLine { .. } => "single_line",
 1526            EditorMode::AutoHeight { .. } => "auto_height",
 1527            EditorMode::Full => "full",
 1528        };
 1529
 1530        if EditorSettings::jupyter_enabled(cx) {
 1531            key_context.add("jupyter");
 1532        }
 1533
 1534        key_context.set("mode", mode);
 1535        if self.pending_rename.is_some() {
 1536            key_context.add("renaming");
 1537        }
 1538
 1539        let mut showing_completions = false;
 1540
 1541        match self.context_menu.borrow().as_ref() {
 1542            Some(CodeContextMenu::Completions(_)) => {
 1543                key_context.add("menu");
 1544                key_context.add("showing_completions");
 1545                showing_completions = true;
 1546            }
 1547            Some(CodeContextMenu::CodeActions(_)) => {
 1548                key_context.add("menu");
 1549                key_context.add("showing_code_actions")
 1550            }
 1551            None => {}
 1552        }
 1553
 1554        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1555        if !self.focus_handle(cx).contains_focused(window, cx)
 1556            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1557        {
 1558            for addon in self.addons.values() {
 1559                addon.extend_key_context(&mut key_context, cx)
 1560            }
 1561        }
 1562
 1563        if let Some(extension) = self
 1564            .buffer
 1565            .read(cx)
 1566            .as_singleton()
 1567            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1568        {
 1569            key_context.set("extension", extension.to_string());
 1570        }
 1571
 1572        if has_active_edit_prediction {
 1573            key_context.add("copilot_suggestion");
 1574            key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1575            if showing_completions
 1576                || self.edit_prediction_requires_modifier()
 1577                // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1578                // bindings to insert tab characters.
 1579                || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1580            {
 1581                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1582            }
 1583        }
 1584
 1585        if self.selection_mark_mode {
 1586            key_context.add("selection_mode");
 1587        }
 1588
 1589        key_context
 1590    }
 1591
 1592    pub fn accept_edit_prediction_keybind(
 1593        &self,
 1594        window: &Window,
 1595        cx: &App,
 1596    ) -> AcceptEditPredictionBinding {
 1597        let key_context = self.key_context_internal(true, window, cx);
 1598        AcceptEditPredictionBinding(
 1599            window
 1600                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1601                .into_iter()
 1602                .rev()
 1603                .next(),
 1604        )
 1605    }
 1606
 1607    pub fn new_file(
 1608        workspace: &mut Workspace,
 1609        _: &workspace::NewFile,
 1610        window: &mut Window,
 1611        cx: &mut Context<Workspace>,
 1612    ) {
 1613        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1614            "Failed to create buffer",
 1615            window,
 1616            cx,
 1617            |e, _, _| match e.error_code() {
 1618                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1619                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1620                e.error_tag("required").unwrap_or("the latest version")
 1621            )),
 1622                _ => None,
 1623            },
 1624        );
 1625    }
 1626
 1627    pub fn new_in_workspace(
 1628        workspace: &mut Workspace,
 1629        window: &mut Window,
 1630        cx: &mut Context<Workspace>,
 1631    ) -> Task<Result<Entity<Editor>>> {
 1632        let project = workspace.project().clone();
 1633        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1634
 1635        cx.spawn_in(window, |workspace, mut cx| async move {
 1636            let buffer = create.await?;
 1637            workspace.update_in(&mut cx, |workspace, window, cx| {
 1638                let editor =
 1639                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1640                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1641                editor
 1642            })
 1643        })
 1644    }
 1645
 1646    fn new_file_vertical(
 1647        workspace: &mut Workspace,
 1648        _: &workspace::NewFileSplitVertical,
 1649        window: &mut Window,
 1650        cx: &mut Context<Workspace>,
 1651    ) {
 1652        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1653    }
 1654
 1655    fn new_file_horizontal(
 1656        workspace: &mut Workspace,
 1657        _: &workspace::NewFileSplitHorizontal,
 1658        window: &mut Window,
 1659        cx: &mut Context<Workspace>,
 1660    ) {
 1661        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1662    }
 1663
 1664    fn new_file_in_direction(
 1665        workspace: &mut Workspace,
 1666        direction: SplitDirection,
 1667        window: &mut Window,
 1668        cx: &mut Context<Workspace>,
 1669    ) {
 1670        let project = workspace.project().clone();
 1671        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1672
 1673        cx.spawn_in(window, |workspace, mut cx| async move {
 1674            let buffer = create.await?;
 1675            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1676                workspace.split_item(
 1677                    direction,
 1678                    Box::new(
 1679                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1680                    ),
 1681                    window,
 1682                    cx,
 1683                )
 1684            })?;
 1685            anyhow::Ok(())
 1686        })
 1687        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1688            match e.error_code() {
 1689                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1690                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1691                e.error_tag("required").unwrap_or("the latest version")
 1692            )),
 1693                _ => None,
 1694            }
 1695        });
 1696    }
 1697
 1698    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1699        self.leader_peer_id
 1700    }
 1701
 1702    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1703        &self.buffer
 1704    }
 1705
 1706    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1707        self.workspace.as_ref()?.0.upgrade()
 1708    }
 1709
 1710    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1711        self.buffer().read(cx).title(cx)
 1712    }
 1713
 1714    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1715        let git_blame_gutter_max_author_length = self
 1716            .render_git_blame_gutter(cx)
 1717            .then(|| {
 1718                if let Some(blame) = self.blame.as_ref() {
 1719                    let max_author_length =
 1720                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1721                    Some(max_author_length)
 1722                } else {
 1723                    None
 1724                }
 1725            })
 1726            .flatten();
 1727
 1728        EditorSnapshot {
 1729            mode: self.mode,
 1730            show_gutter: self.show_gutter,
 1731            show_line_numbers: self.show_line_numbers,
 1732            show_git_diff_gutter: self.show_git_diff_gutter,
 1733            show_code_actions: self.show_code_actions,
 1734            show_runnables: self.show_runnables,
 1735            git_blame_gutter_max_author_length,
 1736            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1737            scroll_anchor: self.scroll_manager.anchor(),
 1738            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1739            placeholder_text: self.placeholder_text.clone(),
 1740            is_focused: self.focus_handle.is_focused(window),
 1741            current_line_highlight: self
 1742                .current_line_highlight
 1743                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1744            gutter_hovered: self.gutter_hovered,
 1745        }
 1746    }
 1747
 1748    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1749        self.buffer.read(cx).language_at(point, cx)
 1750    }
 1751
 1752    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1753        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1754    }
 1755
 1756    pub fn active_excerpt(
 1757        &self,
 1758        cx: &App,
 1759    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1760        self.buffer
 1761            .read(cx)
 1762            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1763    }
 1764
 1765    pub fn mode(&self) -> EditorMode {
 1766        self.mode
 1767    }
 1768
 1769    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1770        self.collaboration_hub.as_deref()
 1771    }
 1772
 1773    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1774        self.collaboration_hub = Some(hub);
 1775    }
 1776
 1777    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1778        self.in_project_search = in_project_search;
 1779    }
 1780
 1781    pub fn set_custom_context_menu(
 1782        &mut self,
 1783        f: impl 'static
 1784            + Fn(
 1785                &mut Self,
 1786                DisplayPoint,
 1787                &mut Window,
 1788                &mut Context<Self>,
 1789            ) -> Option<Entity<ui::ContextMenu>>,
 1790    ) {
 1791        self.custom_context_menu = Some(Box::new(f))
 1792    }
 1793
 1794    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1795        self.completion_provider = provider;
 1796    }
 1797
 1798    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1799        self.semantics_provider.clone()
 1800    }
 1801
 1802    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1803        self.semantics_provider = provider;
 1804    }
 1805
 1806    pub fn set_edit_prediction_provider<T>(
 1807        &mut self,
 1808        provider: Option<Entity<T>>,
 1809        window: &mut Window,
 1810        cx: &mut Context<Self>,
 1811    ) where
 1812        T: EditPredictionProvider,
 1813    {
 1814        self.edit_prediction_provider =
 1815            provider.map(|provider| RegisteredInlineCompletionProvider {
 1816                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1817                    if this.focus_handle.is_focused(window) {
 1818                        this.update_visible_inline_completion(window, cx);
 1819                    }
 1820                }),
 1821                provider: Arc::new(provider),
 1822            });
 1823        self.refresh_inline_completion(false, false, window, cx);
 1824    }
 1825
 1826    pub fn placeholder_text(&self) -> Option<&str> {
 1827        self.placeholder_text.as_deref()
 1828    }
 1829
 1830    pub fn set_placeholder_text(
 1831        &mut self,
 1832        placeholder_text: impl Into<Arc<str>>,
 1833        cx: &mut Context<Self>,
 1834    ) {
 1835        let placeholder_text = Some(placeholder_text.into());
 1836        if self.placeholder_text != placeholder_text {
 1837            self.placeholder_text = placeholder_text;
 1838            cx.notify();
 1839        }
 1840    }
 1841
 1842    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1843        self.cursor_shape = cursor_shape;
 1844
 1845        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1846        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1847
 1848        cx.notify();
 1849    }
 1850
 1851    pub fn set_current_line_highlight(
 1852        &mut self,
 1853        current_line_highlight: Option<CurrentLineHighlight>,
 1854    ) {
 1855        self.current_line_highlight = current_line_highlight;
 1856    }
 1857
 1858    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1859        self.collapse_matches = collapse_matches;
 1860    }
 1861
 1862    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1863        let buffers = self.buffer.read(cx).all_buffers();
 1864        let Some(lsp_store) = self.lsp_store(cx) else {
 1865            return;
 1866        };
 1867        lsp_store.update(cx, |lsp_store, cx| {
 1868            for buffer in buffers {
 1869                self.registered_buffers
 1870                    .entry(buffer.read(cx).remote_id())
 1871                    .or_insert_with(|| {
 1872                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1873                    });
 1874            }
 1875        })
 1876    }
 1877
 1878    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1879        if self.collapse_matches {
 1880            return range.start..range.start;
 1881        }
 1882        range.clone()
 1883    }
 1884
 1885    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1886        if self.display_map.read(cx).clip_at_line_ends != clip {
 1887            self.display_map
 1888                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1889        }
 1890    }
 1891
 1892    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1893        self.input_enabled = input_enabled;
 1894    }
 1895
 1896    pub fn set_inline_completions_hidden_for_vim_mode(
 1897        &mut self,
 1898        hidden: bool,
 1899        window: &mut Window,
 1900        cx: &mut Context<Self>,
 1901    ) {
 1902        if hidden != self.inline_completions_hidden_for_vim_mode {
 1903            self.inline_completions_hidden_for_vim_mode = hidden;
 1904            if hidden {
 1905                self.update_visible_inline_completion(window, cx);
 1906            } else {
 1907                self.refresh_inline_completion(true, false, window, cx);
 1908            }
 1909        }
 1910    }
 1911
 1912    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1913        self.menu_inline_completions_policy = value;
 1914    }
 1915
 1916    pub fn set_autoindent(&mut self, autoindent: bool) {
 1917        if autoindent {
 1918            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1919        } else {
 1920            self.autoindent_mode = None;
 1921        }
 1922    }
 1923
 1924    pub fn read_only(&self, cx: &App) -> bool {
 1925        self.read_only || self.buffer.read(cx).read_only()
 1926    }
 1927
 1928    pub fn set_read_only(&mut self, read_only: bool) {
 1929        self.read_only = read_only;
 1930    }
 1931
 1932    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1933        self.use_autoclose = autoclose;
 1934    }
 1935
 1936    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1937        self.use_auto_surround = auto_surround;
 1938    }
 1939
 1940    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1941        self.auto_replace_emoji_shortcode = auto_replace;
 1942    }
 1943
 1944    pub fn toggle_inline_completions(
 1945        &mut self,
 1946        _: &ToggleEditPrediction,
 1947        window: &mut Window,
 1948        cx: &mut Context<Self>,
 1949    ) {
 1950        if self.show_inline_completions_override.is_some() {
 1951            self.set_show_edit_predictions(None, window, cx);
 1952        } else {
 1953            let show_edit_predictions = !self.edit_predictions_enabled();
 1954            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1955        }
 1956    }
 1957
 1958    pub fn set_show_edit_predictions(
 1959        &mut self,
 1960        show_edit_predictions: Option<bool>,
 1961        window: &mut Window,
 1962        cx: &mut Context<Self>,
 1963    ) {
 1964        self.show_inline_completions_override = show_edit_predictions;
 1965        self.refresh_inline_completion(false, true, window, cx);
 1966    }
 1967
 1968    fn inline_completions_disabled_in_scope(
 1969        &self,
 1970        buffer: &Entity<Buffer>,
 1971        buffer_position: language::Anchor,
 1972        cx: &App,
 1973    ) -> bool {
 1974        let snapshot = buffer.read(cx).snapshot();
 1975        let settings = snapshot.settings_at(buffer_position, cx);
 1976
 1977        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1978            return false;
 1979        };
 1980
 1981        scope.override_name().map_or(false, |scope_name| {
 1982            settings
 1983                .edit_predictions_disabled_in
 1984                .iter()
 1985                .any(|s| s == scope_name)
 1986        })
 1987    }
 1988
 1989    pub fn set_use_modal_editing(&mut self, to: bool) {
 1990        self.use_modal_editing = to;
 1991    }
 1992
 1993    pub fn use_modal_editing(&self) -> bool {
 1994        self.use_modal_editing
 1995    }
 1996
 1997    fn selections_did_change(
 1998        &mut self,
 1999        local: bool,
 2000        old_cursor_position: &Anchor,
 2001        show_completions: bool,
 2002        window: &mut Window,
 2003        cx: &mut Context<Self>,
 2004    ) {
 2005        window.invalidate_character_coordinates();
 2006
 2007        // Copy selections to primary selection buffer
 2008        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2009        if local {
 2010            let selections = self.selections.all::<usize>(cx);
 2011            let buffer_handle = self.buffer.read(cx).read(cx);
 2012
 2013            let mut text = String::new();
 2014            for (index, selection) in selections.iter().enumerate() {
 2015                let text_for_selection = buffer_handle
 2016                    .text_for_range(selection.start..selection.end)
 2017                    .collect::<String>();
 2018
 2019                text.push_str(&text_for_selection);
 2020                if index != selections.len() - 1 {
 2021                    text.push('\n');
 2022                }
 2023            }
 2024
 2025            if !text.is_empty() {
 2026                cx.write_to_primary(ClipboardItem::new_string(text));
 2027            }
 2028        }
 2029
 2030        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2031            self.buffer.update(cx, |buffer, cx| {
 2032                buffer.set_active_selections(
 2033                    &self.selections.disjoint_anchors(),
 2034                    self.selections.line_mode,
 2035                    self.cursor_shape,
 2036                    cx,
 2037                )
 2038            });
 2039        }
 2040        let display_map = self
 2041            .display_map
 2042            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2043        let buffer = &display_map.buffer_snapshot;
 2044        self.add_selections_state = None;
 2045        self.select_next_state = None;
 2046        self.select_prev_state = None;
 2047        self.select_larger_syntax_node_stack.clear();
 2048        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2049        self.snippet_stack
 2050            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2051        self.take_rename(false, window, cx);
 2052
 2053        let new_cursor_position = self.selections.newest_anchor().head();
 2054
 2055        self.push_to_nav_history(
 2056            *old_cursor_position,
 2057            Some(new_cursor_position.to_point(buffer)),
 2058            cx,
 2059        );
 2060
 2061        if local {
 2062            let new_cursor_position = self.selections.newest_anchor().head();
 2063            let mut context_menu = self.context_menu.borrow_mut();
 2064            let completion_menu = match context_menu.as_ref() {
 2065                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2066                _ => {
 2067                    *context_menu = None;
 2068                    None
 2069                }
 2070            };
 2071            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2072                if !self.registered_buffers.contains_key(&buffer_id) {
 2073                    if let Some(lsp_store) = self.lsp_store(cx) {
 2074                        lsp_store.update(cx, |lsp_store, cx| {
 2075                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2076                                return;
 2077                            };
 2078                            self.registered_buffers.insert(
 2079                                buffer_id,
 2080                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2081                            );
 2082                        })
 2083                    }
 2084                }
 2085            }
 2086
 2087            if let Some(completion_menu) = completion_menu {
 2088                let cursor_position = new_cursor_position.to_offset(buffer);
 2089                let (word_range, kind) =
 2090                    buffer.surrounding_word(completion_menu.initial_position, true);
 2091                if kind == Some(CharKind::Word)
 2092                    && word_range.to_inclusive().contains(&cursor_position)
 2093                {
 2094                    let mut completion_menu = completion_menu.clone();
 2095                    drop(context_menu);
 2096
 2097                    let query = Self::completion_query(buffer, cursor_position);
 2098                    cx.spawn(move |this, mut cx| async move {
 2099                        completion_menu
 2100                            .filter(query.as_deref(), cx.background_executor().clone())
 2101                            .await;
 2102
 2103                        this.update(&mut cx, |this, cx| {
 2104                            let mut context_menu = this.context_menu.borrow_mut();
 2105                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2106                            else {
 2107                                return;
 2108                            };
 2109
 2110                            if menu.id > completion_menu.id {
 2111                                return;
 2112                            }
 2113
 2114                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2115                            drop(context_menu);
 2116                            cx.notify();
 2117                        })
 2118                    })
 2119                    .detach();
 2120
 2121                    if show_completions {
 2122                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2123                    }
 2124                } else {
 2125                    drop(context_menu);
 2126                    self.hide_context_menu(window, cx);
 2127                }
 2128            } else {
 2129                drop(context_menu);
 2130            }
 2131
 2132            hide_hover(self, cx);
 2133
 2134            if old_cursor_position.to_display_point(&display_map).row()
 2135                != new_cursor_position.to_display_point(&display_map).row()
 2136            {
 2137                self.available_code_actions.take();
 2138            }
 2139            self.refresh_code_actions(window, cx);
 2140            self.refresh_document_highlights(cx);
 2141            refresh_matching_bracket_highlights(self, window, cx);
 2142            self.update_visible_inline_completion(window, cx);
 2143            self.edit_prediction_requires_modifier_in_leading_space = true;
 2144            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2145            if self.git_blame_inline_enabled {
 2146                self.start_inline_blame_timer(window, cx);
 2147            }
 2148        }
 2149
 2150        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2151        cx.emit(EditorEvent::SelectionsChanged { local });
 2152
 2153        if self.selections.disjoint_anchors().len() == 1 {
 2154            cx.emit(SearchEvent::ActiveMatchChanged)
 2155        }
 2156        cx.notify();
 2157    }
 2158
 2159    pub fn change_selections<R>(
 2160        &mut self,
 2161        autoscroll: Option<Autoscroll>,
 2162        window: &mut Window,
 2163        cx: &mut Context<Self>,
 2164        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2165    ) -> R {
 2166        self.change_selections_inner(autoscroll, true, window, cx, change)
 2167    }
 2168
 2169    pub fn change_selections_inner<R>(
 2170        &mut self,
 2171        autoscroll: Option<Autoscroll>,
 2172        request_completions: bool,
 2173        window: &mut Window,
 2174        cx: &mut Context<Self>,
 2175        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2176    ) -> R {
 2177        let old_cursor_position = self.selections.newest_anchor().head();
 2178        self.push_to_selection_history();
 2179
 2180        let (changed, result) = self.selections.change_with(cx, change);
 2181
 2182        if changed {
 2183            if let Some(autoscroll) = autoscroll {
 2184                self.request_autoscroll(autoscroll, cx);
 2185            }
 2186            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2187
 2188            if self.should_open_signature_help_automatically(
 2189                &old_cursor_position,
 2190                self.signature_help_state.backspace_pressed(),
 2191                cx,
 2192            ) {
 2193                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2194            }
 2195            self.signature_help_state.set_backspace_pressed(false);
 2196        }
 2197
 2198        result
 2199    }
 2200
 2201    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2202    where
 2203        I: IntoIterator<Item = (Range<S>, T)>,
 2204        S: ToOffset,
 2205        T: Into<Arc<str>>,
 2206    {
 2207        if self.read_only(cx) {
 2208            return;
 2209        }
 2210
 2211        self.buffer
 2212            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2213    }
 2214
 2215    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2216    where
 2217        I: IntoIterator<Item = (Range<S>, T)>,
 2218        S: ToOffset,
 2219        T: Into<Arc<str>>,
 2220    {
 2221        if self.read_only(cx) {
 2222            return;
 2223        }
 2224
 2225        self.buffer.update(cx, |buffer, cx| {
 2226            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2227        });
 2228    }
 2229
 2230    pub fn edit_with_block_indent<I, S, T>(
 2231        &mut self,
 2232        edits: I,
 2233        original_indent_columns: Vec<u32>,
 2234        cx: &mut Context<Self>,
 2235    ) where
 2236        I: IntoIterator<Item = (Range<S>, T)>,
 2237        S: ToOffset,
 2238        T: Into<Arc<str>>,
 2239    {
 2240        if self.read_only(cx) {
 2241            return;
 2242        }
 2243
 2244        self.buffer.update(cx, |buffer, cx| {
 2245            buffer.edit(
 2246                edits,
 2247                Some(AutoindentMode::Block {
 2248                    original_indent_columns,
 2249                }),
 2250                cx,
 2251            )
 2252        });
 2253    }
 2254
 2255    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2256        self.hide_context_menu(window, cx);
 2257
 2258        match phase {
 2259            SelectPhase::Begin {
 2260                position,
 2261                add,
 2262                click_count,
 2263            } => self.begin_selection(position, add, click_count, window, cx),
 2264            SelectPhase::BeginColumnar {
 2265                position,
 2266                goal_column,
 2267                reset,
 2268            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2269            SelectPhase::Extend {
 2270                position,
 2271                click_count,
 2272            } => self.extend_selection(position, click_count, window, cx),
 2273            SelectPhase::Update {
 2274                position,
 2275                goal_column,
 2276                scroll_delta,
 2277            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2278            SelectPhase::End => self.end_selection(window, cx),
 2279        }
 2280    }
 2281
 2282    fn extend_selection(
 2283        &mut self,
 2284        position: DisplayPoint,
 2285        click_count: usize,
 2286        window: &mut Window,
 2287        cx: &mut Context<Self>,
 2288    ) {
 2289        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2290        let tail = self.selections.newest::<usize>(cx).tail();
 2291        self.begin_selection(position, false, click_count, window, cx);
 2292
 2293        let position = position.to_offset(&display_map, Bias::Left);
 2294        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2295
 2296        let mut pending_selection = self
 2297            .selections
 2298            .pending_anchor()
 2299            .expect("extend_selection not called with pending selection");
 2300        if position >= tail {
 2301            pending_selection.start = tail_anchor;
 2302        } else {
 2303            pending_selection.end = tail_anchor;
 2304            pending_selection.reversed = true;
 2305        }
 2306
 2307        let mut pending_mode = self.selections.pending_mode().unwrap();
 2308        match &mut pending_mode {
 2309            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2310            _ => {}
 2311        }
 2312
 2313        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2314            s.set_pending(pending_selection, pending_mode)
 2315        });
 2316    }
 2317
 2318    fn begin_selection(
 2319        &mut self,
 2320        position: DisplayPoint,
 2321        add: bool,
 2322        click_count: usize,
 2323        window: &mut Window,
 2324        cx: &mut Context<Self>,
 2325    ) {
 2326        if !self.focus_handle.is_focused(window) {
 2327            self.last_focused_descendant = None;
 2328            window.focus(&self.focus_handle);
 2329        }
 2330
 2331        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2332        let buffer = &display_map.buffer_snapshot;
 2333        let newest_selection = self.selections.newest_anchor().clone();
 2334        let position = display_map.clip_point(position, Bias::Left);
 2335
 2336        let start;
 2337        let end;
 2338        let mode;
 2339        let mut auto_scroll;
 2340        match click_count {
 2341            1 => {
 2342                start = buffer.anchor_before(position.to_point(&display_map));
 2343                end = start;
 2344                mode = SelectMode::Character;
 2345                auto_scroll = true;
 2346            }
 2347            2 => {
 2348                let range = movement::surrounding_word(&display_map, position);
 2349                start = buffer.anchor_before(range.start.to_point(&display_map));
 2350                end = buffer.anchor_before(range.end.to_point(&display_map));
 2351                mode = SelectMode::Word(start..end);
 2352                auto_scroll = true;
 2353            }
 2354            3 => {
 2355                let position = display_map
 2356                    .clip_point(position, Bias::Left)
 2357                    .to_point(&display_map);
 2358                let line_start = display_map.prev_line_boundary(position).0;
 2359                let next_line_start = buffer.clip_point(
 2360                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2361                    Bias::Left,
 2362                );
 2363                start = buffer.anchor_before(line_start);
 2364                end = buffer.anchor_before(next_line_start);
 2365                mode = SelectMode::Line(start..end);
 2366                auto_scroll = true;
 2367            }
 2368            _ => {
 2369                start = buffer.anchor_before(0);
 2370                end = buffer.anchor_before(buffer.len());
 2371                mode = SelectMode::All;
 2372                auto_scroll = false;
 2373            }
 2374        }
 2375        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2376
 2377        let point_to_delete: Option<usize> = {
 2378            let selected_points: Vec<Selection<Point>> =
 2379                self.selections.disjoint_in_range(start..end, cx);
 2380
 2381            if !add || click_count > 1 {
 2382                None
 2383            } else if !selected_points.is_empty() {
 2384                Some(selected_points[0].id)
 2385            } else {
 2386                let clicked_point_already_selected =
 2387                    self.selections.disjoint.iter().find(|selection| {
 2388                        selection.start.to_point(buffer) == start.to_point(buffer)
 2389                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2390                    });
 2391
 2392                clicked_point_already_selected.map(|selection| selection.id)
 2393            }
 2394        };
 2395
 2396        let selections_count = self.selections.count();
 2397
 2398        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2399            if let Some(point_to_delete) = point_to_delete {
 2400                s.delete(point_to_delete);
 2401
 2402                if selections_count == 1 {
 2403                    s.set_pending_anchor_range(start..end, mode);
 2404                }
 2405            } else {
 2406                if !add {
 2407                    s.clear_disjoint();
 2408                } else if click_count > 1 {
 2409                    s.delete(newest_selection.id)
 2410                }
 2411
 2412                s.set_pending_anchor_range(start..end, mode);
 2413            }
 2414        });
 2415    }
 2416
 2417    fn begin_columnar_selection(
 2418        &mut self,
 2419        position: DisplayPoint,
 2420        goal_column: u32,
 2421        reset: bool,
 2422        window: &mut Window,
 2423        cx: &mut Context<Self>,
 2424    ) {
 2425        if !self.focus_handle.is_focused(window) {
 2426            self.last_focused_descendant = None;
 2427            window.focus(&self.focus_handle);
 2428        }
 2429
 2430        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2431
 2432        if reset {
 2433            let pointer_position = display_map
 2434                .buffer_snapshot
 2435                .anchor_before(position.to_point(&display_map));
 2436
 2437            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2438                s.clear_disjoint();
 2439                s.set_pending_anchor_range(
 2440                    pointer_position..pointer_position,
 2441                    SelectMode::Character,
 2442                );
 2443            });
 2444        }
 2445
 2446        let tail = self.selections.newest::<Point>(cx).tail();
 2447        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2448
 2449        if !reset {
 2450            self.select_columns(
 2451                tail.to_display_point(&display_map),
 2452                position,
 2453                goal_column,
 2454                &display_map,
 2455                window,
 2456                cx,
 2457            );
 2458        }
 2459    }
 2460
 2461    fn update_selection(
 2462        &mut self,
 2463        position: DisplayPoint,
 2464        goal_column: u32,
 2465        scroll_delta: gpui::Point<f32>,
 2466        window: &mut Window,
 2467        cx: &mut Context<Self>,
 2468    ) {
 2469        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2470
 2471        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2472            let tail = tail.to_display_point(&display_map);
 2473            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2474        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2475            let buffer = self.buffer.read(cx).snapshot(cx);
 2476            let head;
 2477            let tail;
 2478            let mode = self.selections.pending_mode().unwrap();
 2479            match &mode {
 2480                SelectMode::Character => {
 2481                    head = position.to_point(&display_map);
 2482                    tail = pending.tail().to_point(&buffer);
 2483                }
 2484                SelectMode::Word(original_range) => {
 2485                    let original_display_range = original_range.start.to_display_point(&display_map)
 2486                        ..original_range.end.to_display_point(&display_map);
 2487                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2488                        ..original_display_range.end.to_point(&display_map);
 2489                    if movement::is_inside_word(&display_map, position)
 2490                        || original_display_range.contains(&position)
 2491                    {
 2492                        let word_range = movement::surrounding_word(&display_map, position);
 2493                        if word_range.start < original_display_range.start {
 2494                            head = word_range.start.to_point(&display_map);
 2495                        } else {
 2496                            head = word_range.end.to_point(&display_map);
 2497                        }
 2498                    } else {
 2499                        head = position.to_point(&display_map);
 2500                    }
 2501
 2502                    if head <= original_buffer_range.start {
 2503                        tail = original_buffer_range.end;
 2504                    } else {
 2505                        tail = original_buffer_range.start;
 2506                    }
 2507                }
 2508                SelectMode::Line(original_range) => {
 2509                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2510
 2511                    let position = display_map
 2512                        .clip_point(position, Bias::Left)
 2513                        .to_point(&display_map);
 2514                    let line_start = display_map.prev_line_boundary(position).0;
 2515                    let next_line_start = buffer.clip_point(
 2516                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2517                        Bias::Left,
 2518                    );
 2519
 2520                    if line_start < original_range.start {
 2521                        head = line_start
 2522                    } else {
 2523                        head = next_line_start
 2524                    }
 2525
 2526                    if head <= original_range.start {
 2527                        tail = original_range.end;
 2528                    } else {
 2529                        tail = original_range.start;
 2530                    }
 2531                }
 2532                SelectMode::All => {
 2533                    return;
 2534                }
 2535            };
 2536
 2537            if head < tail {
 2538                pending.start = buffer.anchor_before(head);
 2539                pending.end = buffer.anchor_before(tail);
 2540                pending.reversed = true;
 2541            } else {
 2542                pending.start = buffer.anchor_before(tail);
 2543                pending.end = buffer.anchor_before(head);
 2544                pending.reversed = false;
 2545            }
 2546
 2547            self.change_selections(None, window, cx, |s| {
 2548                s.set_pending(pending, mode);
 2549            });
 2550        } else {
 2551            log::error!("update_selection dispatched with no pending selection");
 2552            return;
 2553        }
 2554
 2555        self.apply_scroll_delta(scroll_delta, window, cx);
 2556        cx.notify();
 2557    }
 2558
 2559    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2560        self.columnar_selection_tail.take();
 2561        if self.selections.pending_anchor().is_some() {
 2562            let selections = self.selections.all::<usize>(cx);
 2563            self.change_selections(None, window, cx, |s| {
 2564                s.select(selections);
 2565                s.clear_pending();
 2566            });
 2567        }
 2568    }
 2569
 2570    fn select_columns(
 2571        &mut self,
 2572        tail: DisplayPoint,
 2573        head: DisplayPoint,
 2574        goal_column: u32,
 2575        display_map: &DisplaySnapshot,
 2576        window: &mut Window,
 2577        cx: &mut Context<Self>,
 2578    ) {
 2579        let start_row = cmp::min(tail.row(), head.row());
 2580        let end_row = cmp::max(tail.row(), head.row());
 2581        let start_column = cmp::min(tail.column(), goal_column);
 2582        let end_column = cmp::max(tail.column(), goal_column);
 2583        let reversed = start_column < tail.column();
 2584
 2585        let selection_ranges = (start_row.0..=end_row.0)
 2586            .map(DisplayRow)
 2587            .filter_map(|row| {
 2588                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2589                    let start = display_map
 2590                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2591                        .to_point(display_map);
 2592                    let end = display_map
 2593                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2594                        .to_point(display_map);
 2595                    if reversed {
 2596                        Some(end..start)
 2597                    } else {
 2598                        Some(start..end)
 2599                    }
 2600                } else {
 2601                    None
 2602                }
 2603            })
 2604            .collect::<Vec<_>>();
 2605
 2606        self.change_selections(None, window, cx, |s| {
 2607            s.select_ranges(selection_ranges);
 2608        });
 2609        cx.notify();
 2610    }
 2611
 2612    pub fn has_pending_nonempty_selection(&self) -> bool {
 2613        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2614            Some(Selection { start, end, .. }) => start != end,
 2615            None => false,
 2616        };
 2617
 2618        pending_nonempty_selection
 2619            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2620    }
 2621
 2622    pub fn has_pending_selection(&self) -> bool {
 2623        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2624    }
 2625
 2626    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2627        self.selection_mark_mode = false;
 2628
 2629        if self.clear_expanded_diff_hunks(cx) {
 2630            cx.notify();
 2631            return;
 2632        }
 2633        if self.dismiss_menus_and_popups(true, window, cx) {
 2634            return;
 2635        }
 2636
 2637        if self.mode == EditorMode::Full
 2638            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2639        {
 2640            return;
 2641        }
 2642
 2643        cx.propagate();
 2644    }
 2645
 2646    pub fn dismiss_menus_and_popups(
 2647        &mut self,
 2648        is_user_requested: bool,
 2649        window: &mut Window,
 2650        cx: &mut Context<Self>,
 2651    ) -> bool {
 2652        if self.take_rename(false, window, cx).is_some() {
 2653            return true;
 2654        }
 2655
 2656        if hide_hover(self, cx) {
 2657            return true;
 2658        }
 2659
 2660        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2661            return true;
 2662        }
 2663
 2664        if self.hide_context_menu(window, cx).is_some() {
 2665            return true;
 2666        }
 2667
 2668        if self.mouse_context_menu.take().is_some() {
 2669            return true;
 2670        }
 2671
 2672        if is_user_requested && self.discard_inline_completion(true, cx) {
 2673            return true;
 2674        }
 2675
 2676        if self.snippet_stack.pop().is_some() {
 2677            return true;
 2678        }
 2679
 2680        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2681            self.dismiss_diagnostics(cx);
 2682            return true;
 2683        }
 2684
 2685        false
 2686    }
 2687
 2688    fn linked_editing_ranges_for(
 2689        &self,
 2690        selection: Range<text::Anchor>,
 2691        cx: &App,
 2692    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2693        if self.linked_edit_ranges.is_empty() {
 2694            return None;
 2695        }
 2696        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2697            selection.end.buffer_id.and_then(|end_buffer_id| {
 2698                if selection.start.buffer_id != Some(end_buffer_id) {
 2699                    return None;
 2700                }
 2701                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2702                let snapshot = buffer.read(cx).snapshot();
 2703                self.linked_edit_ranges
 2704                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2705                    .map(|ranges| (ranges, snapshot, buffer))
 2706            })?;
 2707        use text::ToOffset as TO;
 2708        // find offset from the start of current range to current cursor position
 2709        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2710
 2711        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2712        let start_difference = start_offset - start_byte_offset;
 2713        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2714        let end_difference = end_offset - start_byte_offset;
 2715        // Current range has associated linked ranges.
 2716        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2717        for range in linked_ranges.iter() {
 2718            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2719            let end_offset = start_offset + end_difference;
 2720            let start_offset = start_offset + start_difference;
 2721            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2722                continue;
 2723            }
 2724            if self.selections.disjoint_anchor_ranges().any(|s| {
 2725                if s.start.buffer_id != selection.start.buffer_id
 2726                    || s.end.buffer_id != selection.end.buffer_id
 2727                {
 2728                    return false;
 2729                }
 2730                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2731                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2732            }) {
 2733                continue;
 2734            }
 2735            let start = buffer_snapshot.anchor_after(start_offset);
 2736            let end = buffer_snapshot.anchor_after(end_offset);
 2737            linked_edits
 2738                .entry(buffer.clone())
 2739                .or_default()
 2740                .push(start..end);
 2741        }
 2742        Some(linked_edits)
 2743    }
 2744
 2745    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2746        let text: Arc<str> = text.into();
 2747
 2748        if self.read_only(cx) {
 2749            return;
 2750        }
 2751
 2752        let selections = self.selections.all_adjusted(cx);
 2753        let mut bracket_inserted = false;
 2754        let mut edits = Vec::new();
 2755        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2756        let mut new_selections = Vec::with_capacity(selections.len());
 2757        let mut new_autoclose_regions = Vec::new();
 2758        let snapshot = self.buffer.read(cx).read(cx);
 2759
 2760        for (selection, autoclose_region) in
 2761            self.selections_with_autoclose_regions(selections, &snapshot)
 2762        {
 2763            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2764                // Determine if the inserted text matches the opening or closing
 2765                // bracket of any of this language's bracket pairs.
 2766                let mut bracket_pair = None;
 2767                let mut is_bracket_pair_start = false;
 2768                let mut is_bracket_pair_end = false;
 2769                if !text.is_empty() {
 2770                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2771                    //  and they are removing the character that triggered IME popup.
 2772                    for (pair, enabled) in scope.brackets() {
 2773                        if !pair.close && !pair.surround {
 2774                            continue;
 2775                        }
 2776
 2777                        if enabled && pair.start.ends_with(text.as_ref()) {
 2778                            let prefix_len = pair.start.len() - text.len();
 2779                            let preceding_text_matches_prefix = prefix_len == 0
 2780                                || (selection.start.column >= (prefix_len as u32)
 2781                                    && snapshot.contains_str_at(
 2782                                        Point::new(
 2783                                            selection.start.row,
 2784                                            selection.start.column - (prefix_len as u32),
 2785                                        ),
 2786                                        &pair.start[..prefix_len],
 2787                                    ));
 2788                            if preceding_text_matches_prefix {
 2789                                bracket_pair = Some(pair.clone());
 2790                                is_bracket_pair_start = true;
 2791                                break;
 2792                            }
 2793                        }
 2794                        if pair.end.as_str() == text.as_ref() {
 2795                            bracket_pair = Some(pair.clone());
 2796                            is_bracket_pair_end = true;
 2797                            break;
 2798                        }
 2799                    }
 2800                }
 2801
 2802                if let Some(bracket_pair) = bracket_pair {
 2803                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2804                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2805                    let auto_surround =
 2806                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2807                    if selection.is_empty() {
 2808                        if is_bracket_pair_start {
 2809                            // If the inserted text is a suffix of an opening bracket and the
 2810                            // selection is preceded by the rest of the opening bracket, then
 2811                            // insert the closing bracket.
 2812                            let following_text_allows_autoclose = snapshot
 2813                                .chars_at(selection.start)
 2814                                .next()
 2815                                .map_or(true, |c| scope.should_autoclose_before(c));
 2816
 2817                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2818                                && bracket_pair.start.len() == 1
 2819                            {
 2820                                let target = bracket_pair.start.chars().next().unwrap();
 2821                                let current_line_count = snapshot
 2822                                    .reversed_chars_at(selection.start)
 2823                                    .take_while(|&c| c != '\n')
 2824                                    .filter(|&c| c == target)
 2825                                    .count();
 2826                                current_line_count % 2 == 1
 2827                            } else {
 2828                                false
 2829                            };
 2830
 2831                            if autoclose
 2832                                && bracket_pair.close
 2833                                && following_text_allows_autoclose
 2834                                && !is_closing_quote
 2835                            {
 2836                                let anchor = snapshot.anchor_before(selection.end);
 2837                                new_selections.push((selection.map(|_| anchor), text.len()));
 2838                                new_autoclose_regions.push((
 2839                                    anchor,
 2840                                    text.len(),
 2841                                    selection.id,
 2842                                    bracket_pair.clone(),
 2843                                ));
 2844                                edits.push((
 2845                                    selection.range(),
 2846                                    format!("{}{}", text, bracket_pair.end).into(),
 2847                                ));
 2848                                bracket_inserted = true;
 2849                                continue;
 2850                            }
 2851                        }
 2852
 2853                        if let Some(region) = autoclose_region {
 2854                            // If the selection is followed by an auto-inserted closing bracket,
 2855                            // then don't insert that closing bracket again; just move the selection
 2856                            // past the closing bracket.
 2857                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2858                                && text.as_ref() == region.pair.end.as_str();
 2859                            if should_skip {
 2860                                let anchor = snapshot.anchor_after(selection.end);
 2861                                new_selections
 2862                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2863                                continue;
 2864                            }
 2865                        }
 2866
 2867                        let always_treat_brackets_as_autoclosed = snapshot
 2868                            .settings_at(selection.start, cx)
 2869                            .always_treat_brackets_as_autoclosed;
 2870                        if always_treat_brackets_as_autoclosed
 2871                            && is_bracket_pair_end
 2872                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2873                        {
 2874                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2875                            // and the inserted text is a closing bracket and the selection is followed
 2876                            // by the closing bracket then move the selection past the closing bracket.
 2877                            let anchor = snapshot.anchor_after(selection.end);
 2878                            new_selections.push((selection.map(|_| anchor), text.len()));
 2879                            continue;
 2880                        }
 2881                    }
 2882                    // If an opening bracket is 1 character long and is typed while
 2883                    // text is selected, then surround that text with the bracket pair.
 2884                    else if auto_surround
 2885                        && bracket_pair.surround
 2886                        && is_bracket_pair_start
 2887                        && bracket_pair.start.chars().count() == 1
 2888                    {
 2889                        edits.push((selection.start..selection.start, text.clone()));
 2890                        edits.push((
 2891                            selection.end..selection.end,
 2892                            bracket_pair.end.as_str().into(),
 2893                        ));
 2894                        bracket_inserted = true;
 2895                        new_selections.push((
 2896                            Selection {
 2897                                id: selection.id,
 2898                                start: snapshot.anchor_after(selection.start),
 2899                                end: snapshot.anchor_before(selection.end),
 2900                                reversed: selection.reversed,
 2901                                goal: selection.goal,
 2902                            },
 2903                            0,
 2904                        ));
 2905                        continue;
 2906                    }
 2907                }
 2908            }
 2909
 2910            if self.auto_replace_emoji_shortcode
 2911                && selection.is_empty()
 2912                && text.as_ref().ends_with(':')
 2913            {
 2914                if let Some(possible_emoji_short_code) =
 2915                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2916                {
 2917                    if !possible_emoji_short_code.is_empty() {
 2918                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2919                            let emoji_shortcode_start = Point::new(
 2920                                selection.start.row,
 2921                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2922                            );
 2923
 2924                            // Remove shortcode from buffer
 2925                            edits.push((
 2926                                emoji_shortcode_start..selection.start,
 2927                                "".to_string().into(),
 2928                            ));
 2929                            new_selections.push((
 2930                                Selection {
 2931                                    id: selection.id,
 2932                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2933                                    end: snapshot.anchor_before(selection.start),
 2934                                    reversed: selection.reversed,
 2935                                    goal: selection.goal,
 2936                                },
 2937                                0,
 2938                            ));
 2939
 2940                            // Insert emoji
 2941                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2942                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2943                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2944
 2945                            continue;
 2946                        }
 2947                    }
 2948                }
 2949            }
 2950
 2951            // If not handling any auto-close operation, then just replace the selected
 2952            // text with the given input and move the selection to the end of the
 2953            // newly inserted text.
 2954            let anchor = snapshot.anchor_after(selection.end);
 2955            if !self.linked_edit_ranges.is_empty() {
 2956                let start_anchor = snapshot.anchor_before(selection.start);
 2957
 2958                let is_word_char = text.chars().next().map_or(true, |char| {
 2959                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2960                    classifier.is_word(char)
 2961                });
 2962
 2963                if is_word_char {
 2964                    if let Some(ranges) = self
 2965                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2966                    {
 2967                        for (buffer, edits) in ranges {
 2968                            linked_edits
 2969                                .entry(buffer.clone())
 2970                                .or_default()
 2971                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2972                        }
 2973                    }
 2974                }
 2975            }
 2976
 2977            new_selections.push((selection.map(|_| anchor), 0));
 2978            edits.push((selection.start..selection.end, text.clone()));
 2979        }
 2980
 2981        drop(snapshot);
 2982
 2983        self.transact(window, cx, |this, window, cx| {
 2984            this.buffer.update(cx, |buffer, cx| {
 2985                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2986            });
 2987            for (buffer, edits) in linked_edits {
 2988                buffer.update(cx, |buffer, cx| {
 2989                    let snapshot = buffer.snapshot();
 2990                    let edits = edits
 2991                        .into_iter()
 2992                        .map(|(range, text)| {
 2993                            use text::ToPoint as TP;
 2994                            let end_point = TP::to_point(&range.end, &snapshot);
 2995                            let start_point = TP::to_point(&range.start, &snapshot);
 2996                            (start_point..end_point, text)
 2997                        })
 2998                        .sorted_by_key(|(range, _)| range.start)
 2999                        .collect::<Vec<_>>();
 3000                    buffer.edit(edits, None, cx);
 3001                })
 3002            }
 3003            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3004            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3005            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3006            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3007                .zip(new_selection_deltas)
 3008                .map(|(selection, delta)| Selection {
 3009                    id: selection.id,
 3010                    start: selection.start + delta,
 3011                    end: selection.end + delta,
 3012                    reversed: selection.reversed,
 3013                    goal: SelectionGoal::None,
 3014                })
 3015                .collect::<Vec<_>>();
 3016
 3017            let mut i = 0;
 3018            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3019                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3020                let start = map.buffer_snapshot.anchor_before(position);
 3021                let end = map.buffer_snapshot.anchor_after(position);
 3022                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3023                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3024                        Ordering::Less => i += 1,
 3025                        Ordering::Greater => break,
 3026                        Ordering::Equal => {
 3027                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3028                                Ordering::Less => i += 1,
 3029                                Ordering::Equal => break,
 3030                                Ordering::Greater => break,
 3031                            }
 3032                        }
 3033                    }
 3034                }
 3035                this.autoclose_regions.insert(
 3036                    i,
 3037                    AutocloseRegion {
 3038                        selection_id,
 3039                        range: start..end,
 3040                        pair,
 3041                    },
 3042                );
 3043            }
 3044
 3045            let had_active_inline_completion = this.has_active_inline_completion();
 3046            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3047                s.select(new_selections)
 3048            });
 3049
 3050            if !bracket_inserted {
 3051                if let Some(on_type_format_task) =
 3052                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3053                {
 3054                    on_type_format_task.detach_and_log_err(cx);
 3055                }
 3056            }
 3057
 3058            let editor_settings = EditorSettings::get_global(cx);
 3059            if bracket_inserted
 3060                && (editor_settings.auto_signature_help
 3061                    || editor_settings.show_signature_help_after_edits)
 3062            {
 3063                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3064            }
 3065
 3066            let trigger_in_words =
 3067                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3068            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3069            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3070            this.refresh_inline_completion(true, false, window, cx);
 3071        });
 3072    }
 3073
 3074    fn find_possible_emoji_shortcode_at_position(
 3075        snapshot: &MultiBufferSnapshot,
 3076        position: Point,
 3077    ) -> Option<String> {
 3078        let mut chars = Vec::new();
 3079        let mut found_colon = false;
 3080        for char in snapshot.reversed_chars_at(position).take(100) {
 3081            // Found a possible emoji shortcode in the middle of the buffer
 3082            if found_colon {
 3083                if char.is_whitespace() {
 3084                    chars.reverse();
 3085                    return Some(chars.iter().collect());
 3086                }
 3087                // If the previous character is not a whitespace, we are in the middle of a word
 3088                // and we only want to complete the shortcode if the word is made up of other emojis
 3089                let mut containing_word = String::new();
 3090                for ch in snapshot
 3091                    .reversed_chars_at(position)
 3092                    .skip(chars.len() + 1)
 3093                    .take(100)
 3094                {
 3095                    if ch.is_whitespace() {
 3096                        break;
 3097                    }
 3098                    containing_word.push(ch);
 3099                }
 3100                let containing_word = containing_word.chars().rev().collect::<String>();
 3101                if util::word_consists_of_emojis(containing_word.as_str()) {
 3102                    chars.reverse();
 3103                    return Some(chars.iter().collect());
 3104                }
 3105            }
 3106
 3107            if char.is_whitespace() || !char.is_ascii() {
 3108                return None;
 3109            }
 3110            if char == ':' {
 3111                found_colon = true;
 3112            } else {
 3113                chars.push(char);
 3114            }
 3115        }
 3116        // Found a possible emoji shortcode at the beginning of the buffer
 3117        chars.reverse();
 3118        Some(chars.iter().collect())
 3119    }
 3120
 3121    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3122        self.transact(window, cx, |this, window, cx| {
 3123            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3124                let selections = this.selections.all::<usize>(cx);
 3125                let multi_buffer = this.buffer.read(cx);
 3126                let buffer = multi_buffer.snapshot(cx);
 3127                selections
 3128                    .iter()
 3129                    .map(|selection| {
 3130                        let start_point = selection.start.to_point(&buffer);
 3131                        let mut indent =
 3132                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3133                        indent.len = cmp::min(indent.len, start_point.column);
 3134                        let start = selection.start;
 3135                        let end = selection.end;
 3136                        let selection_is_empty = start == end;
 3137                        let language_scope = buffer.language_scope_at(start);
 3138                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3139                            &language_scope
 3140                        {
 3141                            let leading_whitespace_len = buffer
 3142                                .reversed_chars_at(start)
 3143                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3144                                .map(|c| c.len_utf8())
 3145                                .sum::<usize>();
 3146
 3147                            let trailing_whitespace_len = buffer
 3148                                .chars_at(end)
 3149                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3150                                .map(|c| c.len_utf8())
 3151                                .sum::<usize>();
 3152
 3153                            let insert_extra_newline =
 3154                                language.brackets().any(|(pair, enabled)| {
 3155                                    let pair_start = pair.start.trim_end();
 3156                                    let pair_end = pair.end.trim_start();
 3157
 3158                                    enabled
 3159                                        && pair.newline
 3160                                        && buffer.contains_str_at(
 3161                                            end + trailing_whitespace_len,
 3162                                            pair_end,
 3163                                        )
 3164                                        && buffer.contains_str_at(
 3165                                            (start - leading_whitespace_len)
 3166                                                .saturating_sub(pair_start.len()),
 3167                                            pair_start,
 3168                                        )
 3169                                });
 3170
 3171                            // Comment extension on newline is allowed only for cursor selections
 3172                            let comment_delimiter = maybe!({
 3173                                if !selection_is_empty {
 3174                                    return None;
 3175                                }
 3176
 3177                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3178                                    return None;
 3179                                }
 3180
 3181                                let delimiters = language.line_comment_prefixes();
 3182                                let max_len_of_delimiter =
 3183                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3184                                let (snapshot, range) =
 3185                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3186
 3187                                let mut index_of_first_non_whitespace = 0;
 3188                                let comment_candidate = snapshot
 3189                                    .chars_for_range(range)
 3190                                    .skip_while(|c| {
 3191                                        let should_skip = c.is_whitespace();
 3192                                        if should_skip {
 3193                                            index_of_first_non_whitespace += 1;
 3194                                        }
 3195                                        should_skip
 3196                                    })
 3197                                    .take(max_len_of_delimiter)
 3198                                    .collect::<String>();
 3199                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3200                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3201                                })?;
 3202                                let cursor_is_placed_after_comment_marker =
 3203                                    index_of_first_non_whitespace + comment_prefix.len()
 3204                                        <= start_point.column as usize;
 3205                                if cursor_is_placed_after_comment_marker {
 3206                                    Some(comment_prefix.clone())
 3207                                } else {
 3208                                    None
 3209                                }
 3210                            });
 3211                            (comment_delimiter, insert_extra_newline)
 3212                        } else {
 3213                            (None, false)
 3214                        };
 3215
 3216                        let capacity_for_delimiter = comment_delimiter
 3217                            .as_deref()
 3218                            .map(str::len)
 3219                            .unwrap_or_default();
 3220                        let mut new_text =
 3221                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3222                        new_text.push('\n');
 3223                        new_text.extend(indent.chars());
 3224                        if let Some(delimiter) = &comment_delimiter {
 3225                            new_text.push_str(delimiter);
 3226                        }
 3227                        if insert_extra_newline {
 3228                            new_text = new_text.repeat(2);
 3229                        }
 3230
 3231                        let anchor = buffer.anchor_after(end);
 3232                        let new_selection = selection.map(|_| anchor);
 3233                        (
 3234                            (start..end, new_text),
 3235                            (insert_extra_newline, new_selection),
 3236                        )
 3237                    })
 3238                    .unzip()
 3239            };
 3240
 3241            this.edit_with_autoindent(edits, cx);
 3242            let buffer = this.buffer.read(cx).snapshot(cx);
 3243            let new_selections = selection_fixup_info
 3244                .into_iter()
 3245                .map(|(extra_newline_inserted, new_selection)| {
 3246                    let mut cursor = new_selection.end.to_point(&buffer);
 3247                    if extra_newline_inserted {
 3248                        cursor.row -= 1;
 3249                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3250                    }
 3251                    new_selection.map(|_| cursor)
 3252                })
 3253                .collect();
 3254
 3255            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3256                s.select(new_selections)
 3257            });
 3258            this.refresh_inline_completion(true, false, window, cx);
 3259        });
 3260    }
 3261
 3262    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3263        let buffer = self.buffer.read(cx);
 3264        let snapshot = buffer.snapshot(cx);
 3265
 3266        let mut edits = Vec::new();
 3267        let mut rows = Vec::new();
 3268
 3269        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3270            let cursor = selection.head();
 3271            let row = cursor.row;
 3272
 3273            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3274
 3275            let newline = "\n".to_string();
 3276            edits.push((start_of_line..start_of_line, newline));
 3277
 3278            rows.push(row + rows_inserted as u32);
 3279        }
 3280
 3281        self.transact(window, cx, |editor, window, cx| {
 3282            editor.edit(edits, cx);
 3283
 3284            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3285                let mut index = 0;
 3286                s.move_cursors_with(|map, _, _| {
 3287                    let row = rows[index];
 3288                    index += 1;
 3289
 3290                    let point = Point::new(row, 0);
 3291                    let boundary = map.next_line_boundary(point).1;
 3292                    let clipped = map.clip_point(boundary, Bias::Left);
 3293
 3294                    (clipped, SelectionGoal::None)
 3295                });
 3296            });
 3297
 3298            let mut indent_edits = Vec::new();
 3299            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3300            for row in rows {
 3301                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3302                for (row, indent) in indents {
 3303                    if indent.len == 0 {
 3304                        continue;
 3305                    }
 3306
 3307                    let text = match indent.kind {
 3308                        IndentKind::Space => " ".repeat(indent.len as usize),
 3309                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3310                    };
 3311                    let point = Point::new(row.0, 0);
 3312                    indent_edits.push((point..point, text));
 3313                }
 3314            }
 3315            editor.edit(indent_edits, cx);
 3316        });
 3317    }
 3318
 3319    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3320        let buffer = self.buffer.read(cx);
 3321        let snapshot = buffer.snapshot(cx);
 3322
 3323        let mut edits = Vec::new();
 3324        let mut rows = Vec::new();
 3325        let mut rows_inserted = 0;
 3326
 3327        for selection in self.selections.all_adjusted(cx) {
 3328            let cursor = selection.head();
 3329            let row = cursor.row;
 3330
 3331            let point = Point::new(row + 1, 0);
 3332            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3333
 3334            let newline = "\n".to_string();
 3335            edits.push((start_of_line..start_of_line, newline));
 3336
 3337            rows_inserted += 1;
 3338            rows.push(row + rows_inserted);
 3339        }
 3340
 3341        self.transact(window, cx, |editor, window, cx| {
 3342            editor.edit(edits, cx);
 3343
 3344            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3345                let mut index = 0;
 3346                s.move_cursors_with(|map, _, _| {
 3347                    let row = rows[index];
 3348                    index += 1;
 3349
 3350                    let point = Point::new(row, 0);
 3351                    let boundary = map.next_line_boundary(point).1;
 3352                    let clipped = map.clip_point(boundary, Bias::Left);
 3353
 3354                    (clipped, SelectionGoal::None)
 3355                });
 3356            });
 3357
 3358            let mut indent_edits = Vec::new();
 3359            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3360            for row in rows {
 3361                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3362                for (row, indent) in indents {
 3363                    if indent.len == 0 {
 3364                        continue;
 3365                    }
 3366
 3367                    let text = match indent.kind {
 3368                        IndentKind::Space => " ".repeat(indent.len as usize),
 3369                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3370                    };
 3371                    let point = Point::new(row.0, 0);
 3372                    indent_edits.push((point..point, text));
 3373                }
 3374            }
 3375            editor.edit(indent_edits, cx);
 3376        });
 3377    }
 3378
 3379    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3380        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3381            original_indent_columns: Vec::new(),
 3382        });
 3383        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3384    }
 3385
 3386    fn insert_with_autoindent_mode(
 3387        &mut self,
 3388        text: &str,
 3389        autoindent_mode: Option<AutoindentMode>,
 3390        window: &mut Window,
 3391        cx: &mut Context<Self>,
 3392    ) {
 3393        if self.read_only(cx) {
 3394            return;
 3395        }
 3396
 3397        let text: Arc<str> = text.into();
 3398        self.transact(window, cx, |this, window, cx| {
 3399            let old_selections = this.selections.all_adjusted(cx);
 3400            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3401                let anchors = {
 3402                    let snapshot = buffer.read(cx);
 3403                    old_selections
 3404                        .iter()
 3405                        .map(|s| {
 3406                            let anchor = snapshot.anchor_after(s.head());
 3407                            s.map(|_| anchor)
 3408                        })
 3409                        .collect::<Vec<_>>()
 3410                };
 3411                buffer.edit(
 3412                    old_selections
 3413                        .iter()
 3414                        .map(|s| (s.start..s.end, text.clone())),
 3415                    autoindent_mode,
 3416                    cx,
 3417                );
 3418                anchors
 3419            });
 3420
 3421            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3422                s.select_anchors(selection_anchors);
 3423            });
 3424
 3425            cx.notify();
 3426        });
 3427    }
 3428
 3429    fn trigger_completion_on_input(
 3430        &mut self,
 3431        text: &str,
 3432        trigger_in_words: bool,
 3433        window: &mut Window,
 3434        cx: &mut Context<Self>,
 3435    ) {
 3436        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3437            self.show_completions(
 3438                &ShowCompletions {
 3439                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3440                },
 3441                window,
 3442                cx,
 3443            );
 3444        } else {
 3445            self.hide_context_menu(window, cx);
 3446        }
 3447    }
 3448
 3449    fn is_completion_trigger(
 3450        &self,
 3451        text: &str,
 3452        trigger_in_words: bool,
 3453        cx: &mut Context<Self>,
 3454    ) -> bool {
 3455        let position = self.selections.newest_anchor().head();
 3456        let multibuffer = self.buffer.read(cx);
 3457        let Some(buffer) = position
 3458            .buffer_id
 3459            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3460        else {
 3461            return false;
 3462        };
 3463
 3464        if let Some(completion_provider) = &self.completion_provider {
 3465            completion_provider.is_completion_trigger(
 3466                &buffer,
 3467                position.text_anchor,
 3468                text,
 3469                trigger_in_words,
 3470                cx,
 3471            )
 3472        } else {
 3473            false
 3474        }
 3475    }
 3476
 3477    /// If any empty selections is touching the start of its innermost containing autoclose
 3478    /// region, expand it to select the brackets.
 3479    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3480        let selections = self.selections.all::<usize>(cx);
 3481        let buffer = self.buffer.read(cx).read(cx);
 3482        let new_selections = self
 3483            .selections_with_autoclose_regions(selections, &buffer)
 3484            .map(|(mut selection, region)| {
 3485                if !selection.is_empty() {
 3486                    return selection;
 3487                }
 3488
 3489                if let Some(region) = region {
 3490                    let mut range = region.range.to_offset(&buffer);
 3491                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3492                        range.start -= region.pair.start.len();
 3493                        if buffer.contains_str_at(range.start, &region.pair.start)
 3494                            && buffer.contains_str_at(range.end, &region.pair.end)
 3495                        {
 3496                            range.end += region.pair.end.len();
 3497                            selection.start = range.start;
 3498                            selection.end = range.end;
 3499
 3500                            return selection;
 3501                        }
 3502                    }
 3503                }
 3504
 3505                let always_treat_brackets_as_autoclosed = buffer
 3506                    .settings_at(selection.start, cx)
 3507                    .always_treat_brackets_as_autoclosed;
 3508
 3509                if !always_treat_brackets_as_autoclosed {
 3510                    return selection;
 3511                }
 3512
 3513                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3514                    for (pair, enabled) in scope.brackets() {
 3515                        if !enabled || !pair.close {
 3516                            continue;
 3517                        }
 3518
 3519                        if buffer.contains_str_at(selection.start, &pair.end) {
 3520                            let pair_start_len = pair.start.len();
 3521                            if buffer.contains_str_at(
 3522                                selection.start.saturating_sub(pair_start_len),
 3523                                &pair.start,
 3524                            ) {
 3525                                selection.start -= pair_start_len;
 3526                                selection.end += pair.end.len();
 3527
 3528                                return selection;
 3529                            }
 3530                        }
 3531                    }
 3532                }
 3533
 3534                selection
 3535            })
 3536            .collect();
 3537
 3538        drop(buffer);
 3539        self.change_selections(None, window, cx, |selections| {
 3540            selections.select(new_selections)
 3541        });
 3542    }
 3543
 3544    /// Iterate the given selections, and for each one, find the smallest surrounding
 3545    /// autoclose region. This uses the ordering of the selections and the autoclose
 3546    /// regions to avoid repeated comparisons.
 3547    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3548        &'a self,
 3549        selections: impl IntoIterator<Item = Selection<D>>,
 3550        buffer: &'a MultiBufferSnapshot,
 3551    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3552        let mut i = 0;
 3553        let mut regions = self.autoclose_regions.as_slice();
 3554        selections.into_iter().map(move |selection| {
 3555            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3556
 3557            let mut enclosing = None;
 3558            while let Some(pair_state) = regions.get(i) {
 3559                if pair_state.range.end.to_offset(buffer) < range.start {
 3560                    regions = &regions[i + 1..];
 3561                    i = 0;
 3562                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3563                    break;
 3564                } else {
 3565                    if pair_state.selection_id == selection.id {
 3566                        enclosing = Some(pair_state);
 3567                    }
 3568                    i += 1;
 3569                }
 3570            }
 3571
 3572            (selection, enclosing)
 3573        })
 3574    }
 3575
 3576    /// Remove any autoclose regions that no longer contain their selection.
 3577    fn invalidate_autoclose_regions(
 3578        &mut self,
 3579        mut selections: &[Selection<Anchor>],
 3580        buffer: &MultiBufferSnapshot,
 3581    ) {
 3582        self.autoclose_regions.retain(|state| {
 3583            let mut i = 0;
 3584            while let Some(selection) = selections.get(i) {
 3585                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3586                    selections = &selections[1..];
 3587                    continue;
 3588                }
 3589                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3590                    break;
 3591                }
 3592                if selection.id == state.selection_id {
 3593                    return true;
 3594                } else {
 3595                    i += 1;
 3596                }
 3597            }
 3598            false
 3599        });
 3600    }
 3601
 3602    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3603        let offset = position.to_offset(buffer);
 3604        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3605        if offset > word_range.start && kind == Some(CharKind::Word) {
 3606            Some(
 3607                buffer
 3608                    .text_for_range(word_range.start..offset)
 3609                    .collect::<String>(),
 3610            )
 3611        } else {
 3612            None
 3613        }
 3614    }
 3615
 3616    pub fn toggle_inlay_hints(
 3617        &mut self,
 3618        _: &ToggleInlayHints,
 3619        _: &mut Window,
 3620        cx: &mut Context<Self>,
 3621    ) {
 3622        self.refresh_inlay_hints(
 3623            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3624            cx,
 3625        );
 3626    }
 3627
 3628    pub fn inlay_hints_enabled(&self) -> bool {
 3629        self.inlay_hint_cache.enabled
 3630    }
 3631
 3632    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3633        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3634            return;
 3635        }
 3636
 3637        let reason_description = reason.description();
 3638        let ignore_debounce = matches!(
 3639            reason,
 3640            InlayHintRefreshReason::SettingsChange(_)
 3641                | InlayHintRefreshReason::Toggle(_)
 3642                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3643        );
 3644        let (invalidate_cache, required_languages) = match reason {
 3645            InlayHintRefreshReason::Toggle(enabled) => {
 3646                self.inlay_hint_cache.enabled = enabled;
 3647                if enabled {
 3648                    (InvalidationStrategy::RefreshRequested, None)
 3649                } else {
 3650                    self.inlay_hint_cache.clear();
 3651                    self.splice_inlays(
 3652                        &self
 3653                            .visible_inlay_hints(cx)
 3654                            .iter()
 3655                            .map(|inlay| inlay.id)
 3656                            .collect::<Vec<InlayId>>(),
 3657                        Vec::new(),
 3658                        cx,
 3659                    );
 3660                    return;
 3661                }
 3662            }
 3663            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3664                match self.inlay_hint_cache.update_settings(
 3665                    &self.buffer,
 3666                    new_settings,
 3667                    self.visible_inlay_hints(cx),
 3668                    cx,
 3669                ) {
 3670                    ControlFlow::Break(Some(InlaySplice {
 3671                        to_remove,
 3672                        to_insert,
 3673                    })) => {
 3674                        self.splice_inlays(&to_remove, to_insert, cx);
 3675                        return;
 3676                    }
 3677                    ControlFlow::Break(None) => return,
 3678                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3679                }
 3680            }
 3681            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3682                if let Some(InlaySplice {
 3683                    to_remove,
 3684                    to_insert,
 3685                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3686                {
 3687                    self.splice_inlays(&to_remove, to_insert, cx);
 3688                }
 3689                return;
 3690            }
 3691            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3692            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3693                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3694            }
 3695            InlayHintRefreshReason::RefreshRequested => {
 3696                (InvalidationStrategy::RefreshRequested, None)
 3697            }
 3698        };
 3699
 3700        if let Some(InlaySplice {
 3701            to_remove,
 3702            to_insert,
 3703        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3704            reason_description,
 3705            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3706            invalidate_cache,
 3707            ignore_debounce,
 3708            cx,
 3709        ) {
 3710            self.splice_inlays(&to_remove, to_insert, cx);
 3711        }
 3712    }
 3713
 3714    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3715        self.display_map
 3716            .read(cx)
 3717            .current_inlays()
 3718            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3719            .cloned()
 3720            .collect()
 3721    }
 3722
 3723    pub fn excerpts_for_inlay_hints_query(
 3724        &self,
 3725        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3726        cx: &mut Context<Editor>,
 3727    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3728        let Some(project) = self.project.as_ref() else {
 3729            return HashMap::default();
 3730        };
 3731        let project = project.read(cx);
 3732        let multi_buffer = self.buffer().read(cx);
 3733        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3734        let multi_buffer_visible_start = self
 3735            .scroll_manager
 3736            .anchor()
 3737            .anchor
 3738            .to_point(&multi_buffer_snapshot);
 3739        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3740            multi_buffer_visible_start
 3741                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3742            Bias::Left,
 3743        );
 3744        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3745        multi_buffer_snapshot
 3746            .range_to_buffer_ranges(multi_buffer_visible_range)
 3747            .into_iter()
 3748            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3749            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3750                let buffer_file = project::File::from_dyn(buffer.file())?;
 3751                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3752                let worktree_entry = buffer_worktree
 3753                    .read(cx)
 3754                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3755                if worktree_entry.is_ignored {
 3756                    return None;
 3757                }
 3758
 3759                let language = buffer.language()?;
 3760                if let Some(restrict_to_languages) = restrict_to_languages {
 3761                    if !restrict_to_languages.contains(language) {
 3762                        return None;
 3763                    }
 3764                }
 3765                Some((
 3766                    excerpt_id,
 3767                    (
 3768                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3769                        buffer.version().clone(),
 3770                        excerpt_visible_range,
 3771                    ),
 3772                ))
 3773            })
 3774            .collect()
 3775    }
 3776
 3777    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3778        TextLayoutDetails {
 3779            text_system: window.text_system().clone(),
 3780            editor_style: self.style.clone().unwrap(),
 3781            rem_size: window.rem_size(),
 3782            scroll_anchor: self.scroll_manager.anchor(),
 3783            visible_rows: self.visible_line_count(),
 3784            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3785        }
 3786    }
 3787
 3788    pub fn splice_inlays(
 3789        &self,
 3790        to_remove: &[InlayId],
 3791        to_insert: Vec<Inlay>,
 3792        cx: &mut Context<Self>,
 3793    ) {
 3794        self.display_map.update(cx, |display_map, cx| {
 3795            display_map.splice_inlays(to_remove, to_insert, cx)
 3796        });
 3797        cx.notify();
 3798    }
 3799
 3800    fn trigger_on_type_formatting(
 3801        &self,
 3802        input: String,
 3803        window: &mut Window,
 3804        cx: &mut Context<Self>,
 3805    ) -> Option<Task<Result<()>>> {
 3806        if input.len() != 1 {
 3807            return None;
 3808        }
 3809
 3810        let project = self.project.as_ref()?;
 3811        let position = self.selections.newest_anchor().head();
 3812        let (buffer, buffer_position) = self
 3813            .buffer
 3814            .read(cx)
 3815            .text_anchor_for_position(position, cx)?;
 3816
 3817        let settings = language_settings::language_settings(
 3818            buffer
 3819                .read(cx)
 3820                .language_at(buffer_position)
 3821                .map(|l| l.name()),
 3822            buffer.read(cx).file(),
 3823            cx,
 3824        );
 3825        if !settings.use_on_type_format {
 3826            return None;
 3827        }
 3828
 3829        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3830        // hence we do LSP request & edit on host side only — add formats to host's history.
 3831        let push_to_lsp_host_history = true;
 3832        // If this is not the host, append its history with new edits.
 3833        let push_to_client_history = project.read(cx).is_via_collab();
 3834
 3835        let on_type_formatting = project.update(cx, |project, cx| {
 3836            project.on_type_format(
 3837                buffer.clone(),
 3838                buffer_position,
 3839                input,
 3840                push_to_lsp_host_history,
 3841                cx,
 3842            )
 3843        });
 3844        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3845            if let Some(transaction) = on_type_formatting.await? {
 3846                if push_to_client_history {
 3847                    buffer
 3848                        .update(&mut cx, |buffer, _| {
 3849                            buffer.push_transaction(transaction, Instant::now());
 3850                        })
 3851                        .ok();
 3852                }
 3853                editor.update(&mut cx, |editor, cx| {
 3854                    editor.refresh_document_highlights(cx);
 3855                })?;
 3856            }
 3857            Ok(())
 3858        }))
 3859    }
 3860
 3861    pub fn show_completions(
 3862        &mut self,
 3863        options: &ShowCompletions,
 3864        window: &mut Window,
 3865        cx: &mut Context<Self>,
 3866    ) {
 3867        if self.pending_rename.is_some() {
 3868            return;
 3869        }
 3870
 3871        let Some(provider) = self.completion_provider.as_ref() else {
 3872            return;
 3873        };
 3874
 3875        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3876            return;
 3877        }
 3878
 3879        let position = self.selections.newest_anchor().head();
 3880        if position.diff_base_anchor.is_some() {
 3881            return;
 3882        }
 3883        let (buffer, buffer_position) =
 3884            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3885                output
 3886            } else {
 3887                return;
 3888            };
 3889        let show_completion_documentation = buffer
 3890            .read(cx)
 3891            .snapshot()
 3892            .settings_at(buffer_position, cx)
 3893            .show_completion_documentation;
 3894
 3895        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3896
 3897        let trigger_kind = match &options.trigger {
 3898            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3899                CompletionTriggerKind::TRIGGER_CHARACTER
 3900            }
 3901            _ => CompletionTriggerKind::INVOKED,
 3902        };
 3903        let completion_context = CompletionContext {
 3904            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3905                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3906                    Some(String::from(trigger))
 3907                } else {
 3908                    None
 3909                }
 3910            }),
 3911            trigger_kind,
 3912        };
 3913        let completions =
 3914            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3915        let sort_completions = provider.sort_completions();
 3916
 3917        let id = post_inc(&mut self.next_completion_id);
 3918        let task = cx.spawn_in(window, |editor, mut cx| {
 3919            async move {
 3920                editor.update(&mut cx, |this, _| {
 3921                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3922                })?;
 3923                let completions = completions.await.log_err();
 3924                let menu = if let Some(completions) = completions {
 3925                    let mut menu = CompletionsMenu::new(
 3926                        id,
 3927                        sort_completions,
 3928                        show_completion_documentation,
 3929                        position,
 3930                        buffer.clone(),
 3931                        completions.into(),
 3932                    );
 3933
 3934                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3935                        .await;
 3936
 3937                    menu.visible().then_some(menu)
 3938                } else {
 3939                    None
 3940                };
 3941
 3942                editor.update_in(&mut cx, |editor, window, cx| {
 3943                    match editor.context_menu.borrow().as_ref() {
 3944                        None => {}
 3945                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3946                            if prev_menu.id > id {
 3947                                return;
 3948                            }
 3949                        }
 3950                        _ => return,
 3951                    }
 3952
 3953                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3954                        let mut menu = menu.unwrap();
 3955                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3956
 3957                        *editor.context_menu.borrow_mut() =
 3958                            Some(CodeContextMenu::Completions(menu));
 3959
 3960                        if editor.show_edit_predictions_in_menu() {
 3961                            editor.update_visible_inline_completion(window, cx);
 3962                        } else {
 3963                            editor.discard_inline_completion(false, cx);
 3964                        }
 3965
 3966                        cx.notify();
 3967                    } else if editor.completion_tasks.len() <= 1 {
 3968                        // If there are no more completion tasks and the last menu was
 3969                        // empty, we should hide it.
 3970                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3971                        // If it was already hidden and we don't show inline
 3972                        // completions in the menu, we should also show the
 3973                        // inline-completion when available.
 3974                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3975                            editor.update_visible_inline_completion(window, cx);
 3976                        }
 3977                    }
 3978                })?;
 3979
 3980                Ok::<_, anyhow::Error>(())
 3981            }
 3982            .log_err()
 3983        });
 3984
 3985        self.completion_tasks.push((id, task));
 3986    }
 3987
 3988    pub fn confirm_completion(
 3989        &mut self,
 3990        action: &ConfirmCompletion,
 3991        window: &mut Window,
 3992        cx: &mut Context<Self>,
 3993    ) -> Option<Task<Result<()>>> {
 3994        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3995    }
 3996
 3997    pub fn compose_completion(
 3998        &mut self,
 3999        action: &ComposeCompletion,
 4000        window: &mut Window,
 4001        cx: &mut Context<Self>,
 4002    ) -> Option<Task<Result<()>>> {
 4003        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4004    }
 4005
 4006    fn do_completion(
 4007        &mut self,
 4008        item_ix: Option<usize>,
 4009        intent: CompletionIntent,
 4010        window: &mut Window,
 4011        cx: &mut Context<Editor>,
 4012    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4013        use language::ToOffset as _;
 4014
 4015        let completions_menu =
 4016            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4017                menu
 4018            } else {
 4019                return None;
 4020            };
 4021
 4022        let entries = completions_menu.entries.borrow();
 4023        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4024        if self.show_edit_predictions_in_menu() {
 4025            self.discard_inline_completion(true, cx);
 4026        }
 4027        let candidate_id = mat.candidate_id;
 4028        drop(entries);
 4029
 4030        let buffer_handle = completions_menu.buffer;
 4031        let completion = completions_menu
 4032            .completions
 4033            .borrow()
 4034            .get(candidate_id)?
 4035            .clone();
 4036        cx.stop_propagation();
 4037
 4038        let snippet;
 4039        let text;
 4040
 4041        if completion.is_snippet() {
 4042            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4043            text = snippet.as_ref().unwrap().text.clone();
 4044        } else {
 4045            snippet = None;
 4046            text = completion.new_text.clone();
 4047        };
 4048        let selections = self.selections.all::<usize>(cx);
 4049        let buffer = buffer_handle.read(cx);
 4050        let old_range = completion.old_range.to_offset(buffer);
 4051        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4052
 4053        let newest_selection = self.selections.newest_anchor();
 4054        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4055            return None;
 4056        }
 4057
 4058        let lookbehind = newest_selection
 4059            .start
 4060            .text_anchor
 4061            .to_offset(buffer)
 4062            .saturating_sub(old_range.start);
 4063        let lookahead = old_range
 4064            .end
 4065            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4066        let mut common_prefix_len = old_text
 4067            .bytes()
 4068            .zip(text.bytes())
 4069            .take_while(|(a, b)| a == b)
 4070            .count();
 4071
 4072        let snapshot = self.buffer.read(cx).snapshot(cx);
 4073        let mut range_to_replace: Option<Range<isize>> = None;
 4074        let mut ranges = Vec::new();
 4075        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4076        for selection in &selections {
 4077            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4078                let start = selection.start.saturating_sub(lookbehind);
 4079                let end = selection.end + lookahead;
 4080                if selection.id == newest_selection.id {
 4081                    range_to_replace = Some(
 4082                        ((start + common_prefix_len) as isize - selection.start as isize)
 4083                            ..(end as isize - selection.start as isize),
 4084                    );
 4085                }
 4086                ranges.push(start + common_prefix_len..end);
 4087            } else {
 4088                common_prefix_len = 0;
 4089                ranges.clear();
 4090                ranges.extend(selections.iter().map(|s| {
 4091                    if s.id == newest_selection.id {
 4092                        range_to_replace = Some(
 4093                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4094                                - selection.start as isize
 4095                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4096                                    - selection.start as isize,
 4097                        );
 4098                        old_range.clone()
 4099                    } else {
 4100                        s.start..s.end
 4101                    }
 4102                }));
 4103                break;
 4104            }
 4105            if !self.linked_edit_ranges.is_empty() {
 4106                let start_anchor = snapshot.anchor_before(selection.head());
 4107                let end_anchor = snapshot.anchor_after(selection.tail());
 4108                if let Some(ranges) = self
 4109                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4110                {
 4111                    for (buffer, edits) in ranges {
 4112                        linked_edits.entry(buffer.clone()).or_default().extend(
 4113                            edits
 4114                                .into_iter()
 4115                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4116                        );
 4117                    }
 4118                }
 4119            }
 4120        }
 4121        let text = &text[common_prefix_len..];
 4122
 4123        cx.emit(EditorEvent::InputHandled {
 4124            utf16_range_to_replace: range_to_replace,
 4125            text: text.into(),
 4126        });
 4127
 4128        self.transact(window, cx, |this, window, cx| {
 4129            if let Some(mut snippet) = snippet {
 4130                snippet.text = text.to_string();
 4131                for tabstop in snippet
 4132                    .tabstops
 4133                    .iter_mut()
 4134                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4135                {
 4136                    tabstop.start -= common_prefix_len as isize;
 4137                    tabstop.end -= common_prefix_len as isize;
 4138                }
 4139
 4140                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4141            } else {
 4142                this.buffer.update(cx, |buffer, cx| {
 4143                    buffer.edit(
 4144                        ranges.iter().map(|range| (range.clone(), text)),
 4145                        this.autoindent_mode.clone(),
 4146                        cx,
 4147                    );
 4148                });
 4149            }
 4150            for (buffer, edits) in linked_edits {
 4151                buffer.update(cx, |buffer, cx| {
 4152                    let snapshot = buffer.snapshot();
 4153                    let edits = edits
 4154                        .into_iter()
 4155                        .map(|(range, text)| {
 4156                            use text::ToPoint as TP;
 4157                            let end_point = TP::to_point(&range.end, &snapshot);
 4158                            let start_point = TP::to_point(&range.start, &snapshot);
 4159                            (start_point..end_point, text)
 4160                        })
 4161                        .sorted_by_key(|(range, _)| range.start)
 4162                        .collect::<Vec<_>>();
 4163                    buffer.edit(edits, None, cx);
 4164                })
 4165            }
 4166
 4167            this.refresh_inline_completion(true, false, window, cx);
 4168        });
 4169
 4170        let show_new_completions_on_confirm = completion
 4171            .confirm
 4172            .as_ref()
 4173            .map_or(false, |confirm| confirm(intent, window, cx));
 4174        if show_new_completions_on_confirm {
 4175            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4176        }
 4177
 4178        let provider = self.completion_provider.as_ref()?;
 4179        drop(completion);
 4180        let apply_edits = provider.apply_additional_edits_for_completion(
 4181            buffer_handle,
 4182            completions_menu.completions.clone(),
 4183            candidate_id,
 4184            true,
 4185            cx,
 4186        );
 4187
 4188        let editor_settings = EditorSettings::get_global(cx);
 4189        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4190            // After the code completion is finished, users often want to know what signatures are needed.
 4191            // so we should automatically call signature_help
 4192            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4193        }
 4194
 4195        Some(cx.foreground_executor().spawn(async move {
 4196            apply_edits.await?;
 4197            Ok(())
 4198        }))
 4199    }
 4200
 4201    pub fn toggle_code_actions(
 4202        &mut self,
 4203        action: &ToggleCodeActions,
 4204        window: &mut Window,
 4205        cx: &mut Context<Self>,
 4206    ) {
 4207        let mut context_menu = self.context_menu.borrow_mut();
 4208        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4209            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4210                // Toggle if we're selecting the same one
 4211                *context_menu = None;
 4212                cx.notify();
 4213                return;
 4214            } else {
 4215                // Otherwise, clear it and start a new one
 4216                *context_menu = None;
 4217                cx.notify();
 4218            }
 4219        }
 4220        drop(context_menu);
 4221        let snapshot = self.snapshot(window, cx);
 4222        let deployed_from_indicator = action.deployed_from_indicator;
 4223        let mut task = self.code_actions_task.take();
 4224        let action = action.clone();
 4225        cx.spawn_in(window, |editor, mut cx| async move {
 4226            while let Some(prev_task) = task {
 4227                prev_task.await.log_err();
 4228                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4229            }
 4230
 4231            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4232                if editor.focus_handle.is_focused(window) {
 4233                    let multibuffer_point = action
 4234                        .deployed_from_indicator
 4235                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4236                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4237                    let (buffer, buffer_row) = snapshot
 4238                        .buffer_snapshot
 4239                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4240                        .and_then(|(buffer_snapshot, range)| {
 4241                            editor
 4242                                .buffer
 4243                                .read(cx)
 4244                                .buffer(buffer_snapshot.remote_id())
 4245                                .map(|buffer| (buffer, range.start.row))
 4246                        })?;
 4247                    let (_, code_actions) = editor
 4248                        .available_code_actions
 4249                        .clone()
 4250                        .and_then(|(location, code_actions)| {
 4251                            let snapshot = location.buffer.read(cx).snapshot();
 4252                            let point_range = location.range.to_point(&snapshot);
 4253                            let point_range = point_range.start.row..=point_range.end.row;
 4254                            if point_range.contains(&buffer_row) {
 4255                                Some((location, code_actions))
 4256                            } else {
 4257                                None
 4258                            }
 4259                        })
 4260                        .unzip();
 4261                    let buffer_id = buffer.read(cx).remote_id();
 4262                    let tasks = editor
 4263                        .tasks
 4264                        .get(&(buffer_id, buffer_row))
 4265                        .map(|t| Arc::new(t.to_owned()));
 4266                    if tasks.is_none() && code_actions.is_none() {
 4267                        return None;
 4268                    }
 4269
 4270                    editor.completion_tasks.clear();
 4271                    editor.discard_inline_completion(false, cx);
 4272                    let task_context =
 4273                        tasks
 4274                            .as_ref()
 4275                            .zip(editor.project.clone())
 4276                            .map(|(tasks, project)| {
 4277                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4278                            });
 4279
 4280                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4281                        let task_context = match task_context {
 4282                            Some(task_context) => task_context.await,
 4283                            None => None,
 4284                        };
 4285                        let resolved_tasks =
 4286                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4287                                Rc::new(ResolvedTasks {
 4288                                    templates: tasks.resolve(&task_context).collect(),
 4289                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4290                                        multibuffer_point.row,
 4291                                        tasks.column,
 4292                                    )),
 4293                                })
 4294                            });
 4295                        let spawn_straight_away = resolved_tasks
 4296                            .as_ref()
 4297                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4298                            && code_actions
 4299                                .as_ref()
 4300                                .map_or(true, |actions| actions.is_empty());
 4301                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4302                            *editor.context_menu.borrow_mut() =
 4303                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4304                                    buffer,
 4305                                    actions: CodeActionContents {
 4306                                        tasks: resolved_tasks,
 4307                                        actions: code_actions,
 4308                                    },
 4309                                    selected_item: Default::default(),
 4310                                    scroll_handle: UniformListScrollHandle::default(),
 4311                                    deployed_from_indicator,
 4312                                }));
 4313                            if spawn_straight_away {
 4314                                if let Some(task) = editor.confirm_code_action(
 4315                                    &ConfirmCodeAction { item_ix: Some(0) },
 4316                                    window,
 4317                                    cx,
 4318                                ) {
 4319                                    cx.notify();
 4320                                    return task;
 4321                                }
 4322                            }
 4323                            cx.notify();
 4324                            Task::ready(Ok(()))
 4325                        }) {
 4326                            task.await
 4327                        } else {
 4328                            Ok(())
 4329                        }
 4330                    }))
 4331                } else {
 4332                    Some(Task::ready(Ok(())))
 4333                }
 4334            })?;
 4335            if let Some(task) = spawned_test_task {
 4336                task.await?;
 4337            }
 4338
 4339            Ok::<_, anyhow::Error>(())
 4340        })
 4341        .detach_and_log_err(cx);
 4342    }
 4343
 4344    pub fn confirm_code_action(
 4345        &mut self,
 4346        action: &ConfirmCodeAction,
 4347        window: &mut Window,
 4348        cx: &mut Context<Self>,
 4349    ) -> Option<Task<Result<()>>> {
 4350        let actions_menu =
 4351            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4352                menu
 4353            } else {
 4354                return None;
 4355            };
 4356        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4357        let action = actions_menu.actions.get(action_ix)?;
 4358        let title = action.label();
 4359        let buffer = actions_menu.buffer;
 4360        let workspace = self.workspace()?;
 4361
 4362        match action {
 4363            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4364                workspace.update(cx, |workspace, cx| {
 4365                    workspace::tasks::schedule_resolved_task(
 4366                        workspace,
 4367                        task_source_kind,
 4368                        resolved_task,
 4369                        false,
 4370                        cx,
 4371                    );
 4372
 4373                    Some(Task::ready(Ok(())))
 4374                })
 4375            }
 4376            CodeActionsItem::CodeAction {
 4377                excerpt_id,
 4378                action,
 4379                provider,
 4380            } => {
 4381                let apply_code_action =
 4382                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4383                let workspace = workspace.downgrade();
 4384                Some(cx.spawn_in(window, |editor, cx| async move {
 4385                    let project_transaction = apply_code_action.await?;
 4386                    Self::open_project_transaction(
 4387                        &editor,
 4388                        workspace,
 4389                        project_transaction,
 4390                        title,
 4391                        cx,
 4392                    )
 4393                    .await
 4394                }))
 4395            }
 4396        }
 4397    }
 4398
 4399    pub async fn open_project_transaction(
 4400        this: &WeakEntity<Editor>,
 4401        workspace: WeakEntity<Workspace>,
 4402        transaction: ProjectTransaction,
 4403        title: String,
 4404        mut cx: AsyncWindowContext,
 4405    ) -> Result<()> {
 4406        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4407        cx.update(|_, cx| {
 4408            entries.sort_unstable_by_key(|(buffer, _)| {
 4409                buffer.read(cx).file().map(|f| f.path().clone())
 4410            });
 4411        })?;
 4412
 4413        // If the project transaction's edits are all contained within this editor, then
 4414        // avoid opening a new editor to display them.
 4415
 4416        if let Some((buffer, transaction)) = entries.first() {
 4417            if entries.len() == 1 {
 4418                let excerpt = this.update(&mut cx, |editor, cx| {
 4419                    editor
 4420                        .buffer()
 4421                        .read(cx)
 4422                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4423                })?;
 4424                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4425                    if excerpted_buffer == *buffer {
 4426                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4427                            let excerpt_range = excerpt_range.to_offset(buffer);
 4428                            buffer
 4429                                .edited_ranges_for_transaction::<usize>(transaction)
 4430                                .all(|range| {
 4431                                    excerpt_range.start <= range.start
 4432                                        && excerpt_range.end >= range.end
 4433                                })
 4434                        })?;
 4435
 4436                        if all_edits_within_excerpt {
 4437                            return Ok(());
 4438                        }
 4439                    }
 4440                }
 4441            }
 4442        } else {
 4443            return Ok(());
 4444        }
 4445
 4446        let mut ranges_to_highlight = Vec::new();
 4447        let excerpt_buffer = cx.new(|cx| {
 4448            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4449            for (buffer_handle, transaction) in &entries {
 4450                let buffer = buffer_handle.read(cx);
 4451                ranges_to_highlight.extend(
 4452                    multibuffer.push_excerpts_with_context_lines(
 4453                        buffer_handle.clone(),
 4454                        buffer
 4455                            .edited_ranges_for_transaction::<usize>(transaction)
 4456                            .collect(),
 4457                        DEFAULT_MULTIBUFFER_CONTEXT,
 4458                        cx,
 4459                    ),
 4460                );
 4461            }
 4462            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4463            multibuffer
 4464        })?;
 4465
 4466        workspace.update_in(&mut cx, |workspace, window, cx| {
 4467            let project = workspace.project().clone();
 4468            let editor = cx
 4469                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4470            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4471            editor.update(cx, |editor, cx| {
 4472                editor.highlight_background::<Self>(
 4473                    &ranges_to_highlight,
 4474                    |theme| theme.editor_highlighted_line_background,
 4475                    cx,
 4476                );
 4477            });
 4478        })?;
 4479
 4480        Ok(())
 4481    }
 4482
 4483    pub fn clear_code_action_providers(&mut self) {
 4484        self.code_action_providers.clear();
 4485        self.available_code_actions.take();
 4486    }
 4487
 4488    pub fn add_code_action_provider(
 4489        &mut self,
 4490        provider: Rc<dyn CodeActionProvider>,
 4491        window: &mut Window,
 4492        cx: &mut Context<Self>,
 4493    ) {
 4494        if self
 4495            .code_action_providers
 4496            .iter()
 4497            .any(|existing_provider| existing_provider.id() == provider.id())
 4498        {
 4499            return;
 4500        }
 4501
 4502        self.code_action_providers.push(provider);
 4503        self.refresh_code_actions(window, cx);
 4504    }
 4505
 4506    pub fn remove_code_action_provider(
 4507        &mut self,
 4508        id: Arc<str>,
 4509        window: &mut Window,
 4510        cx: &mut Context<Self>,
 4511    ) {
 4512        self.code_action_providers
 4513            .retain(|provider| provider.id() != id);
 4514        self.refresh_code_actions(window, cx);
 4515    }
 4516
 4517    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4518        let buffer = self.buffer.read(cx);
 4519        let newest_selection = self.selections.newest_anchor().clone();
 4520        if newest_selection.head().diff_base_anchor.is_some() {
 4521            return None;
 4522        }
 4523        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4524        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4525        if start_buffer != end_buffer {
 4526            return None;
 4527        }
 4528
 4529        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4530            cx.background_executor()
 4531                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4532                .await;
 4533
 4534            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4535                let providers = this.code_action_providers.clone();
 4536                let tasks = this
 4537                    .code_action_providers
 4538                    .iter()
 4539                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4540                    .collect::<Vec<_>>();
 4541                (providers, tasks)
 4542            })?;
 4543
 4544            let mut actions = Vec::new();
 4545            for (provider, provider_actions) in
 4546                providers.into_iter().zip(future::join_all(tasks).await)
 4547            {
 4548                if let Some(provider_actions) = provider_actions.log_err() {
 4549                    actions.extend(provider_actions.into_iter().map(|action| {
 4550                        AvailableCodeAction {
 4551                            excerpt_id: newest_selection.start.excerpt_id,
 4552                            action,
 4553                            provider: provider.clone(),
 4554                        }
 4555                    }));
 4556                }
 4557            }
 4558
 4559            this.update(&mut cx, |this, cx| {
 4560                this.available_code_actions = if actions.is_empty() {
 4561                    None
 4562                } else {
 4563                    Some((
 4564                        Location {
 4565                            buffer: start_buffer,
 4566                            range: start..end,
 4567                        },
 4568                        actions.into(),
 4569                    ))
 4570                };
 4571                cx.notify();
 4572            })
 4573        }));
 4574        None
 4575    }
 4576
 4577    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4578        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4579            self.show_git_blame_inline = false;
 4580
 4581            self.show_git_blame_inline_delay_task =
 4582                Some(cx.spawn_in(window, |this, mut cx| async move {
 4583                    cx.background_executor().timer(delay).await;
 4584
 4585                    this.update(&mut cx, |this, cx| {
 4586                        this.show_git_blame_inline = true;
 4587                        cx.notify();
 4588                    })
 4589                    .log_err();
 4590                }));
 4591        }
 4592    }
 4593
 4594    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4595        if self.pending_rename.is_some() {
 4596            return None;
 4597        }
 4598
 4599        let provider = self.semantics_provider.clone()?;
 4600        let buffer = self.buffer.read(cx);
 4601        let newest_selection = self.selections.newest_anchor().clone();
 4602        let cursor_position = newest_selection.head();
 4603        let (cursor_buffer, cursor_buffer_position) =
 4604            buffer.text_anchor_for_position(cursor_position, cx)?;
 4605        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4606        if cursor_buffer != tail_buffer {
 4607            return None;
 4608        }
 4609        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4610        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4611            cx.background_executor()
 4612                .timer(Duration::from_millis(debounce))
 4613                .await;
 4614
 4615            let highlights = if let Some(highlights) = cx
 4616                .update(|cx| {
 4617                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4618                })
 4619                .ok()
 4620                .flatten()
 4621            {
 4622                highlights.await.log_err()
 4623            } else {
 4624                None
 4625            };
 4626
 4627            if let Some(highlights) = highlights {
 4628                this.update(&mut cx, |this, cx| {
 4629                    if this.pending_rename.is_some() {
 4630                        return;
 4631                    }
 4632
 4633                    let buffer_id = cursor_position.buffer_id;
 4634                    let buffer = this.buffer.read(cx);
 4635                    if !buffer
 4636                        .text_anchor_for_position(cursor_position, cx)
 4637                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4638                    {
 4639                        return;
 4640                    }
 4641
 4642                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4643                    let mut write_ranges = Vec::new();
 4644                    let mut read_ranges = Vec::new();
 4645                    for highlight in highlights {
 4646                        for (excerpt_id, excerpt_range) in
 4647                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4648                        {
 4649                            let start = highlight
 4650                                .range
 4651                                .start
 4652                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4653                            let end = highlight
 4654                                .range
 4655                                .end
 4656                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4657                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4658                                continue;
 4659                            }
 4660
 4661                            let range = Anchor {
 4662                                buffer_id,
 4663                                excerpt_id,
 4664                                text_anchor: start,
 4665                                diff_base_anchor: None,
 4666                            }..Anchor {
 4667                                buffer_id,
 4668                                excerpt_id,
 4669                                text_anchor: end,
 4670                                diff_base_anchor: None,
 4671                            };
 4672                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4673                                write_ranges.push(range);
 4674                            } else {
 4675                                read_ranges.push(range);
 4676                            }
 4677                        }
 4678                    }
 4679
 4680                    this.highlight_background::<DocumentHighlightRead>(
 4681                        &read_ranges,
 4682                        |theme| theme.editor_document_highlight_read_background,
 4683                        cx,
 4684                    );
 4685                    this.highlight_background::<DocumentHighlightWrite>(
 4686                        &write_ranges,
 4687                        |theme| theme.editor_document_highlight_write_background,
 4688                        cx,
 4689                    );
 4690                    cx.notify();
 4691                })
 4692                .log_err();
 4693            }
 4694        }));
 4695        None
 4696    }
 4697
 4698    pub fn refresh_inline_completion(
 4699        &mut self,
 4700        debounce: bool,
 4701        user_requested: bool,
 4702        window: &mut Window,
 4703        cx: &mut Context<Self>,
 4704    ) -> Option<()> {
 4705        let provider = self.edit_prediction_provider()?;
 4706        let cursor = self.selections.newest_anchor().head();
 4707        let (buffer, cursor_buffer_position) =
 4708            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4709
 4710        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4711            self.discard_inline_completion(false, cx);
 4712            return None;
 4713        }
 4714
 4715        if !user_requested
 4716            && (!self.should_show_edit_predictions()
 4717                || !self.is_focused(window)
 4718                || buffer.read(cx).is_empty())
 4719        {
 4720            self.discard_inline_completion(false, cx);
 4721            return None;
 4722        }
 4723
 4724        self.update_visible_inline_completion(window, cx);
 4725        provider.refresh(
 4726            self.project.clone(),
 4727            buffer,
 4728            cursor_buffer_position,
 4729            debounce,
 4730            cx,
 4731        );
 4732        Some(())
 4733    }
 4734
 4735    fn show_edit_predictions_in_menu(&self) -> bool {
 4736        match self.edit_prediction_settings {
 4737            EditPredictionSettings::Disabled => false,
 4738            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4739        }
 4740    }
 4741
 4742    pub fn edit_predictions_enabled(&self) -> bool {
 4743        match self.edit_prediction_settings {
 4744            EditPredictionSettings::Disabled => false,
 4745            EditPredictionSettings::Enabled { .. } => true,
 4746        }
 4747    }
 4748
 4749    fn edit_prediction_requires_modifier(&self) -> bool {
 4750        match self.edit_prediction_settings {
 4751            EditPredictionSettings::Disabled => false,
 4752            EditPredictionSettings::Enabled {
 4753                preview_requires_modifier,
 4754                ..
 4755            } => preview_requires_modifier,
 4756        }
 4757    }
 4758
 4759    fn edit_prediction_settings_at_position(
 4760        &self,
 4761        buffer: &Entity<Buffer>,
 4762        buffer_position: language::Anchor,
 4763        cx: &App,
 4764    ) -> EditPredictionSettings {
 4765        if self.mode != EditorMode::Full
 4766            || !self.show_inline_completions_override.unwrap_or(true)
 4767            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4768        {
 4769            return EditPredictionSettings::Disabled;
 4770        }
 4771
 4772        let buffer = buffer.read(cx);
 4773
 4774        let file = buffer.file();
 4775
 4776        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4777            return EditPredictionSettings::Disabled;
 4778        };
 4779
 4780        let by_provider = matches!(
 4781            self.menu_inline_completions_policy,
 4782            MenuInlineCompletionsPolicy::ByProvider
 4783        );
 4784
 4785        let show_in_menu = by_provider
 4786            && self
 4787                .edit_prediction_provider
 4788                .as_ref()
 4789                .map_or(false, |provider| {
 4790                    provider.provider.show_completions_in_menu()
 4791                });
 4792
 4793        let preview_requires_modifier =
 4794            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4795
 4796        EditPredictionSettings::Enabled {
 4797            show_in_menu,
 4798            preview_requires_modifier,
 4799        }
 4800    }
 4801
 4802    fn should_show_edit_predictions(&self) -> bool {
 4803        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4804    }
 4805
 4806    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4807        matches!(
 4808            self.edit_prediction_preview,
 4809            EditPredictionPreview::Active { .. }
 4810        )
 4811    }
 4812
 4813    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4814        let cursor = self.selections.newest_anchor().head();
 4815        if let Some((buffer, cursor_position)) =
 4816            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4817        {
 4818            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4819        } else {
 4820            false
 4821        }
 4822    }
 4823
 4824    fn inline_completions_enabled_in_buffer(
 4825        &self,
 4826        buffer: &Entity<Buffer>,
 4827        buffer_position: language::Anchor,
 4828        cx: &App,
 4829    ) -> bool {
 4830        maybe!({
 4831            let provider = self.edit_prediction_provider()?;
 4832            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4833                return Some(false);
 4834            }
 4835            let buffer = buffer.read(cx);
 4836            let Some(file) = buffer.file() else {
 4837                return Some(true);
 4838            };
 4839            let settings = all_language_settings(Some(file), cx);
 4840            Some(settings.inline_completions_enabled_for_path(file.path()))
 4841        })
 4842        .unwrap_or(false)
 4843    }
 4844
 4845    fn cycle_inline_completion(
 4846        &mut self,
 4847        direction: Direction,
 4848        window: &mut Window,
 4849        cx: &mut Context<Self>,
 4850    ) -> Option<()> {
 4851        let provider = self.edit_prediction_provider()?;
 4852        let cursor = self.selections.newest_anchor().head();
 4853        let (buffer, cursor_buffer_position) =
 4854            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4855        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4856            return None;
 4857        }
 4858
 4859        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4860        self.update_visible_inline_completion(window, cx);
 4861
 4862        Some(())
 4863    }
 4864
 4865    pub fn show_inline_completion(
 4866        &mut self,
 4867        _: &ShowEditPrediction,
 4868        window: &mut Window,
 4869        cx: &mut Context<Self>,
 4870    ) {
 4871        if !self.has_active_inline_completion() {
 4872            self.refresh_inline_completion(false, true, window, cx);
 4873            return;
 4874        }
 4875
 4876        self.update_visible_inline_completion(window, cx);
 4877    }
 4878
 4879    pub fn display_cursor_names(
 4880        &mut self,
 4881        _: &DisplayCursorNames,
 4882        window: &mut Window,
 4883        cx: &mut Context<Self>,
 4884    ) {
 4885        self.show_cursor_names(window, cx);
 4886    }
 4887
 4888    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4889        self.show_cursor_names = true;
 4890        cx.notify();
 4891        cx.spawn_in(window, |this, mut cx| async move {
 4892            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4893            this.update(&mut cx, |this, cx| {
 4894                this.show_cursor_names = false;
 4895                cx.notify()
 4896            })
 4897            .ok()
 4898        })
 4899        .detach();
 4900    }
 4901
 4902    pub fn next_edit_prediction(
 4903        &mut self,
 4904        _: &NextEditPrediction,
 4905        window: &mut Window,
 4906        cx: &mut Context<Self>,
 4907    ) {
 4908        if self.has_active_inline_completion() {
 4909            self.cycle_inline_completion(Direction::Next, window, cx);
 4910        } else {
 4911            let is_copilot_disabled = self
 4912                .refresh_inline_completion(false, true, window, cx)
 4913                .is_none();
 4914            if is_copilot_disabled {
 4915                cx.propagate();
 4916            }
 4917        }
 4918    }
 4919
 4920    pub fn previous_edit_prediction(
 4921        &mut self,
 4922        _: &PreviousEditPrediction,
 4923        window: &mut Window,
 4924        cx: &mut Context<Self>,
 4925    ) {
 4926        if self.has_active_inline_completion() {
 4927            self.cycle_inline_completion(Direction::Prev, window, cx);
 4928        } else {
 4929            let is_copilot_disabled = self
 4930                .refresh_inline_completion(false, true, window, cx)
 4931                .is_none();
 4932            if is_copilot_disabled {
 4933                cx.propagate();
 4934            }
 4935        }
 4936    }
 4937
 4938    pub fn accept_edit_prediction(
 4939        &mut self,
 4940        _: &AcceptEditPrediction,
 4941        window: &mut Window,
 4942        cx: &mut Context<Self>,
 4943    ) {
 4944        if self.show_edit_predictions_in_menu() {
 4945            self.hide_context_menu(window, cx);
 4946        }
 4947
 4948        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4949            return;
 4950        };
 4951
 4952        self.report_inline_completion_event(
 4953            active_inline_completion.completion_id.clone(),
 4954            true,
 4955            cx,
 4956        );
 4957
 4958        match &active_inline_completion.completion {
 4959            InlineCompletion::Move { target, .. } => {
 4960                let target = *target;
 4961
 4962                if let Some(position_map) = &self.last_position_map {
 4963                    if position_map
 4964                        .visible_row_range
 4965                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4966                        || !self.edit_prediction_requires_modifier()
 4967                    {
 4968                        // Note that this is also done in vim's handler of the Tab action.
 4969                        self.change_selections(
 4970                            Some(Autoscroll::newest()),
 4971                            window,
 4972                            cx,
 4973                            |selections| {
 4974                                selections.select_anchor_ranges([target..target]);
 4975                            },
 4976                        );
 4977                        self.clear_row_highlights::<EditPredictionPreview>();
 4978
 4979                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4980                            previous_scroll_position: None,
 4981                        };
 4982                    } else {
 4983                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4984                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 4985                        };
 4986                        self.highlight_rows::<EditPredictionPreview>(
 4987                            target..target,
 4988                            cx.theme().colors().editor_highlighted_line_background,
 4989                            true,
 4990                            cx,
 4991                        );
 4992                        self.request_autoscroll(Autoscroll::fit(), cx);
 4993                    }
 4994                }
 4995            }
 4996            InlineCompletion::Edit { edits, .. } => {
 4997                if let Some(provider) = self.edit_prediction_provider() {
 4998                    provider.accept(cx);
 4999                }
 5000
 5001                let snapshot = self.buffer.read(cx).snapshot(cx);
 5002                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5003
 5004                self.buffer.update(cx, |buffer, cx| {
 5005                    buffer.edit(edits.iter().cloned(), None, cx)
 5006                });
 5007
 5008                self.change_selections(None, window, cx, |s| {
 5009                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5010                });
 5011
 5012                self.update_visible_inline_completion(window, cx);
 5013                if self.active_inline_completion.is_none() {
 5014                    self.refresh_inline_completion(true, true, window, cx);
 5015                }
 5016
 5017                cx.notify();
 5018            }
 5019        }
 5020
 5021        self.edit_prediction_requires_modifier_in_leading_space = false;
 5022    }
 5023
 5024    pub fn accept_partial_inline_completion(
 5025        &mut self,
 5026        _: &AcceptPartialEditPrediction,
 5027        window: &mut Window,
 5028        cx: &mut Context<Self>,
 5029    ) {
 5030        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5031            return;
 5032        };
 5033        if self.selections.count() != 1 {
 5034            return;
 5035        }
 5036
 5037        self.report_inline_completion_event(
 5038            active_inline_completion.completion_id.clone(),
 5039            true,
 5040            cx,
 5041        );
 5042
 5043        match &active_inline_completion.completion {
 5044            InlineCompletion::Move { target, .. } => {
 5045                let target = *target;
 5046                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5047                    selections.select_anchor_ranges([target..target]);
 5048                });
 5049            }
 5050            InlineCompletion::Edit { edits, .. } => {
 5051                // Find an insertion that starts at the cursor position.
 5052                let snapshot = self.buffer.read(cx).snapshot(cx);
 5053                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5054                let insertion = edits.iter().find_map(|(range, text)| {
 5055                    let range = range.to_offset(&snapshot);
 5056                    if range.is_empty() && range.start == cursor_offset {
 5057                        Some(text)
 5058                    } else {
 5059                        None
 5060                    }
 5061                });
 5062
 5063                if let Some(text) = insertion {
 5064                    let mut partial_completion = text
 5065                        .chars()
 5066                        .by_ref()
 5067                        .take_while(|c| c.is_alphabetic())
 5068                        .collect::<String>();
 5069                    if partial_completion.is_empty() {
 5070                        partial_completion = text
 5071                            .chars()
 5072                            .by_ref()
 5073                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5074                            .collect::<String>();
 5075                    }
 5076
 5077                    cx.emit(EditorEvent::InputHandled {
 5078                        utf16_range_to_replace: None,
 5079                        text: partial_completion.clone().into(),
 5080                    });
 5081
 5082                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5083
 5084                    self.refresh_inline_completion(true, true, window, cx);
 5085                    cx.notify();
 5086                } else {
 5087                    self.accept_edit_prediction(&Default::default(), window, cx);
 5088                }
 5089            }
 5090        }
 5091    }
 5092
 5093    fn discard_inline_completion(
 5094        &mut self,
 5095        should_report_inline_completion_event: bool,
 5096        cx: &mut Context<Self>,
 5097    ) -> bool {
 5098        if should_report_inline_completion_event {
 5099            let completion_id = self
 5100                .active_inline_completion
 5101                .as_ref()
 5102                .and_then(|active_completion| active_completion.completion_id.clone());
 5103
 5104            self.report_inline_completion_event(completion_id, false, cx);
 5105        }
 5106
 5107        if let Some(provider) = self.edit_prediction_provider() {
 5108            provider.discard(cx);
 5109        }
 5110
 5111        self.take_active_inline_completion(cx)
 5112    }
 5113
 5114    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5115        let Some(provider) = self.edit_prediction_provider() else {
 5116            return;
 5117        };
 5118
 5119        let Some((_, buffer, _)) = self
 5120            .buffer
 5121            .read(cx)
 5122            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5123        else {
 5124            return;
 5125        };
 5126
 5127        let extension = buffer
 5128            .read(cx)
 5129            .file()
 5130            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5131
 5132        let event_type = match accepted {
 5133            true => "Edit Prediction Accepted",
 5134            false => "Edit Prediction Discarded",
 5135        };
 5136        telemetry::event!(
 5137            event_type,
 5138            provider = provider.name(),
 5139            prediction_id = id,
 5140            suggestion_accepted = accepted,
 5141            file_extension = extension,
 5142        );
 5143    }
 5144
 5145    pub fn has_active_inline_completion(&self) -> bool {
 5146        self.active_inline_completion.is_some()
 5147    }
 5148
 5149    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5150        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5151            return false;
 5152        };
 5153
 5154        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5155        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5156        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5157        true
 5158    }
 5159
 5160    /// Returns true when we're displaying the edit prediction popover below the cursor
 5161    /// like we are not previewing and the LSP autocomplete menu is visible
 5162    /// or we are in `when_holding_modifier` mode.
 5163    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5164        if self.edit_prediction_preview_is_active()
 5165            || !self.show_edit_predictions_in_menu()
 5166            || !self.edit_predictions_enabled()
 5167        {
 5168            return false;
 5169        }
 5170
 5171        if self.has_visible_completions_menu() {
 5172            return true;
 5173        }
 5174
 5175        has_completion && self.edit_prediction_requires_modifier()
 5176    }
 5177
 5178    fn handle_modifiers_changed(
 5179        &mut self,
 5180        modifiers: Modifiers,
 5181        position_map: &PositionMap,
 5182        window: &mut Window,
 5183        cx: &mut Context<Self>,
 5184    ) {
 5185        if self.show_edit_predictions_in_menu() {
 5186            self.update_edit_prediction_preview(&modifiers, window, cx);
 5187        }
 5188
 5189        let mouse_position = window.mouse_position();
 5190        if !position_map.text_hitbox.is_hovered(window) {
 5191            return;
 5192        }
 5193
 5194        self.update_hovered_link(
 5195            position_map.point_for_position(mouse_position),
 5196            &position_map.snapshot,
 5197            modifiers,
 5198            window,
 5199            cx,
 5200        )
 5201    }
 5202
 5203    fn update_edit_prediction_preview(
 5204        &mut self,
 5205        modifiers: &Modifiers,
 5206        window: &mut Window,
 5207        cx: &mut Context<Self>,
 5208    ) {
 5209        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5210        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5211            return;
 5212        };
 5213
 5214        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5215            if matches!(
 5216                self.edit_prediction_preview,
 5217                EditPredictionPreview::Inactive
 5218            ) {
 5219                self.edit_prediction_preview = EditPredictionPreview::Active {
 5220                    previous_scroll_position: None,
 5221                };
 5222
 5223                self.update_visible_inline_completion(window, cx);
 5224                cx.notify();
 5225            }
 5226        } else if let EditPredictionPreview::Active {
 5227            previous_scroll_position,
 5228        } = self.edit_prediction_preview
 5229        {
 5230            if let (Some(previous_scroll_position), Some(position_map)) =
 5231                (previous_scroll_position, self.last_position_map.as_ref())
 5232            {
 5233                self.set_scroll_position(
 5234                    previous_scroll_position
 5235                        .scroll_position(&position_map.snapshot.display_snapshot),
 5236                    window,
 5237                    cx,
 5238                );
 5239            }
 5240
 5241            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5242            self.clear_row_highlights::<EditPredictionPreview>();
 5243            self.update_visible_inline_completion(window, cx);
 5244            cx.notify();
 5245        }
 5246    }
 5247
 5248    fn update_visible_inline_completion(
 5249        &mut self,
 5250        _window: &mut Window,
 5251        cx: &mut Context<Self>,
 5252    ) -> Option<()> {
 5253        let selection = self.selections.newest_anchor();
 5254        let cursor = selection.head();
 5255        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5256        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5257        let excerpt_id = cursor.excerpt_id;
 5258
 5259        let show_in_menu = self.show_edit_predictions_in_menu();
 5260        let completions_menu_has_precedence = !show_in_menu
 5261            && (self.context_menu.borrow().is_some()
 5262                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5263
 5264        if completions_menu_has_precedence
 5265            || !offset_selection.is_empty()
 5266            || self
 5267                .active_inline_completion
 5268                .as_ref()
 5269                .map_or(false, |completion| {
 5270                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5271                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5272                    !invalidation_range.contains(&offset_selection.head())
 5273                })
 5274        {
 5275            self.discard_inline_completion(false, cx);
 5276            return None;
 5277        }
 5278
 5279        self.take_active_inline_completion(cx);
 5280        let Some(provider) = self.edit_prediction_provider() else {
 5281            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5282            return None;
 5283        };
 5284
 5285        let (buffer, cursor_buffer_position) =
 5286            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5287
 5288        self.edit_prediction_settings =
 5289            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5290
 5291        if !self.edit_prediction_settings.is_enabled() {
 5292            self.discard_inline_completion(false, cx);
 5293            return None;
 5294        }
 5295
 5296        self.edit_prediction_cursor_on_leading_whitespace =
 5297            multibuffer.is_line_whitespace_upto(cursor);
 5298
 5299        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5300        let edits = inline_completion
 5301            .edits
 5302            .into_iter()
 5303            .flat_map(|(range, new_text)| {
 5304                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5305                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5306                Some((start..end, new_text))
 5307            })
 5308            .collect::<Vec<_>>();
 5309        if edits.is_empty() {
 5310            return None;
 5311        }
 5312
 5313        let first_edit_start = edits.first().unwrap().0.start;
 5314        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5315        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5316
 5317        let last_edit_end = edits.last().unwrap().0.end;
 5318        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5319        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5320
 5321        let cursor_row = cursor.to_point(&multibuffer).row;
 5322
 5323        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5324
 5325        let mut inlay_ids = Vec::new();
 5326        let invalidation_row_range;
 5327        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5328            Some(cursor_row..edit_end_row)
 5329        } else if cursor_row > edit_end_row {
 5330            Some(edit_start_row..cursor_row)
 5331        } else {
 5332            None
 5333        };
 5334        let is_move =
 5335            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5336        let completion = if is_move {
 5337            invalidation_row_range =
 5338                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5339            let target = first_edit_start;
 5340            InlineCompletion::Move { target, snapshot }
 5341        } else {
 5342            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5343                && !self.inline_completions_hidden_for_vim_mode;
 5344
 5345            if show_completions_in_buffer {
 5346                if edits
 5347                    .iter()
 5348                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5349                {
 5350                    let mut inlays = Vec::new();
 5351                    for (range, new_text) in &edits {
 5352                        let inlay = Inlay::inline_completion(
 5353                            post_inc(&mut self.next_inlay_id),
 5354                            range.start,
 5355                            new_text.as_str(),
 5356                        );
 5357                        inlay_ids.push(inlay.id);
 5358                        inlays.push(inlay);
 5359                    }
 5360
 5361                    self.splice_inlays(&[], inlays, cx);
 5362                } else {
 5363                    let background_color = cx.theme().status().deleted_background;
 5364                    self.highlight_text::<InlineCompletionHighlight>(
 5365                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5366                        HighlightStyle {
 5367                            background_color: Some(background_color),
 5368                            ..Default::default()
 5369                        },
 5370                        cx,
 5371                    );
 5372                }
 5373            }
 5374
 5375            invalidation_row_range = edit_start_row..edit_end_row;
 5376
 5377            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5378                if provider.show_tab_accept_marker() {
 5379                    EditDisplayMode::TabAccept
 5380                } else {
 5381                    EditDisplayMode::Inline
 5382                }
 5383            } else {
 5384                EditDisplayMode::DiffPopover
 5385            };
 5386
 5387            InlineCompletion::Edit {
 5388                edits,
 5389                edit_preview: inline_completion.edit_preview,
 5390                display_mode,
 5391                snapshot,
 5392            }
 5393        };
 5394
 5395        let invalidation_range = multibuffer
 5396            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5397            ..multibuffer.anchor_after(Point::new(
 5398                invalidation_row_range.end,
 5399                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5400            ));
 5401
 5402        self.stale_inline_completion_in_menu = None;
 5403        self.active_inline_completion = Some(InlineCompletionState {
 5404            inlay_ids,
 5405            completion,
 5406            completion_id: inline_completion.id,
 5407            invalidation_range,
 5408        });
 5409
 5410        cx.notify();
 5411
 5412        Some(())
 5413    }
 5414
 5415    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5416        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5417    }
 5418
 5419    fn render_code_actions_indicator(
 5420        &self,
 5421        _style: &EditorStyle,
 5422        row: DisplayRow,
 5423        is_active: bool,
 5424        cx: &mut Context<Self>,
 5425    ) -> Option<IconButton> {
 5426        if self.available_code_actions.is_some() {
 5427            Some(
 5428                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5429                    .shape(ui::IconButtonShape::Square)
 5430                    .icon_size(IconSize::XSmall)
 5431                    .icon_color(Color::Muted)
 5432                    .toggle_state(is_active)
 5433                    .tooltip({
 5434                        let focus_handle = self.focus_handle.clone();
 5435                        move |window, cx| {
 5436                            Tooltip::for_action_in(
 5437                                "Toggle Code Actions",
 5438                                &ToggleCodeActions {
 5439                                    deployed_from_indicator: None,
 5440                                },
 5441                                &focus_handle,
 5442                                window,
 5443                                cx,
 5444                            )
 5445                        }
 5446                    })
 5447                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5448                        window.focus(&editor.focus_handle(cx));
 5449                        editor.toggle_code_actions(
 5450                            &ToggleCodeActions {
 5451                                deployed_from_indicator: Some(row),
 5452                            },
 5453                            window,
 5454                            cx,
 5455                        );
 5456                    })),
 5457            )
 5458        } else {
 5459            None
 5460        }
 5461    }
 5462
 5463    fn clear_tasks(&mut self) {
 5464        self.tasks.clear()
 5465    }
 5466
 5467    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5468        if self.tasks.insert(key, value).is_some() {
 5469            // This case should hopefully be rare, but just in case...
 5470            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5471        }
 5472    }
 5473
 5474    fn build_tasks_context(
 5475        project: &Entity<Project>,
 5476        buffer: &Entity<Buffer>,
 5477        buffer_row: u32,
 5478        tasks: &Arc<RunnableTasks>,
 5479        cx: &mut Context<Self>,
 5480    ) -> Task<Option<task::TaskContext>> {
 5481        let position = Point::new(buffer_row, tasks.column);
 5482        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5483        let location = Location {
 5484            buffer: buffer.clone(),
 5485            range: range_start..range_start,
 5486        };
 5487        // Fill in the environmental variables from the tree-sitter captures
 5488        let mut captured_task_variables = TaskVariables::default();
 5489        for (capture_name, value) in tasks.extra_variables.clone() {
 5490            captured_task_variables.insert(
 5491                task::VariableName::Custom(capture_name.into()),
 5492                value.clone(),
 5493            );
 5494        }
 5495        project.update(cx, |project, cx| {
 5496            project.task_store().update(cx, |task_store, cx| {
 5497                task_store.task_context_for_location(captured_task_variables, location, cx)
 5498            })
 5499        })
 5500    }
 5501
 5502    pub fn spawn_nearest_task(
 5503        &mut self,
 5504        action: &SpawnNearestTask,
 5505        window: &mut Window,
 5506        cx: &mut Context<Self>,
 5507    ) {
 5508        let Some((workspace, _)) = self.workspace.clone() else {
 5509            return;
 5510        };
 5511        let Some(project) = self.project.clone() else {
 5512            return;
 5513        };
 5514
 5515        // Try to find a closest, enclosing node using tree-sitter that has a
 5516        // task
 5517        let Some((buffer, buffer_row, tasks)) = self
 5518            .find_enclosing_node_task(cx)
 5519            // Or find the task that's closest in row-distance.
 5520            .or_else(|| self.find_closest_task(cx))
 5521        else {
 5522            return;
 5523        };
 5524
 5525        let reveal_strategy = action.reveal;
 5526        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5527        cx.spawn_in(window, |_, mut cx| async move {
 5528            let context = task_context.await?;
 5529            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5530
 5531            let resolved = resolved_task.resolved.as_mut()?;
 5532            resolved.reveal = reveal_strategy;
 5533
 5534            workspace
 5535                .update(&mut cx, |workspace, cx| {
 5536                    workspace::tasks::schedule_resolved_task(
 5537                        workspace,
 5538                        task_source_kind,
 5539                        resolved_task,
 5540                        false,
 5541                        cx,
 5542                    );
 5543                })
 5544                .ok()
 5545        })
 5546        .detach();
 5547    }
 5548
 5549    fn find_closest_task(
 5550        &mut self,
 5551        cx: &mut Context<Self>,
 5552    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5553        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5554
 5555        let ((buffer_id, row), tasks) = self
 5556            .tasks
 5557            .iter()
 5558            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5559
 5560        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5561        let tasks = Arc::new(tasks.to_owned());
 5562        Some((buffer, *row, tasks))
 5563    }
 5564
 5565    fn find_enclosing_node_task(
 5566        &mut self,
 5567        cx: &mut Context<Self>,
 5568    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5569        let snapshot = self.buffer.read(cx).snapshot(cx);
 5570        let offset = self.selections.newest::<usize>(cx).head();
 5571        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5572        let buffer_id = excerpt.buffer().remote_id();
 5573
 5574        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5575        let mut cursor = layer.node().walk();
 5576
 5577        while cursor.goto_first_child_for_byte(offset).is_some() {
 5578            if cursor.node().end_byte() == offset {
 5579                cursor.goto_next_sibling();
 5580            }
 5581        }
 5582
 5583        // Ascend to the smallest ancestor that contains the range and has a task.
 5584        loop {
 5585            let node = cursor.node();
 5586            let node_range = node.byte_range();
 5587            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5588
 5589            // Check if this node contains our offset
 5590            if node_range.start <= offset && node_range.end >= offset {
 5591                // If it contains offset, check for task
 5592                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5593                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5594                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5595                }
 5596            }
 5597
 5598            if !cursor.goto_parent() {
 5599                break;
 5600            }
 5601        }
 5602        None
 5603    }
 5604
 5605    fn render_run_indicator(
 5606        &self,
 5607        _style: &EditorStyle,
 5608        is_active: bool,
 5609        row: DisplayRow,
 5610        cx: &mut Context<Self>,
 5611    ) -> IconButton {
 5612        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5613            .shape(ui::IconButtonShape::Square)
 5614            .icon_size(IconSize::XSmall)
 5615            .icon_color(Color::Muted)
 5616            .toggle_state(is_active)
 5617            .on_click(cx.listener(move |editor, _e, window, cx| {
 5618                window.focus(&editor.focus_handle(cx));
 5619                editor.toggle_code_actions(
 5620                    &ToggleCodeActions {
 5621                        deployed_from_indicator: Some(row),
 5622                    },
 5623                    window,
 5624                    cx,
 5625                );
 5626            }))
 5627    }
 5628
 5629    pub fn context_menu_visible(&self) -> bool {
 5630        !self.edit_prediction_preview_is_active()
 5631            && self
 5632                .context_menu
 5633                .borrow()
 5634                .as_ref()
 5635                .map_or(false, |menu| menu.visible())
 5636    }
 5637
 5638    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5639        self.context_menu
 5640            .borrow()
 5641            .as_ref()
 5642            .map(|menu| menu.origin())
 5643    }
 5644
 5645    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5646        px(30.)
 5647    }
 5648
 5649    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5650        if self.read_only(cx) {
 5651            cx.theme().players().read_only()
 5652        } else {
 5653            self.style.as_ref().unwrap().local_player
 5654        }
 5655    }
 5656
 5657    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5658        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5659        let accept_keystroke = accept_binding.keystroke()?;
 5660
 5661        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5662
 5663        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5664            Color::Accent
 5665        } else {
 5666            Color::Muted
 5667        };
 5668
 5669        h_flex()
 5670            .px_0p5()
 5671            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5672            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5673            .text_size(TextSize::XSmall.rems(cx))
 5674            .child(h_flex().children(ui::render_modifiers(
 5675                &accept_keystroke.modifiers,
 5676                PlatformStyle::platform(),
 5677                Some(modifiers_color),
 5678                Some(IconSize::XSmall.rems().into()),
 5679                true,
 5680            )))
 5681            .when(is_platform_style_mac, |parent| {
 5682                parent.child(accept_keystroke.key.clone())
 5683            })
 5684            .when(!is_platform_style_mac, |parent| {
 5685                parent.child(
 5686                    Key::new(
 5687                        util::capitalize(&accept_keystroke.key),
 5688                        Some(Color::Default),
 5689                    )
 5690                    .size(Some(IconSize::XSmall.rems().into())),
 5691                )
 5692            })
 5693            .into()
 5694    }
 5695
 5696    fn render_edit_prediction_line_popover(
 5697        &self,
 5698        label: impl Into<SharedString>,
 5699        icon: Option<IconName>,
 5700        window: &mut Window,
 5701        cx: &App,
 5702    ) -> Option<Div> {
 5703        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5704
 5705        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5706
 5707        let result = h_flex()
 5708            .gap_1()
 5709            .border_1()
 5710            .rounded_lg()
 5711            .shadow_sm()
 5712            .bg(bg_color)
 5713            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5714            .py_0p5()
 5715            .pl_1()
 5716            .pr(padding_right)
 5717            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5718            .child(Label::new(label).size(LabelSize::Small))
 5719            .when_some(icon, |element, icon| {
 5720                element.child(
 5721                    div()
 5722                        .mt(px(1.5))
 5723                        .child(Icon::new(icon).size(IconSize::Small)),
 5724                )
 5725            });
 5726
 5727        Some(result)
 5728    }
 5729
 5730    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5731        let accent_color = cx.theme().colors().text_accent;
 5732        let editor_bg_color = cx.theme().colors().editor_background;
 5733        editor_bg_color.blend(accent_color.opacity(0.1))
 5734    }
 5735
 5736    #[allow(clippy::too_many_arguments)]
 5737    fn render_edit_prediction_cursor_popover(
 5738        &self,
 5739        min_width: Pixels,
 5740        max_width: Pixels,
 5741        cursor_point: Point,
 5742        style: &EditorStyle,
 5743        accept_keystroke: &gpui::Keystroke,
 5744        _window: &Window,
 5745        cx: &mut Context<Editor>,
 5746    ) -> Option<AnyElement> {
 5747        let provider = self.edit_prediction_provider.as_ref()?;
 5748
 5749        if provider.provider.needs_terms_acceptance(cx) {
 5750            return Some(
 5751                h_flex()
 5752                    .min_w(min_width)
 5753                    .flex_1()
 5754                    .px_2()
 5755                    .py_1()
 5756                    .gap_3()
 5757                    .elevation_2(cx)
 5758                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5759                    .id("accept-terms")
 5760                    .cursor_pointer()
 5761                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5762                    .on_click(cx.listener(|this, _event, window, cx| {
 5763                        cx.stop_propagation();
 5764                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5765                        window.dispatch_action(
 5766                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5767                            cx,
 5768                        );
 5769                    }))
 5770                    .child(
 5771                        h_flex()
 5772                            .flex_1()
 5773                            .gap_2()
 5774                            .child(Icon::new(IconName::ZedPredict))
 5775                            .child(Label::new("Accept Terms of Service"))
 5776                            .child(div().w_full())
 5777                            .child(
 5778                                Icon::new(IconName::ArrowUpRight)
 5779                                    .color(Color::Muted)
 5780                                    .size(IconSize::Small),
 5781                            )
 5782                            .into_any_element(),
 5783                    )
 5784                    .into_any(),
 5785            );
 5786        }
 5787
 5788        let is_refreshing = provider.provider.is_refreshing(cx);
 5789
 5790        fn pending_completion_container() -> Div {
 5791            h_flex()
 5792                .h_full()
 5793                .flex_1()
 5794                .gap_2()
 5795                .child(Icon::new(IconName::ZedPredict))
 5796        }
 5797
 5798        let completion = match &self.active_inline_completion {
 5799            Some(completion) => match &completion.completion {
 5800                InlineCompletion::Move {
 5801                    target, snapshot, ..
 5802                } if !self.has_visible_completions_menu() => {
 5803                    use text::ToPoint as _;
 5804
 5805                    return Some(
 5806                        h_flex()
 5807                            .px_2()
 5808                            .py_1()
 5809                            .elevation_2(cx)
 5810                            .border_color(cx.theme().colors().border)
 5811                            .rounded_tl(px(0.))
 5812                            .gap_2()
 5813                            .child(
 5814                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5815                                    Icon::new(IconName::ZedPredictDown)
 5816                                } else {
 5817                                    Icon::new(IconName::ZedPredictUp)
 5818                                },
 5819                            )
 5820                            .child(Label::new("Hold").size(LabelSize::Small))
 5821                            .child(h_flex().children(ui::render_modifiers(
 5822                                &accept_keystroke.modifiers,
 5823                                PlatformStyle::platform(),
 5824                                Some(Color::Default),
 5825                                Some(IconSize::Small.rems().into()),
 5826                                false,
 5827                            )))
 5828                            .into_any(),
 5829                    );
 5830                }
 5831                _ => self.render_edit_prediction_cursor_popover_preview(
 5832                    completion,
 5833                    cursor_point,
 5834                    style,
 5835                    cx,
 5836                )?,
 5837            },
 5838
 5839            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5840                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5841                    stale_completion,
 5842                    cursor_point,
 5843                    style,
 5844                    cx,
 5845                )?,
 5846
 5847                None => {
 5848                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5849                }
 5850            },
 5851
 5852            None => pending_completion_container().child(Label::new("No Prediction")),
 5853        };
 5854
 5855        let completion = if is_refreshing {
 5856            completion
 5857                .with_animation(
 5858                    "loading-completion",
 5859                    Animation::new(Duration::from_secs(2))
 5860                        .repeat()
 5861                        .with_easing(pulsating_between(0.4, 0.8)),
 5862                    |label, delta| label.opacity(delta),
 5863                )
 5864                .into_any_element()
 5865        } else {
 5866            completion.into_any_element()
 5867        };
 5868
 5869        let has_completion = self.active_inline_completion.is_some();
 5870
 5871        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5872        Some(
 5873            h_flex()
 5874                .min_w(min_width)
 5875                .max_w(max_width)
 5876                .flex_1()
 5877                .elevation_2(cx)
 5878                .border_color(cx.theme().colors().border)
 5879                .child(
 5880                    div()
 5881                        .flex_1()
 5882                        .py_1()
 5883                        .px_2()
 5884                        .overflow_hidden()
 5885                        .child(completion),
 5886                )
 5887                .child(
 5888                    h_flex()
 5889                        .h_full()
 5890                        .border_l_1()
 5891                        .rounded_r_lg()
 5892                        .border_color(cx.theme().colors().border)
 5893                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5894                        .gap_1()
 5895                        .py_1()
 5896                        .px_2()
 5897                        .child(
 5898                            h_flex()
 5899                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5900                                .when(is_platform_style_mac, |parent| parent.gap_1())
 5901                                .child(h_flex().children(ui::render_modifiers(
 5902                                    &accept_keystroke.modifiers,
 5903                                    PlatformStyle::platform(),
 5904                                    Some(if !has_completion {
 5905                                        Color::Muted
 5906                                    } else {
 5907                                        Color::Default
 5908                                    }),
 5909                                    None,
 5910                                    false,
 5911                                ))),
 5912                        )
 5913                        .child(Label::new("Preview").into_any_element())
 5914                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5915                )
 5916                .into_any(),
 5917        )
 5918    }
 5919
 5920    fn render_edit_prediction_cursor_popover_preview(
 5921        &self,
 5922        completion: &InlineCompletionState,
 5923        cursor_point: Point,
 5924        style: &EditorStyle,
 5925        cx: &mut Context<Editor>,
 5926    ) -> Option<Div> {
 5927        use text::ToPoint as _;
 5928
 5929        fn render_relative_row_jump(
 5930            prefix: impl Into<String>,
 5931            current_row: u32,
 5932            target_row: u32,
 5933        ) -> Div {
 5934            let (row_diff, arrow) = if target_row < current_row {
 5935                (current_row - target_row, IconName::ArrowUp)
 5936            } else {
 5937                (target_row - current_row, IconName::ArrowDown)
 5938            };
 5939
 5940            h_flex()
 5941                .child(
 5942                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5943                        .color(Color::Muted)
 5944                        .size(LabelSize::Small),
 5945                )
 5946                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5947        }
 5948
 5949        match &completion.completion {
 5950            InlineCompletion::Move {
 5951                target, snapshot, ..
 5952            } => Some(
 5953                h_flex()
 5954                    .px_2()
 5955                    .gap_2()
 5956                    .flex_1()
 5957                    .child(
 5958                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5959                            Icon::new(IconName::ZedPredictDown)
 5960                        } else {
 5961                            Icon::new(IconName::ZedPredictUp)
 5962                        },
 5963                    )
 5964                    .child(Label::new("Jump to Edit")),
 5965            ),
 5966
 5967            InlineCompletion::Edit {
 5968                edits,
 5969                edit_preview,
 5970                snapshot,
 5971                display_mode: _,
 5972            } => {
 5973                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5974
 5975                let highlighted_edits = crate::inline_completion_edit_text(
 5976                    &snapshot,
 5977                    &edits,
 5978                    edit_preview.as_ref()?,
 5979                    true,
 5980                    cx,
 5981                );
 5982
 5983                let len_total = highlighted_edits.text.len();
 5984                let first_line = &highlighted_edits.text
 5985                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5986                let first_line_len = first_line.len();
 5987
 5988                let first_highlight_start = highlighted_edits
 5989                    .highlights
 5990                    .first()
 5991                    .map_or(0, |(range, _)| range.start);
 5992                let drop_prefix_len = first_line
 5993                    .char_indices()
 5994                    .find(|(_, c)| !c.is_whitespace())
 5995                    .map_or(first_highlight_start, |(ix, _)| {
 5996                        ix.min(first_highlight_start)
 5997                    });
 5998
 5999                let preview_text = &first_line[drop_prefix_len..];
 6000                let preview_len = preview_text.len();
 6001                let highlights = highlighted_edits
 6002                    .highlights
 6003                    .into_iter()
 6004                    .take_until(|(range, _)| range.start > first_line_len)
 6005                    .map(|(range, style)| {
 6006                        (
 6007                            range.start - drop_prefix_len
 6008                                ..(range.end - drop_prefix_len).min(preview_len),
 6009                            style,
 6010                        )
 6011                    });
 6012
 6013                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 6014                    .with_highlights(&style.text, highlights);
 6015
 6016                let preview = h_flex()
 6017                    .gap_1()
 6018                    .min_w_16()
 6019                    .child(styled_text)
 6020                    .when(len_total > first_line_len, |parent| parent.child(""));
 6021
 6022                let left = if first_edit_row != cursor_point.row {
 6023                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6024                        .into_any_element()
 6025                } else {
 6026                    Icon::new(IconName::ZedPredict).into_any_element()
 6027                };
 6028
 6029                Some(
 6030                    h_flex()
 6031                        .h_full()
 6032                        .flex_1()
 6033                        .gap_2()
 6034                        .pr_1()
 6035                        .overflow_x_hidden()
 6036                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6037                        .child(left)
 6038                        .child(preview),
 6039                )
 6040            }
 6041        }
 6042    }
 6043
 6044    fn render_context_menu(
 6045        &self,
 6046        style: &EditorStyle,
 6047        max_height_in_lines: u32,
 6048        y_flipped: bool,
 6049        window: &mut Window,
 6050        cx: &mut Context<Editor>,
 6051    ) -> Option<AnyElement> {
 6052        let menu = self.context_menu.borrow();
 6053        let menu = menu.as_ref()?;
 6054        if !menu.visible() {
 6055            return None;
 6056        };
 6057        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6058    }
 6059
 6060    fn render_context_menu_aside(
 6061        &self,
 6062        style: &EditorStyle,
 6063        max_size: Size<Pixels>,
 6064        cx: &mut Context<Editor>,
 6065    ) -> Option<AnyElement> {
 6066        self.context_menu.borrow().as_ref().and_then(|menu| {
 6067            if menu.visible() {
 6068                menu.render_aside(
 6069                    style,
 6070                    max_size,
 6071                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6072                    cx,
 6073                )
 6074            } else {
 6075                None
 6076            }
 6077        })
 6078    }
 6079
 6080    fn hide_context_menu(
 6081        &mut self,
 6082        window: &mut Window,
 6083        cx: &mut Context<Self>,
 6084    ) -> Option<CodeContextMenu> {
 6085        cx.notify();
 6086        self.completion_tasks.clear();
 6087        let context_menu = self.context_menu.borrow_mut().take();
 6088        self.stale_inline_completion_in_menu.take();
 6089        self.update_visible_inline_completion(window, cx);
 6090        context_menu
 6091    }
 6092
 6093    fn show_snippet_choices(
 6094        &mut self,
 6095        choices: &Vec<String>,
 6096        selection: Range<Anchor>,
 6097        cx: &mut Context<Self>,
 6098    ) {
 6099        if selection.start.buffer_id.is_none() {
 6100            return;
 6101        }
 6102        let buffer_id = selection.start.buffer_id.unwrap();
 6103        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6104        let id = post_inc(&mut self.next_completion_id);
 6105
 6106        if let Some(buffer) = buffer {
 6107            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6108                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6109            ));
 6110        }
 6111    }
 6112
 6113    pub fn insert_snippet(
 6114        &mut self,
 6115        insertion_ranges: &[Range<usize>],
 6116        snippet: Snippet,
 6117        window: &mut Window,
 6118        cx: &mut Context<Self>,
 6119    ) -> Result<()> {
 6120        struct Tabstop<T> {
 6121            is_end_tabstop: bool,
 6122            ranges: Vec<Range<T>>,
 6123            choices: Option<Vec<String>>,
 6124        }
 6125
 6126        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6127            let snippet_text: Arc<str> = snippet.text.clone().into();
 6128            buffer.edit(
 6129                insertion_ranges
 6130                    .iter()
 6131                    .cloned()
 6132                    .map(|range| (range, snippet_text.clone())),
 6133                Some(AutoindentMode::EachLine),
 6134                cx,
 6135            );
 6136
 6137            let snapshot = &*buffer.read(cx);
 6138            let snippet = &snippet;
 6139            snippet
 6140                .tabstops
 6141                .iter()
 6142                .map(|tabstop| {
 6143                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6144                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6145                    });
 6146                    let mut tabstop_ranges = tabstop
 6147                        .ranges
 6148                        .iter()
 6149                        .flat_map(|tabstop_range| {
 6150                            let mut delta = 0_isize;
 6151                            insertion_ranges.iter().map(move |insertion_range| {
 6152                                let insertion_start = insertion_range.start as isize + delta;
 6153                                delta +=
 6154                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6155
 6156                                let start = ((insertion_start + tabstop_range.start) as usize)
 6157                                    .min(snapshot.len());
 6158                                let end = ((insertion_start + tabstop_range.end) as usize)
 6159                                    .min(snapshot.len());
 6160                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6161                            })
 6162                        })
 6163                        .collect::<Vec<_>>();
 6164                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6165
 6166                    Tabstop {
 6167                        is_end_tabstop,
 6168                        ranges: tabstop_ranges,
 6169                        choices: tabstop.choices.clone(),
 6170                    }
 6171                })
 6172                .collect::<Vec<_>>()
 6173        });
 6174        if let Some(tabstop) = tabstops.first() {
 6175            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6176                s.select_ranges(tabstop.ranges.iter().cloned());
 6177            });
 6178
 6179            if let Some(choices) = &tabstop.choices {
 6180                if let Some(selection) = tabstop.ranges.first() {
 6181                    self.show_snippet_choices(choices, selection.clone(), cx)
 6182                }
 6183            }
 6184
 6185            // If we're already at the last tabstop and it's at the end of the snippet,
 6186            // we're done, we don't need to keep the state around.
 6187            if !tabstop.is_end_tabstop {
 6188                let choices = tabstops
 6189                    .iter()
 6190                    .map(|tabstop| tabstop.choices.clone())
 6191                    .collect();
 6192
 6193                let ranges = tabstops
 6194                    .into_iter()
 6195                    .map(|tabstop| tabstop.ranges)
 6196                    .collect::<Vec<_>>();
 6197
 6198                self.snippet_stack.push(SnippetState {
 6199                    active_index: 0,
 6200                    ranges,
 6201                    choices,
 6202                });
 6203            }
 6204
 6205            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6206            if self.autoclose_regions.is_empty() {
 6207                let snapshot = self.buffer.read(cx).snapshot(cx);
 6208                for selection in &mut self.selections.all::<Point>(cx) {
 6209                    let selection_head = selection.head();
 6210                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6211                        continue;
 6212                    };
 6213
 6214                    let mut bracket_pair = None;
 6215                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6216                    let prev_chars = snapshot
 6217                        .reversed_chars_at(selection_head)
 6218                        .collect::<String>();
 6219                    for (pair, enabled) in scope.brackets() {
 6220                        if enabled
 6221                            && pair.close
 6222                            && prev_chars.starts_with(pair.start.as_str())
 6223                            && next_chars.starts_with(pair.end.as_str())
 6224                        {
 6225                            bracket_pair = Some(pair.clone());
 6226                            break;
 6227                        }
 6228                    }
 6229                    if let Some(pair) = bracket_pair {
 6230                        let start = snapshot.anchor_after(selection_head);
 6231                        let end = snapshot.anchor_after(selection_head);
 6232                        self.autoclose_regions.push(AutocloseRegion {
 6233                            selection_id: selection.id,
 6234                            range: start..end,
 6235                            pair,
 6236                        });
 6237                    }
 6238                }
 6239            }
 6240        }
 6241        Ok(())
 6242    }
 6243
 6244    pub fn move_to_next_snippet_tabstop(
 6245        &mut self,
 6246        window: &mut Window,
 6247        cx: &mut Context<Self>,
 6248    ) -> bool {
 6249        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6250    }
 6251
 6252    pub fn move_to_prev_snippet_tabstop(
 6253        &mut self,
 6254        window: &mut Window,
 6255        cx: &mut Context<Self>,
 6256    ) -> bool {
 6257        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6258    }
 6259
 6260    pub fn move_to_snippet_tabstop(
 6261        &mut self,
 6262        bias: Bias,
 6263        window: &mut Window,
 6264        cx: &mut Context<Self>,
 6265    ) -> bool {
 6266        if let Some(mut snippet) = self.snippet_stack.pop() {
 6267            match bias {
 6268                Bias::Left => {
 6269                    if snippet.active_index > 0 {
 6270                        snippet.active_index -= 1;
 6271                    } else {
 6272                        self.snippet_stack.push(snippet);
 6273                        return false;
 6274                    }
 6275                }
 6276                Bias::Right => {
 6277                    if snippet.active_index + 1 < snippet.ranges.len() {
 6278                        snippet.active_index += 1;
 6279                    } else {
 6280                        self.snippet_stack.push(snippet);
 6281                        return false;
 6282                    }
 6283                }
 6284            }
 6285            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6286                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6287                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6288                });
 6289
 6290                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6291                    if let Some(selection) = current_ranges.first() {
 6292                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6293                    }
 6294                }
 6295
 6296                // If snippet state is not at the last tabstop, push it back on the stack
 6297                if snippet.active_index + 1 < snippet.ranges.len() {
 6298                    self.snippet_stack.push(snippet);
 6299                }
 6300                return true;
 6301            }
 6302        }
 6303
 6304        false
 6305    }
 6306
 6307    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6308        self.transact(window, cx, |this, window, cx| {
 6309            this.select_all(&SelectAll, window, cx);
 6310            this.insert("", window, cx);
 6311        });
 6312    }
 6313
 6314    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6315        self.transact(window, cx, |this, window, cx| {
 6316            this.select_autoclose_pair(window, cx);
 6317            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6318            if !this.linked_edit_ranges.is_empty() {
 6319                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6320                let snapshot = this.buffer.read(cx).snapshot(cx);
 6321
 6322                for selection in selections.iter() {
 6323                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6324                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6325                    if selection_start.buffer_id != selection_end.buffer_id {
 6326                        continue;
 6327                    }
 6328                    if let Some(ranges) =
 6329                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6330                    {
 6331                        for (buffer, entries) in ranges {
 6332                            linked_ranges.entry(buffer).or_default().extend(entries);
 6333                        }
 6334                    }
 6335                }
 6336            }
 6337
 6338            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6339            if !this.selections.line_mode {
 6340                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6341                for selection in &mut selections {
 6342                    if selection.is_empty() {
 6343                        let old_head = selection.head();
 6344                        let mut new_head =
 6345                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6346                                .to_point(&display_map);
 6347                        if let Some((buffer, line_buffer_range)) = display_map
 6348                            .buffer_snapshot
 6349                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6350                        {
 6351                            let indent_size =
 6352                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6353                            let indent_len = match indent_size.kind {
 6354                                IndentKind::Space => {
 6355                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6356                                }
 6357                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6358                            };
 6359                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6360                                let indent_len = indent_len.get();
 6361                                new_head = cmp::min(
 6362                                    new_head,
 6363                                    MultiBufferPoint::new(
 6364                                        old_head.row,
 6365                                        ((old_head.column - 1) / indent_len) * indent_len,
 6366                                    ),
 6367                                );
 6368                            }
 6369                        }
 6370
 6371                        selection.set_head(new_head, SelectionGoal::None);
 6372                    }
 6373                }
 6374            }
 6375
 6376            this.signature_help_state.set_backspace_pressed(true);
 6377            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6378                s.select(selections)
 6379            });
 6380            this.insert("", window, cx);
 6381            let empty_str: Arc<str> = Arc::from("");
 6382            for (buffer, edits) in linked_ranges {
 6383                let snapshot = buffer.read(cx).snapshot();
 6384                use text::ToPoint as TP;
 6385
 6386                let edits = edits
 6387                    .into_iter()
 6388                    .map(|range| {
 6389                        let end_point = TP::to_point(&range.end, &snapshot);
 6390                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6391
 6392                        if end_point == start_point {
 6393                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6394                                .saturating_sub(1);
 6395                            start_point =
 6396                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6397                        };
 6398
 6399                        (start_point..end_point, empty_str.clone())
 6400                    })
 6401                    .sorted_by_key(|(range, _)| range.start)
 6402                    .collect::<Vec<_>>();
 6403                buffer.update(cx, |this, cx| {
 6404                    this.edit(edits, None, cx);
 6405                })
 6406            }
 6407            this.refresh_inline_completion(true, false, window, cx);
 6408            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6409        });
 6410    }
 6411
 6412    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6413        self.transact(window, cx, |this, window, cx| {
 6414            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6415                let line_mode = s.line_mode;
 6416                s.move_with(|map, selection| {
 6417                    if selection.is_empty() && !line_mode {
 6418                        let cursor = movement::right(map, selection.head());
 6419                        selection.end = cursor;
 6420                        selection.reversed = true;
 6421                        selection.goal = SelectionGoal::None;
 6422                    }
 6423                })
 6424            });
 6425            this.insert("", window, cx);
 6426            this.refresh_inline_completion(true, false, window, cx);
 6427        });
 6428    }
 6429
 6430    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6431        if self.move_to_prev_snippet_tabstop(window, cx) {
 6432            return;
 6433        }
 6434
 6435        self.outdent(&Outdent, window, cx);
 6436    }
 6437
 6438    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6439        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6440            return;
 6441        }
 6442
 6443        let mut selections = self.selections.all_adjusted(cx);
 6444        let buffer = self.buffer.read(cx);
 6445        let snapshot = buffer.snapshot(cx);
 6446        let rows_iter = selections.iter().map(|s| s.head().row);
 6447        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6448
 6449        let mut edits = Vec::new();
 6450        let mut prev_edited_row = 0;
 6451        let mut row_delta = 0;
 6452        for selection in &mut selections {
 6453            if selection.start.row != prev_edited_row {
 6454                row_delta = 0;
 6455            }
 6456            prev_edited_row = selection.end.row;
 6457
 6458            // If the selection is non-empty, then increase the indentation of the selected lines.
 6459            if !selection.is_empty() {
 6460                row_delta =
 6461                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6462                continue;
 6463            }
 6464
 6465            // If the selection is empty and the cursor is in the leading whitespace before the
 6466            // suggested indentation, then auto-indent the line.
 6467            let cursor = selection.head();
 6468            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6469            if let Some(suggested_indent) =
 6470                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6471            {
 6472                if cursor.column < suggested_indent.len
 6473                    && cursor.column <= current_indent.len
 6474                    && current_indent.len <= suggested_indent.len
 6475                {
 6476                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6477                    selection.end = selection.start;
 6478                    if row_delta == 0 {
 6479                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6480                            cursor.row,
 6481                            current_indent,
 6482                            suggested_indent,
 6483                        ));
 6484                        row_delta = suggested_indent.len - current_indent.len;
 6485                    }
 6486                    continue;
 6487                }
 6488            }
 6489
 6490            // Otherwise, insert a hard or soft tab.
 6491            let settings = buffer.settings_at(cursor, cx);
 6492            let tab_size = if settings.hard_tabs {
 6493                IndentSize::tab()
 6494            } else {
 6495                let tab_size = settings.tab_size.get();
 6496                let char_column = snapshot
 6497                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6498                    .flat_map(str::chars)
 6499                    .count()
 6500                    + row_delta as usize;
 6501                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6502                IndentSize::spaces(chars_to_next_tab_stop)
 6503            };
 6504            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6505            selection.end = selection.start;
 6506            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6507            row_delta += tab_size.len;
 6508        }
 6509
 6510        self.transact(window, cx, |this, window, cx| {
 6511            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6512            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6513                s.select(selections)
 6514            });
 6515            this.refresh_inline_completion(true, false, window, cx);
 6516        });
 6517    }
 6518
 6519    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6520        if self.read_only(cx) {
 6521            return;
 6522        }
 6523        let mut selections = self.selections.all::<Point>(cx);
 6524        let mut prev_edited_row = 0;
 6525        let mut row_delta = 0;
 6526        let mut edits = Vec::new();
 6527        let buffer = self.buffer.read(cx);
 6528        let snapshot = buffer.snapshot(cx);
 6529        for selection in &mut selections {
 6530            if selection.start.row != prev_edited_row {
 6531                row_delta = 0;
 6532            }
 6533            prev_edited_row = selection.end.row;
 6534
 6535            row_delta =
 6536                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6537        }
 6538
 6539        self.transact(window, cx, |this, window, cx| {
 6540            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6541            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6542                s.select(selections)
 6543            });
 6544        });
 6545    }
 6546
 6547    fn indent_selection(
 6548        buffer: &MultiBuffer,
 6549        snapshot: &MultiBufferSnapshot,
 6550        selection: &mut Selection<Point>,
 6551        edits: &mut Vec<(Range<Point>, String)>,
 6552        delta_for_start_row: u32,
 6553        cx: &App,
 6554    ) -> u32 {
 6555        let settings = buffer.settings_at(selection.start, cx);
 6556        let tab_size = settings.tab_size.get();
 6557        let indent_kind = if settings.hard_tabs {
 6558            IndentKind::Tab
 6559        } else {
 6560            IndentKind::Space
 6561        };
 6562        let mut start_row = selection.start.row;
 6563        let mut end_row = selection.end.row + 1;
 6564
 6565        // If a selection ends at the beginning of a line, don't indent
 6566        // that last line.
 6567        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6568            end_row -= 1;
 6569        }
 6570
 6571        // Avoid re-indenting a row that has already been indented by a
 6572        // previous selection, but still update this selection's column
 6573        // to reflect that indentation.
 6574        if delta_for_start_row > 0 {
 6575            start_row += 1;
 6576            selection.start.column += delta_for_start_row;
 6577            if selection.end.row == selection.start.row {
 6578                selection.end.column += delta_for_start_row;
 6579            }
 6580        }
 6581
 6582        let mut delta_for_end_row = 0;
 6583        let has_multiple_rows = start_row + 1 != end_row;
 6584        for row in start_row..end_row {
 6585            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6586            let indent_delta = match (current_indent.kind, indent_kind) {
 6587                (IndentKind::Space, IndentKind::Space) => {
 6588                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6589                    IndentSize::spaces(columns_to_next_tab_stop)
 6590                }
 6591                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6592                (_, IndentKind::Tab) => IndentSize::tab(),
 6593            };
 6594
 6595            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6596                0
 6597            } else {
 6598                selection.start.column
 6599            };
 6600            let row_start = Point::new(row, start);
 6601            edits.push((
 6602                row_start..row_start,
 6603                indent_delta.chars().collect::<String>(),
 6604            ));
 6605
 6606            // Update this selection's endpoints to reflect the indentation.
 6607            if row == selection.start.row {
 6608                selection.start.column += indent_delta.len;
 6609            }
 6610            if row == selection.end.row {
 6611                selection.end.column += indent_delta.len;
 6612                delta_for_end_row = indent_delta.len;
 6613            }
 6614        }
 6615
 6616        if selection.start.row == selection.end.row {
 6617            delta_for_start_row + delta_for_end_row
 6618        } else {
 6619            delta_for_end_row
 6620        }
 6621    }
 6622
 6623    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6624        if self.read_only(cx) {
 6625            return;
 6626        }
 6627        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6628        let selections = self.selections.all::<Point>(cx);
 6629        let mut deletion_ranges = Vec::new();
 6630        let mut last_outdent = None;
 6631        {
 6632            let buffer = self.buffer.read(cx);
 6633            let snapshot = buffer.snapshot(cx);
 6634            for selection in &selections {
 6635                let settings = buffer.settings_at(selection.start, cx);
 6636                let tab_size = settings.tab_size.get();
 6637                let mut rows = selection.spanned_rows(false, &display_map);
 6638
 6639                // Avoid re-outdenting a row that has already been outdented by a
 6640                // previous selection.
 6641                if let Some(last_row) = last_outdent {
 6642                    if last_row == rows.start {
 6643                        rows.start = rows.start.next_row();
 6644                    }
 6645                }
 6646                let has_multiple_rows = rows.len() > 1;
 6647                for row in rows.iter_rows() {
 6648                    let indent_size = snapshot.indent_size_for_line(row);
 6649                    if indent_size.len > 0 {
 6650                        let deletion_len = match indent_size.kind {
 6651                            IndentKind::Space => {
 6652                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6653                                if columns_to_prev_tab_stop == 0 {
 6654                                    tab_size
 6655                                } else {
 6656                                    columns_to_prev_tab_stop
 6657                                }
 6658                            }
 6659                            IndentKind::Tab => 1,
 6660                        };
 6661                        let start = if has_multiple_rows
 6662                            || deletion_len > selection.start.column
 6663                            || indent_size.len < selection.start.column
 6664                        {
 6665                            0
 6666                        } else {
 6667                            selection.start.column - deletion_len
 6668                        };
 6669                        deletion_ranges.push(
 6670                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6671                        );
 6672                        last_outdent = Some(row);
 6673                    }
 6674                }
 6675            }
 6676        }
 6677
 6678        self.transact(window, cx, |this, window, cx| {
 6679            this.buffer.update(cx, |buffer, cx| {
 6680                let empty_str: Arc<str> = Arc::default();
 6681                buffer.edit(
 6682                    deletion_ranges
 6683                        .into_iter()
 6684                        .map(|range| (range, empty_str.clone())),
 6685                    None,
 6686                    cx,
 6687                );
 6688            });
 6689            let selections = this.selections.all::<usize>(cx);
 6690            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6691                s.select(selections)
 6692            });
 6693        });
 6694    }
 6695
 6696    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6697        if self.read_only(cx) {
 6698            return;
 6699        }
 6700        let selections = self
 6701            .selections
 6702            .all::<usize>(cx)
 6703            .into_iter()
 6704            .map(|s| s.range());
 6705
 6706        self.transact(window, cx, |this, window, cx| {
 6707            this.buffer.update(cx, |buffer, cx| {
 6708                buffer.autoindent_ranges(selections, cx);
 6709            });
 6710            let selections = this.selections.all::<usize>(cx);
 6711            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6712                s.select(selections)
 6713            });
 6714        });
 6715    }
 6716
 6717    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6719        let selections = self.selections.all::<Point>(cx);
 6720
 6721        let mut new_cursors = Vec::new();
 6722        let mut edit_ranges = Vec::new();
 6723        let mut selections = selections.iter().peekable();
 6724        while let Some(selection) = selections.next() {
 6725            let mut rows = selection.spanned_rows(false, &display_map);
 6726            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6727
 6728            // Accumulate contiguous regions of rows that we want to delete.
 6729            while let Some(next_selection) = selections.peek() {
 6730                let next_rows = next_selection.spanned_rows(false, &display_map);
 6731                if next_rows.start <= rows.end {
 6732                    rows.end = next_rows.end;
 6733                    selections.next().unwrap();
 6734                } else {
 6735                    break;
 6736                }
 6737            }
 6738
 6739            let buffer = &display_map.buffer_snapshot;
 6740            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6741            let edit_end;
 6742            let cursor_buffer_row;
 6743            if buffer.max_point().row >= rows.end.0 {
 6744                // If there's a line after the range, delete the \n from the end of the row range
 6745                // and position the cursor on the next line.
 6746                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6747                cursor_buffer_row = rows.end;
 6748            } else {
 6749                // If there isn't a line after the range, delete the \n from the line before the
 6750                // start of the row range and position the cursor there.
 6751                edit_start = edit_start.saturating_sub(1);
 6752                edit_end = buffer.len();
 6753                cursor_buffer_row = rows.start.previous_row();
 6754            }
 6755
 6756            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6757            *cursor.column_mut() =
 6758                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6759
 6760            new_cursors.push((
 6761                selection.id,
 6762                buffer.anchor_after(cursor.to_point(&display_map)),
 6763            ));
 6764            edit_ranges.push(edit_start..edit_end);
 6765        }
 6766
 6767        self.transact(window, cx, |this, window, cx| {
 6768            let buffer = this.buffer.update(cx, |buffer, cx| {
 6769                let empty_str: Arc<str> = Arc::default();
 6770                buffer.edit(
 6771                    edit_ranges
 6772                        .into_iter()
 6773                        .map(|range| (range, empty_str.clone())),
 6774                    None,
 6775                    cx,
 6776                );
 6777                buffer.snapshot(cx)
 6778            });
 6779            let new_selections = new_cursors
 6780                .into_iter()
 6781                .map(|(id, cursor)| {
 6782                    let cursor = cursor.to_point(&buffer);
 6783                    Selection {
 6784                        id,
 6785                        start: cursor,
 6786                        end: cursor,
 6787                        reversed: false,
 6788                        goal: SelectionGoal::None,
 6789                    }
 6790                })
 6791                .collect();
 6792
 6793            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6794                s.select(new_selections);
 6795            });
 6796        });
 6797    }
 6798
 6799    pub fn join_lines_impl(
 6800        &mut self,
 6801        insert_whitespace: bool,
 6802        window: &mut Window,
 6803        cx: &mut Context<Self>,
 6804    ) {
 6805        if self.read_only(cx) {
 6806            return;
 6807        }
 6808        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6809        for selection in self.selections.all::<Point>(cx) {
 6810            let start = MultiBufferRow(selection.start.row);
 6811            // Treat single line selections as if they include the next line. Otherwise this action
 6812            // would do nothing for single line selections individual cursors.
 6813            let end = if selection.start.row == selection.end.row {
 6814                MultiBufferRow(selection.start.row + 1)
 6815            } else {
 6816                MultiBufferRow(selection.end.row)
 6817            };
 6818
 6819            if let Some(last_row_range) = row_ranges.last_mut() {
 6820                if start <= last_row_range.end {
 6821                    last_row_range.end = end;
 6822                    continue;
 6823                }
 6824            }
 6825            row_ranges.push(start..end);
 6826        }
 6827
 6828        let snapshot = self.buffer.read(cx).snapshot(cx);
 6829        let mut cursor_positions = Vec::new();
 6830        for row_range in &row_ranges {
 6831            let anchor = snapshot.anchor_before(Point::new(
 6832                row_range.end.previous_row().0,
 6833                snapshot.line_len(row_range.end.previous_row()),
 6834            ));
 6835            cursor_positions.push(anchor..anchor);
 6836        }
 6837
 6838        self.transact(window, cx, |this, window, cx| {
 6839            for row_range in row_ranges.into_iter().rev() {
 6840                for row in row_range.iter_rows().rev() {
 6841                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6842                    let next_line_row = row.next_row();
 6843                    let indent = snapshot.indent_size_for_line(next_line_row);
 6844                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6845
 6846                    let replace =
 6847                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6848                            " "
 6849                        } else {
 6850                            ""
 6851                        };
 6852
 6853                    this.buffer.update(cx, |buffer, cx| {
 6854                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6855                    });
 6856                }
 6857            }
 6858
 6859            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6860                s.select_anchor_ranges(cursor_positions)
 6861            });
 6862        });
 6863    }
 6864
 6865    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6866        self.join_lines_impl(true, window, cx);
 6867    }
 6868
 6869    pub fn sort_lines_case_sensitive(
 6870        &mut self,
 6871        _: &SortLinesCaseSensitive,
 6872        window: &mut Window,
 6873        cx: &mut Context<Self>,
 6874    ) {
 6875        self.manipulate_lines(window, cx, |lines| lines.sort())
 6876    }
 6877
 6878    pub fn sort_lines_case_insensitive(
 6879        &mut self,
 6880        _: &SortLinesCaseInsensitive,
 6881        window: &mut Window,
 6882        cx: &mut Context<Self>,
 6883    ) {
 6884        self.manipulate_lines(window, cx, |lines| {
 6885            lines.sort_by_key(|line| line.to_lowercase())
 6886        })
 6887    }
 6888
 6889    pub fn unique_lines_case_insensitive(
 6890        &mut self,
 6891        _: &UniqueLinesCaseInsensitive,
 6892        window: &mut Window,
 6893        cx: &mut Context<Self>,
 6894    ) {
 6895        self.manipulate_lines(window, cx, |lines| {
 6896            let mut seen = HashSet::default();
 6897            lines.retain(|line| seen.insert(line.to_lowercase()));
 6898        })
 6899    }
 6900
 6901    pub fn unique_lines_case_sensitive(
 6902        &mut self,
 6903        _: &UniqueLinesCaseSensitive,
 6904        window: &mut Window,
 6905        cx: &mut Context<Self>,
 6906    ) {
 6907        self.manipulate_lines(window, cx, |lines| {
 6908            let mut seen = HashSet::default();
 6909            lines.retain(|line| seen.insert(*line));
 6910        })
 6911    }
 6912
 6913    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6914        let mut revert_changes = HashMap::default();
 6915        let snapshot = self.snapshot(window, cx);
 6916        for hunk in snapshot
 6917            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6918        {
 6919            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6920        }
 6921        if !revert_changes.is_empty() {
 6922            self.transact(window, cx, |editor, window, cx| {
 6923                editor.revert(revert_changes, window, cx);
 6924            });
 6925        }
 6926    }
 6927
 6928    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6929        let Some(project) = self.project.clone() else {
 6930            return;
 6931        };
 6932        self.reload(project, window, cx)
 6933            .detach_and_notify_err(window, cx);
 6934    }
 6935
 6936    pub fn revert_selected_hunks(
 6937        &mut self,
 6938        _: &RevertSelectedHunks,
 6939        window: &mut Window,
 6940        cx: &mut Context<Self>,
 6941    ) {
 6942        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6943        self.revert_hunks_in_ranges(selections, window, cx);
 6944    }
 6945
 6946    fn revert_hunks_in_ranges(
 6947        &mut self,
 6948        ranges: impl Iterator<Item = Range<Point>>,
 6949        window: &mut Window,
 6950        cx: &mut Context<Editor>,
 6951    ) {
 6952        let mut revert_changes = HashMap::default();
 6953        let snapshot = self.snapshot(window, cx);
 6954        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6955            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6956        }
 6957        if !revert_changes.is_empty() {
 6958            self.transact(window, cx, |editor, window, cx| {
 6959                editor.revert(revert_changes, window, cx);
 6960            });
 6961        }
 6962    }
 6963
 6964    pub fn open_active_item_in_terminal(
 6965        &mut self,
 6966        _: &OpenInTerminal,
 6967        window: &mut Window,
 6968        cx: &mut Context<Self>,
 6969    ) {
 6970        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6971            let project_path = buffer.read(cx).project_path(cx)?;
 6972            let project = self.project.as_ref()?.read(cx);
 6973            let entry = project.entry_for_path(&project_path, cx)?;
 6974            let parent = match &entry.canonical_path {
 6975                Some(canonical_path) => canonical_path.to_path_buf(),
 6976                None => project.absolute_path(&project_path, cx)?,
 6977            }
 6978            .parent()?
 6979            .to_path_buf();
 6980            Some(parent)
 6981        }) {
 6982            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6983        }
 6984    }
 6985
 6986    pub fn prepare_revert_change(
 6987        &self,
 6988        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6989        hunk: &MultiBufferDiffHunk,
 6990        cx: &mut App,
 6991    ) -> Option<()> {
 6992        let buffer = self.buffer.read(cx);
 6993        let diff = buffer.diff_for(hunk.buffer_id)?;
 6994        let buffer = buffer.buffer(hunk.buffer_id)?;
 6995        let buffer = buffer.read(cx);
 6996        let original_text = diff
 6997            .read(cx)
 6998            .base_text()
 6999            .as_ref()?
 7000            .as_rope()
 7001            .slice(hunk.diff_base_byte_range.clone());
 7002        let buffer_snapshot = buffer.snapshot();
 7003        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7004        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7005            probe
 7006                .0
 7007                .start
 7008                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7009                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7010        }) {
 7011            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7012            Some(())
 7013        } else {
 7014            None
 7015        }
 7016    }
 7017
 7018    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7019        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7020    }
 7021
 7022    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7023        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7024    }
 7025
 7026    fn manipulate_lines<Fn>(
 7027        &mut self,
 7028        window: &mut Window,
 7029        cx: &mut Context<Self>,
 7030        mut callback: Fn,
 7031    ) where
 7032        Fn: FnMut(&mut Vec<&str>),
 7033    {
 7034        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7035        let buffer = self.buffer.read(cx).snapshot(cx);
 7036
 7037        let mut edits = Vec::new();
 7038
 7039        let selections = self.selections.all::<Point>(cx);
 7040        let mut selections = selections.iter().peekable();
 7041        let mut contiguous_row_selections = Vec::new();
 7042        let mut new_selections = Vec::new();
 7043        let mut added_lines = 0;
 7044        let mut removed_lines = 0;
 7045
 7046        while let Some(selection) = selections.next() {
 7047            let (start_row, end_row) = consume_contiguous_rows(
 7048                &mut contiguous_row_selections,
 7049                selection,
 7050                &display_map,
 7051                &mut selections,
 7052            );
 7053
 7054            let start_point = Point::new(start_row.0, 0);
 7055            let end_point = Point::new(
 7056                end_row.previous_row().0,
 7057                buffer.line_len(end_row.previous_row()),
 7058            );
 7059            let text = buffer
 7060                .text_for_range(start_point..end_point)
 7061                .collect::<String>();
 7062
 7063            let mut lines = text.split('\n').collect_vec();
 7064
 7065            let lines_before = lines.len();
 7066            callback(&mut lines);
 7067            let lines_after = lines.len();
 7068
 7069            edits.push((start_point..end_point, lines.join("\n")));
 7070
 7071            // Selections must change based on added and removed line count
 7072            let start_row =
 7073                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7074            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7075            new_selections.push(Selection {
 7076                id: selection.id,
 7077                start: start_row,
 7078                end: end_row,
 7079                goal: SelectionGoal::None,
 7080                reversed: selection.reversed,
 7081            });
 7082
 7083            if lines_after > lines_before {
 7084                added_lines += lines_after - lines_before;
 7085            } else if lines_before > lines_after {
 7086                removed_lines += lines_before - lines_after;
 7087            }
 7088        }
 7089
 7090        self.transact(window, cx, |this, window, cx| {
 7091            let buffer = this.buffer.update(cx, |buffer, cx| {
 7092                buffer.edit(edits, None, cx);
 7093                buffer.snapshot(cx)
 7094            });
 7095
 7096            // Recalculate offsets on newly edited buffer
 7097            let new_selections = new_selections
 7098                .iter()
 7099                .map(|s| {
 7100                    let start_point = Point::new(s.start.0, 0);
 7101                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7102                    Selection {
 7103                        id: s.id,
 7104                        start: buffer.point_to_offset(start_point),
 7105                        end: buffer.point_to_offset(end_point),
 7106                        goal: s.goal,
 7107                        reversed: s.reversed,
 7108                    }
 7109                })
 7110                .collect();
 7111
 7112            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7113                s.select(new_selections);
 7114            });
 7115
 7116            this.request_autoscroll(Autoscroll::fit(), cx);
 7117        });
 7118    }
 7119
 7120    pub fn convert_to_upper_case(
 7121        &mut self,
 7122        _: &ConvertToUpperCase,
 7123        window: &mut Window,
 7124        cx: &mut Context<Self>,
 7125    ) {
 7126        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7127    }
 7128
 7129    pub fn convert_to_lower_case(
 7130        &mut self,
 7131        _: &ConvertToLowerCase,
 7132        window: &mut Window,
 7133        cx: &mut Context<Self>,
 7134    ) {
 7135        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7136    }
 7137
 7138    pub fn convert_to_title_case(
 7139        &mut self,
 7140        _: &ConvertToTitleCase,
 7141        window: &mut Window,
 7142        cx: &mut Context<Self>,
 7143    ) {
 7144        self.manipulate_text(window, cx, |text| {
 7145            text.split('\n')
 7146                .map(|line| line.to_case(Case::Title))
 7147                .join("\n")
 7148        })
 7149    }
 7150
 7151    pub fn convert_to_snake_case(
 7152        &mut self,
 7153        _: &ConvertToSnakeCase,
 7154        window: &mut Window,
 7155        cx: &mut Context<Self>,
 7156    ) {
 7157        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7158    }
 7159
 7160    pub fn convert_to_kebab_case(
 7161        &mut self,
 7162        _: &ConvertToKebabCase,
 7163        window: &mut Window,
 7164        cx: &mut Context<Self>,
 7165    ) {
 7166        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7167    }
 7168
 7169    pub fn convert_to_upper_camel_case(
 7170        &mut self,
 7171        _: &ConvertToUpperCamelCase,
 7172        window: &mut Window,
 7173        cx: &mut Context<Self>,
 7174    ) {
 7175        self.manipulate_text(window, cx, |text| {
 7176            text.split('\n')
 7177                .map(|line| line.to_case(Case::UpperCamel))
 7178                .join("\n")
 7179        })
 7180    }
 7181
 7182    pub fn convert_to_lower_camel_case(
 7183        &mut self,
 7184        _: &ConvertToLowerCamelCase,
 7185        window: &mut Window,
 7186        cx: &mut Context<Self>,
 7187    ) {
 7188        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7189    }
 7190
 7191    pub fn convert_to_opposite_case(
 7192        &mut self,
 7193        _: &ConvertToOppositeCase,
 7194        window: &mut Window,
 7195        cx: &mut Context<Self>,
 7196    ) {
 7197        self.manipulate_text(window, cx, |text| {
 7198            text.chars()
 7199                .fold(String::with_capacity(text.len()), |mut t, c| {
 7200                    if c.is_uppercase() {
 7201                        t.extend(c.to_lowercase());
 7202                    } else {
 7203                        t.extend(c.to_uppercase());
 7204                    }
 7205                    t
 7206                })
 7207        })
 7208    }
 7209
 7210    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7211    where
 7212        Fn: FnMut(&str) -> String,
 7213    {
 7214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7215        let buffer = self.buffer.read(cx).snapshot(cx);
 7216
 7217        let mut new_selections = Vec::new();
 7218        let mut edits = Vec::new();
 7219        let mut selection_adjustment = 0i32;
 7220
 7221        for selection in self.selections.all::<usize>(cx) {
 7222            let selection_is_empty = selection.is_empty();
 7223
 7224            let (start, end) = if selection_is_empty {
 7225                let word_range = movement::surrounding_word(
 7226                    &display_map,
 7227                    selection.start.to_display_point(&display_map),
 7228                );
 7229                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7230                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7231                (start, end)
 7232            } else {
 7233                (selection.start, selection.end)
 7234            };
 7235
 7236            let text = buffer.text_for_range(start..end).collect::<String>();
 7237            let old_length = text.len() as i32;
 7238            let text = callback(&text);
 7239
 7240            new_selections.push(Selection {
 7241                start: (start as i32 - selection_adjustment) as usize,
 7242                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7243                goal: SelectionGoal::None,
 7244                ..selection
 7245            });
 7246
 7247            selection_adjustment += old_length - text.len() as i32;
 7248
 7249            edits.push((start..end, text));
 7250        }
 7251
 7252        self.transact(window, cx, |this, window, cx| {
 7253            this.buffer.update(cx, |buffer, cx| {
 7254                buffer.edit(edits, None, cx);
 7255            });
 7256
 7257            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7258                s.select(new_selections);
 7259            });
 7260
 7261            this.request_autoscroll(Autoscroll::fit(), cx);
 7262        });
 7263    }
 7264
 7265    pub fn duplicate(
 7266        &mut self,
 7267        upwards: bool,
 7268        whole_lines: bool,
 7269        window: &mut Window,
 7270        cx: &mut Context<Self>,
 7271    ) {
 7272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7273        let buffer = &display_map.buffer_snapshot;
 7274        let selections = self.selections.all::<Point>(cx);
 7275
 7276        let mut edits = Vec::new();
 7277        let mut selections_iter = selections.iter().peekable();
 7278        while let Some(selection) = selections_iter.next() {
 7279            let mut rows = selection.spanned_rows(false, &display_map);
 7280            // duplicate line-wise
 7281            if whole_lines || selection.start == selection.end {
 7282                // Avoid duplicating the same lines twice.
 7283                while let Some(next_selection) = selections_iter.peek() {
 7284                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7285                    if next_rows.start < rows.end {
 7286                        rows.end = next_rows.end;
 7287                        selections_iter.next().unwrap();
 7288                    } else {
 7289                        break;
 7290                    }
 7291                }
 7292
 7293                // Copy the text from the selected row region and splice it either at the start
 7294                // or end of the region.
 7295                let start = Point::new(rows.start.0, 0);
 7296                let end = Point::new(
 7297                    rows.end.previous_row().0,
 7298                    buffer.line_len(rows.end.previous_row()),
 7299                );
 7300                let text = buffer
 7301                    .text_for_range(start..end)
 7302                    .chain(Some("\n"))
 7303                    .collect::<String>();
 7304                let insert_location = if upwards {
 7305                    Point::new(rows.end.0, 0)
 7306                } else {
 7307                    start
 7308                };
 7309                edits.push((insert_location..insert_location, text));
 7310            } else {
 7311                // duplicate character-wise
 7312                let start = selection.start;
 7313                let end = selection.end;
 7314                let text = buffer.text_for_range(start..end).collect::<String>();
 7315                edits.push((selection.end..selection.end, text));
 7316            }
 7317        }
 7318
 7319        self.transact(window, cx, |this, _, cx| {
 7320            this.buffer.update(cx, |buffer, cx| {
 7321                buffer.edit(edits, None, cx);
 7322            });
 7323
 7324            this.request_autoscroll(Autoscroll::fit(), cx);
 7325        });
 7326    }
 7327
 7328    pub fn duplicate_line_up(
 7329        &mut self,
 7330        _: &DuplicateLineUp,
 7331        window: &mut Window,
 7332        cx: &mut Context<Self>,
 7333    ) {
 7334        self.duplicate(true, true, window, cx);
 7335    }
 7336
 7337    pub fn duplicate_line_down(
 7338        &mut self,
 7339        _: &DuplicateLineDown,
 7340        window: &mut Window,
 7341        cx: &mut Context<Self>,
 7342    ) {
 7343        self.duplicate(false, true, window, cx);
 7344    }
 7345
 7346    pub fn duplicate_selection(
 7347        &mut self,
 7348        _: &DuplicateSelection,
 7349        window: &mut Window,
 7350        cx: &mut Context<Self>,
 7351    ) {
 7352        self.duplicate(false, false, window, cx);
 7353    }
 7354
 7355    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7356        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7357        let buffer = self.buffer.read(cx).snapshot(cx);
 7358
 7359        let mut edits = Vec::new();
 7360        let mut unfold_ranges = Vec::new();
 7361        let mut refold_creases = Vec::new();
 7362
 7363        let selections = self.selections.all::<Point>(cx);
 7364        let mut selections = selections.iter().peekable();
 7365        let mut contiguous_row_selections = Vec::new();
 7366        let mut new_selections = Vec::new();
 7367
 7368        while let Some(selection) = selections.next() {
 7369            // Find all the selections that span a contiguous row range
 7370            let (start_row, end_row) = consume_contiguous_rows(
 7371                &mut contiguous_row_selections,
 7372                selection,
 7373                &display_map,
 7374                &mut selections,
 7375            );
 7376
 7377            // Move the text spanned by the row range to be before the line preceding the row range
 7378            if start_row.0 > 0 {
 7379                let range_to_move = Point::new(
 7380                    start_row.previous_row().0,
 7381                    buffer.line_len(start_row.previous_row()),
 7382                )
 7383                    ..Point::new(
 7384                        end_row.previous_row().0,
 7385                        buffer.line_len(end_row.previous_row()),
 7386                    );
 7387                let insertion_point = display_map
 7388                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7389                    .0;
 7390
 7391                // Don't move lines across excerpts
 7392                if buffer
 7393                    .excerpt_containing(insertion_point..range_to_move.end)
 7394                    .is_some()
 7395                {
 7396                    let text = buffer
 7397                        .text_for_range(range_to_move.clone())
 7398                        .flat_map(|s| s.chars())
 7399                        .skip(1)
 7400                        .chain(['\n'])
 7401                        .collect::<String>();
 7402
 7403                    edits.push((
 7404                        buffer.anchor_after(range_to_move.start)
 7405                            ..buffer.anchor_before(range_to_move.end),
 7406                        String::new(),
 7407                    ));
 7408                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7409                    edits.push((insertion_anchor..insertion_anchor, text));
 7410
 7411                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7412
 7413                    // Move selections up
 7414                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7415                        |mut selection| {
 7416                            selection.start.row -= row_delta;
 7417                            selection.end.row -= row_delta;
 7418                            selection
 7419                        },
 7420                    ));
 7421
 7422                    // Move folds up
 7423                    unfold_ranges.push(range_to_move.clone());
 7424                    for fold in display_map.folds_in_range(
 7425                        buffer.anchor_before(range_to_move.start)
 7426                            ..buffer.anchor_after(range_to_move.end),
 7427                    ) {
 7428                        let mut start = fold.range.start.to_point(&buffer);
 7429                        let mut end = fold.range.end.to_point(&buffer);
 7430                        start.row -= row_delta;
 7431                        end.row -= row_delta;
 7432                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7433                    }
 7434                }
 7435            }
 7436
 7437            // If we didn't move line(s), preserve the existing selections
 7438            new_selections.append(&mut contiguous_row_selections);
 7439        }
 7440
 7441        self.transact(window, cx, |this, window, cx| {
 7442            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7443            this.buffer.update(cx, |buffer, cx| {
 7444                for (range, text) in edits {
 7445                    buffer.edit([(range, text)], None, cx);
 7446                }
 7447            });
 7448            this.fold_creases(refold_creases, true, window, cx);
 7449            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7450                s.select(new_selections);
 7451            })
 7452        });
 7453    }
 7454
 7455    pub fn move_line_down(
 7456        &mut self,
 7457        _: &MoveLineDown,
 7458        window: &mut Window,
 7459        cx: &mut Context<Self>,
 7460    ) {
 7461        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7462        let buffer = self.buffer.read(cx).snapshot(cx);
 7463
 7464        let mut edits = Vec::new();
 7465        let mut unfold_ranges = Vec::new();
 7466        let mut refold_creases = Vec::new();
 7467
 7468        let selections = self.selections.all::<Point>(cx);
 7469        let mut selections = selections.iter().peekable();
 7470        let mut contiguous_row_selections = Vec::new();
 7471        let mut new_selections = Vec::new();
 7472
 7473        while let Some(selection) = selections.next() {
 7474            // Find all the selections that span a contiguous row range
 7475            let (start_row, end_row) = consume_contiguous_rows(
 7476                &mut contiguous_row_selections,
 7477                selection,
 7478                &display_map,
 7479                &mut selections,
 7480            );
 7481
 7482            // Move the text spanned by the row range to be after the last line of the row range
 7483            if end_row.0 <= buffer.max_point().row {
 7484                let range_to_move =
 7485                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7486                let insertion_point = display_map
 7487                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7488                    .0;
 7489
 7490                // Don't move lines across excerpt boundaries
 7491                if buffer
 7492                    .excerpt_containing(range_to_move.start..insertion_point)
 7493                    .is_some()
 7494                {
 7495                    let mut text = String::from("\n");
 7496                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7497                    text.pop(); // Drop trailing newline
 7498                    edits.push((
 7499                        buffer.anchor_after(range_to_move.start)
 7500                            ..buffer.anchor_before(range_to_move.end),
 7501                        String::new(),
 7502                    ));
 7503                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7504                    edits.push((insertion_anchor..insertion_anchor, text));
 7505
 7506                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7507
 7508                    // Move selections down
 7509                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7510                        |mut selection| {
 7511                            selection.start.row += row_delta;
 7512                            selection.end.row += row_delta;
 7513                            selection
 7514                        },
 7515                    ));
 7516
 7517                    // Move folds down
 7518                    unfold_ranges.push(range_to_move.clone());
 7519                    for fold in display_map.folds_in_range(
 7520                        buffer.anchor_before(range_to_move.start)
 7521                            ..buffer.anchor_after(range_to_move.end),
 7522                    ) {
 7523                        let mut start = fold.range.start.to_point(&buffer);
 7524                        let mut end = fold.range.end.to_point(&buffer);
 7525                        start.row += row_delta;
 7526                        end.row += row_delta;
 7527                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7528                    }
 7529                }
 7530            }
 7531
 7532            // If we didn't move line(s), preserve the existing selections
 7533            new_selections.append(&mut contiguous_row_selections);
 7534        }
 7535
 7536        self.transact(window, cx, |this, window, cx| {
 7537            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7538            this.buffer.update(cx, |buffer, cx| {
 7539                for (range, text) in edits {
 7540                    buffer.edit([(range, text)], None, cx);
 7541                }
 7542            });
 7543            this.fold_creases(refold_creases, true, window, cx);
 7544            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7545                s.select(new_selections)
 7546            });
 7547        });
 7548    }
 7549
 7550    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7551        let text_layout_details = &self.text_layout_details(window);
 7552        self.transact(window, cx, |this, window, cx| {
 7553            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7554                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7555                let line_mode = s.line_mode;
 7556                s.move_with(|display_map, selection| {
 7557                    if !selection.is_empty() || line_mode {
 7558                        return;
 7559                    }
 7560
 7561                    let mut head = selection.head();
 7562                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7563                    if head.column() == display_map.line_len(head.row()) {
 7564                        transpose_offset = display_map
 7565                            .buffer_snapshot
 7566                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7567                    }
 7568
 7569                    if transpose_offset == 0 {
 7570                        return;
 7571                    }
 7572
 7573                    *head.column_mut() += 1;
 7574                    head = display_map.clip_point(head, Bias::Right);
 7575                    let goal = SelectionGoal::HorizontalPosition(
 7576                        display_map
 7577                            .x_for_display_point(head, text_layout_details)
 7578                            .into(),
 7579                    );
 7580                    selection.collapse_to(head, goal);
 7581
 7582                    let transpose_start = display_map
 7583                        .buffer_snapshot
 7584                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7585                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7586                        let transpose_end = display_map
 7587                            .buffer_snapshot
 7588                            .clip_offset(transpose_offset + 1, Bias::Right);
 7589                        if let Some(ch) =
 7590                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7591                        {
 7592                            edits.push((transpose_start..transpose_offset, String::new()));
 7593                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7594                        }
 7595                    }
 7596                });
 7597                edits
 7598            });
 7599            this.buffer
 7600                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7601            let selections = this.selections.all::<usize>(cx);
 7602            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7603                s.select(selections);
 7604            });
 7605        });
 7606    }
 7607
 7608    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7609        self.rewrap_impl(IsVimMode::No, cx)
 7610    }
 7611
 7612    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7613        let buffer = self.buffer.read(cx).snapshot(cx);
 7614        let selections = self.selections.all::<Point>(cx);
 7615        let mut selections = selections.iter().peekable();
 7616
 7617        let mut edits = Vec::new();
 7618        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7619
 7620        while let Some(selection) = selections.next() {
 7621            let mut start_row = selection.start.row;
 7622            let mut end_row = selection.end.row;
 7623
 7624            // Skip selections that overlap with a range that has already been rewrapped.
 7625            let selection_range = start_row..end_row;
 7626            if rewrapped_row_ranges
 7627                .iter()
 7628                .any(|range| range.overlaps(&selection_range))
 7629            {
 7630                continue;
 7631            }
 7632
 7633            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7634
 7635            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7636                match language_scope.language_name().as_ref() {
 7637                    "Markdown" | "Plain Text" => {
 7638                        should_rewrap = true;
 7639                    }
 7640                    _ => {}
 7641                }
 7642            }
 7643
 7644            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7645
 7646            // Since not all lines in the selection may be at the same indent
 7647            // level, choose the indent size that is the most common between all
 7648            // of the lines.
 7649            //
 7650            // If there is a tie, we use the deepest indent.
 7651            let (indent_size, indent_end) = {
 7652                let mut indent_size_occurrences = HashMap::default();
 7653                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7654
 7655                for row in start_row..=end_row {
 7656                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7657                    rows_by_indent_size.entry(indent).or_default().push(row);
 7658                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7659                }
 7660
 7661                let indent_size = indent_size_occurrences
 7662                    .into_iter()
 7663                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7664                    .map(|(indent, _)| indent)
 7665                    .unwrap_or_default();
 7666                let row = rows_by_indent_size[&indent_size][0];
 7667                let indent_end = Point::new(row, indent_size.len);
 7668
 7669                (indent_size, indent_end)
 7670            };
 7671
 7672            let mut line_prefix = indent_size.chars().collect::<String>();
 7673
 7674            if let Some(comment_prefix) =
 7675                buffer
 7676                    .language_scope_at(selection.head())
 7677                    .and_then(|language| {
 7678                        language
 7679                            .line_comment_prefixes()
 7680                            .iter()
 7681                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7682                            .cloned()
 7683                    })
 7684            {
 7685                line_prefix.push_str(&comment_prefix);
 7686                should_rewrap = true;
 7687            }
 7688
 7689            if !should_rewrap {
 7690                continue;
 7691            }
 7692
 7693            if selection.is_empty() {
 7694                'expand_upwards: while start_row > 0 {
 7695                    let prev_row = start_row - 1;
 7696                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7697                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7698                    {
 7699                        start_row = prev_row;
 7700                    } else {
 7701                        break 'expand_upwards;
 7702                    }
 7703                }
 7704
 7705                'expand_downwards: while end_row < buffer.max_point().row {
 7706                    let next_row = end_row + 1;
 7707                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7708                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7709                    {
 7710                        end_row = next_row;
 7711                    } else {
 7712                        break 'expand_downwards;
 7713                    }
 7714                }
 7715            }
 7716
 7717            let start = Point::new(start_row, 0);
 7718            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7719            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7720            let Some(lines_without_prefixes) = selection_text
 7721                .lines()
 7722                .map(|line| {
 7723                    line.strip_prefix(&line_prefix)
 7724                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7725                        .ok_or_else(|| {
 7726                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7727                        })
 7728                })
 7729                .collect::<Result<Vec<_>, _>>()
 7730                .log_err()
 7731            else {
 7732                continue;
 7733            };
 7734
 7735            let wrap_column = buffer
 7736                .settings_at(Point::new(start_row, 0), cx)
 7737                .preferred_line_length as usize;
 7738            let wrapped_text = wrap_with_prefix(
 7739                line_prefix,
 7740                lines_without_prefixes.join(" "),
 7741                wrap_column,
 7742                tab_size,
 7743            );
 7744
 7745            // TODO: should always use char-based diff while still supporting cursor behavior that
 7746            // matches vim.
 7747            let diff = match is_vim_mode {
 7748                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7749                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7750            };
 7751            let mut offset = start.to_offset(&buffer);
 7752            let mut moved_since_edit = true;
 7753
 7754            for change in diff.iter_all_changes() {
 7755                let value = change.value();
 7756                match change.tag() {
 7757                    ChangeTag::Equal => {
 7758                        offset += value.len();
 7759                        moved_since_edit = true;
 7760                    }
 7761                    ChangeTag::Delete => {
 7762                        let start = buffer.anchor_after(offset);
 7763                        let end = buffer.anchor_before(offset + value.len());
 7764
 7765                        if moved_since_edit {
 7766                            edits.push((start..end, String::new()));
 7767                        } else {
 7768                            edits.last_mut().unwrap().0.end = end;
 7769                        }
 7770
 7771                        offset += value.len();
 7772                        moved_since_edit = false;
 7773                    }
 7774                    ChangeTag::Insert => {
 7775                        if moved_since_edit {
 7776                            let anchor = buffer.anchor_after(offset);
 7777                            edits.push((anchor..anchor, value.to_string()));
 7778                        } else {
 7779                            edits.last_mut().unwrap().1.push_str(value);
 7780                        }
 7781
 7782                        moved_since_edit = false;
 7783                    }
 7784                }
 7785            }
 7786
 7787            rewrapped_row_ranges.push(start_row..=end_row);
 7788        }
 7789
 7790        self.buffer
 7791            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7792    }
 7793
 7794    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7795        let mut text = String::new();
 7796        let buffer = self.buffer.read(cx).snapshot(cx);
 7797        let mut selections = self.selections.all::<Point>(cx);
 7798        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7799        {
 7800            let max_point = buffer.max_point();
 7801            let mut is_first = true;
 7802            for selection in &mut selections {
 7803                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7804                if is_entire_line {
 7805                    selection.start = Point::new(selection.start.row, 0);
 7806                    if !selection.is_empty() && selection.end.column == 0 {
 7807                        selection.end = cmp::min(max_point, selection.end);
 7808                    } else {
 7809                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7810                    }
 7811                    selection.goal = SelectionGoal::None;
 7812                }
 7813                if is_first {
 7814                    is_first = false;
 7815                } else {
 7816                    text += "\n";
 7817                }
 7818                let mut len = 0;
 7819                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7820                    text.push_str(chunk);
 7821                    len += chunk.len();
 7822                }
 7823                clipboard_selections.push(ClipboardSelection {
 7824                    len,
 7825                    is_entire_line,
 7826                    first_line_indent: buffer
 7827                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7828                        .len,
 7829                });
 7830            }
 7831        }
 7832
 7833        self.transact(window, cx, |this, window, cx| {
 7834            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7835                s.select(selections);
 7836            });
 7837            this.insert("", window, cx);
 7838        });
 7839        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7840    }
 7841
 7842    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7843        let item = self.cut_common(window, cx);
 7844        cx.write_to_clipboard(item);
 7845    }
 7846
 7847    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7848        self.change_selections(None, window, cx, |s| {
 7849            s.move_with(|snapshot, sel| {
 7850                if sel.is_empty() {
 7851                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7852                }
 7853            });
 7854        });
 7855        let item = self.cut_common(window, cx);
 7856        cx.set_global(KillRing(item))
 7857    }
 7858
 7859    pub fn kill_ring_yank(
 7860        &mut self,
 7861        _: &KillRingYank,
 7862        window: &mut Window,
 7863        cx: &mut Context<Self>,
 7864    ) {
 7865        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7866            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7867                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7868            } else {
 7869                return;
 7870            }
 7871        } else {
 7872            return;
 7873        };
 7874        self.do_paste(&text, metadata, false, window, cx);
 7875    }
 7876
 7877    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7878        let selections = self.selections.all::<Point>(cx);
 7879        let buffer = self.buffer.read(cx).read(cx);
 7880        let mut text = String::new();
 7881
 7882        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7883        {
 7884            let max_point = buffer.max_point();
 7885            let mut is_first = true;
 7886            for selection in selections.iter() {
 7887                let mut start = selection.start;
 7888                let mut end = selection.end;
 7889                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7890                if is_entire_line {
 7891                    start = Point::new(start.row, 0);
 7892                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7893                }
 7894                if is_first {
 7895                    is_first = false;
 7896                } else {
 7897                    text += "\n";
 7898                }
 7899                let mut len = 0;
 7900                for chunk in buffer.text_for_range(start..end) {
 7901                    text.push_str(chunk);
 7902                    len += chunk.len();
 7903                }
 7904                clipboard_selections.push(ClipboardSelection {
 7905                    len,
 7906                    is_entire_line,
 7907                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7908                });
 7909            }
 7910        }
 7911
 7912        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7913            text,
 7914            clipboard_selections,
 7915        ));
 7916    }
 7917
 7918    pub fn do_paste(
 7919        &mut self,
 7920        text: &String,
 7921        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7922        handle_entire_lines: bool,
 7923        window: &mut Window,
 7924        cx: &mut Context<Self>,
 7925    ) {
 7926        if self.read_only(cx) {
 7927            return;
 7928        }
 7929
 7930        let clipboard_text = Cow::Borrowed(text);
 7931
 7932        self.transact(window, cx, |this, window, cx| {
 7933            if let Some(mut clipboard_selections) = clipboard_selections {
 7934                let old_selections = this.selections.all::<usize>(cx);
 7935                let all_selections_were_entire_line =
 7936                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7937                let first_selection_indent_column =
 7938                    clipboard_selections.first().map(|s| s.first_line_indent);
 7939                if clipboard_selections.len() != old_selections.len() {
 7940                    clipboard_selections.drain(..);
 7941                }
 7942                let cursor_offset = this.selections.last::<usize>(cx).head();
 7943                let mut auto_indent_on_paste = true;
 7944
 7945                this.buffer.update(cx, |buffer, cx| {
 7946                    let snapshot = buffer.read(cx);
 7947                    auto_indent_on_paste =
 7948                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7949
 7950                    let mut start_offset = 0;
 7951                    let mut edits = Vec::new();
 7952                    let mut original_indent_columns = Vec::new();
 7953                    for (ix, selection) in old_selections.iter().enumerate() {
 7954                        let to_insert;
 7955                        let entire_line;
 7956                        let original_indent_column;
 7957                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7958                            let end_offset = start_offset + clipboard_selection.len;
 7959                            to_insert = &clipboard_text[start_offset..end_offset];
 7960                            entire_line = clipboard_selection.is_entire_line;
 7961                            start_offset = end_offset + 1;
 7962                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7963                        } else {
 7964                            to_insert = clipboard_text.as_str();
 7965                            entire_line = all_selections_were_entire_line;
 7966                            original_indent_column = first_selection_indent_column
 7967                        }
 7968
 7969                        // If the corresponding selection was empty when this slice of the
 7970                        // clipboard text was written, then the entire line containing the
 7971                        // selection was copied. If this selection is also currently empty,
 7972                        // then paste the line before the current line of the buffer.
 7973                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7974                            let column = selection.start.to_point(&snapshot).column as usize;
 7975                            let line_start = selection.start - column;
 7976                            line_start..line_start
 7977                        } else {
 7978                            selection.range()
 7979                        };
 7980
 7981                        edits.push((range, to_insert));
 7982                        original_indent_columns.extend(original_indent_column);
 7983                    }
 7984                    drop(snapshot);
 7985
 7986                    buffer.edit(
 7987                        edits,
 7988                        if auto_indent_on_paste {
 7989                            Some(AutoindentMode::Block {
 7990                                original_indent_columns,
 7991                            })
 7992                        } else {
 7993                            None
 7994                        },
 7995                        cx,
 7996                    );
 7997                });
 7998
 7999                let selections = this.selections.all::<usize>(cx);
 8000                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8001                    s.select(selections)
 8002                });
 8003            } else {
 8004                this.insert(&clipboard_text, window, cx);
 8005            }
 8006        });
 8007    }
 8008
 8009    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8010        if let Some(item) = cx.read_from_clipboard() {
 8011            let entries = item.entries();
 8012
 8013            match entries.first() {
 8014                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8015                // of all the pasted entries.
 8016                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8017                    .do_paste(
 8018                        clipboard_string.text(),
 8019                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8020                        true,
 8021                        window,
 8022                        cx,
 8023                    ),
 8024                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8025            }
 8026        }
 8027    }
 8028
 8029    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8030        if self.read_only(cx) {
 8031            return;
 8032        }
 8033
 8034        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8035            if let Some((selections, _)) =
 8036                self.selection_history.transaction(transaction_id).cloned()
 8037            {
 8038                self.change_selections(None, window, cx, |s| {
 8039                    s.select_anchors(selections.to_vec());
 8040                });
 8041            }
 8042            self.request_autoscroll(Autoscroll::fit(), cx);
 8043            self.unmark_text(window, cx);
 8044            self.refresh_inline_completion(true, false, window, cx);
 8045            cx.emit(EditorEvent::Edited { transaction_id });
 8046            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8047        }
 8048    }
 8049
 8050    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8051        if self.read_only(cx) {
 8052            return;
 8053        }
 8054
 8055        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8056            if let Some((_, Some(selections))) =
 8057                self.selection_history.transaction(transaction_id).cloned()
 8058            {
 8059                self.change_selections(None, window, cx, |s| {
 8060                    s.select_anchors(selections.to_vec());
 8061                });
 8062            }
 8063            self.request_autoscroll(Autoscroll::fit(), cx);
 8064            self.unmark_text(window, cx);
 8065            self.refresh_inline_completion(true, false, window, cx);
 8066            cx.emit(EditorEvent::Edited { transaction_id });
 8067        }
 8068    }
 8069
 8070    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8071        self.buffer
 8072            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8073    }
 8074
 8075    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8076        self.buffer
 8077            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8078    }
 8079
 8080    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8081        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8082            let line_mode = s.line_mode;
 8083            s.move_with(|map, selection| {
 8084                let cursor = if selection.is_empty() && !line_mode {
 8085                    movement::left(map, selection.start)
 8086                } else {
 8087                    selection.start
 8088                };
 8089                selection.collapse_to(cursor, SelectionGoal::None);
 8090            });
 8091        })
 8092    }
 8093
 8094    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8095        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8096            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8097        })
 8098    }
 8099
 8100    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8101        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8102            let line_mode = s.line_mode;
 8103            s.move_with(|map, selection| {
 8104                let cursor = if selection.is_empty() && !line_mode {
 8105                    movement::right(map, selection.end)
 8106                } else {
 8107                    selection.end
 8108                };
 8109                selection.collapse_to(cursor, SelectionGoal::None)
 8110            });
 8111        })
 8112    }
 8113
 8114    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8115        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8116            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8117        })
 8118    }
 8119
 8120    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8121        if self.take_rename(true, window, cx).is_some() {
 8122            return;
 8123        }
 8124
 8125        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8126            cx.propagate();
 8127            return;
 8128        }
 8129
 8130        let text_layout_details = &self.text_layout_details(window);
 8131        let selection_count = self.selections.count();
 8132        let first_selection = self.selections.first_anchor();
 8133
 8134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8135            let line_mode = s.line_mode;
 8136            s.move_with(|map, selection| {
 8137                if !selection.is_empty() && !line_mode {
 8138                    selection.goal = SelectionGoal::None;
 8139                }
 8140                let (cursor, goal) = movement::up(
 8141                    map,
 8142                    selection.start,
 8143                    selection.goal,
 8144                    false,
 8145                    text_layout_details,
 8146                );
 8147                selection.collapse_to(cursor, goal);
 8148            });
 8149        });
 8150
 8151        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8152        {
 8153            cx.propagate();
 8154        }
 8155    }
 8156
 8157    pub fn move_up_by_lines(
 8158        &mut self,
 8159        action: &MoveUpByLines,
 8160        window: &mut Window,
 8161        cx: &mut Context<Self>,
 8162    ) {
 8163        if self.take_rename(true, window, cx).is_some() {
 8164            return;
 8165        }
 8166
 8167        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8168            cx.propagate();
 8169            return;
 8170        }
 8171
 8172        let text_layout_details = &self.text_layout_details(window);
 8173
 8174        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8175            let line_mode = s.line_mode;
 8176            s.move_with(|map, selection| {
 8177                if !selection.is_empty() && !line_mode {
 8178                    selection.goal = SelectionGoal::None;
 8179                }
 8180                let (cursor, goal) = movement::up_by_rows(
 8181                    map,
 8182                    selection.start,
 8183                    action.lines,
 8184                    selection.goal,
 8185                    false,
 8186                    text_layout_details,
 8187                );
 8188                selection.collapse_to(cursor, goal);
 8189            });
 8190        })
 8191    }
 8192
 8193    pub fn move_down_by_lines(
 8194        &mut self,
 8195        action: &MoveDownByLines,
 8196        window: &mut Window,
 8197        cx: &mut Context<Self>,
 8198    ) {
 8199        if self.take_rename(true, window, cx).is_some() {
 8200            return;
 8201        }
 8202
 8203        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8204            cx.propagate();
 8205            return;
 8206        }
 8207
 8208        let text_layout_details = &self.text_layout_details(window);
 8209
 8210        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8211            let line_mode = s.line_mode;
 8212            s.move_with(|map, selection| {
 8213                if !selection.is_empty() && !line_mode {
 8214                    selection.goal = SelectionGoal::None;
 8215                }
 8216                let (cursor, goal) = movement::down_by_rows(
 8217                    map,
 8218                    selection.start,
 8219                    action.lines,
 8220                    selection.goal,
 8221                    false,
 8222                    text_layout_details,
 8223                );
 8224                selection.collapse_to(cursor, goal);
 8225            });
 8226        })
 8227    }
 8228
 8229    pub fn select_down_by_lines(
 8230        &mut self,
 8231        action: &SelectDownByLines,
 8232        window: &mut Window,
 8233        cx: &mut Context<Self>,
 8234    ) {
 8235        let text_layout_details = &self.text_layout_details(window);
 8236        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8237            s.move_heads_with(|map, head, goal| {
 8238                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8239            })
 8240        })
 8241    }
 8242
 8243    pub fn select_up_by_lines(
 8244        &mut self,
 8245        action: &SelectUpByLines,
 8246        window: &mut Window,
 8247        cx: &mut Context<Self>,
 8248    ) {
 8249        let text_layout_details = &self.text_layout_details(window);
 8250        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8251            s.move_heads_with(|map, head, goal| {
 8252                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8253            })
 8254        })
 8255    }
 8256
 8257    pub fn select_page_up(
 8258        &mut self,
 8259        _: &SelectPageUp,
 8260        window: &mut Window,
 8261        cx: &mut Context<Self>,
 8262    ) {
 8263        let Some(row_count) = self.visible_row_count() else {
 8264            return;
 8265        };
 8266
 8267        let text_layout_details = &self.text_layout_details(window);
 8268
 8269        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8270            s.move_heads_with(|map, head, goal| {
 8271                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8272            })
 8273        })
 8274    }
 8275
 8276    pub fn move_page_up(
 8277        &mut self,
 8278        action: &MovePageUp,
 8279        window: &mut Window,
 8280        cx: &mut Context<Self>,
 8281    ) {
 8282        if self.take_rename(true, window, cx).is_some() {
 8283            return;
 8284        }
 8285
 8286        if self
 8287            .context_menu
 8288            .borrow_mut()
 8289            .as_mut()
 8290            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8291            .unwrap_or(false)
 8292        {
 8293            return;
 8294        }
 8295
 8296        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8297            cx.propagate();
 8298            return;
 8299        }
 8300
 8301        let Some(row_count) = self.visible_row_count() else {
 8302            return;
 8303        };
 8304
 8305        let autoscroll = if action.center_cursor {
 8306            Autoscroll::center()
 8307        } else {
 8308            Autoscroll::fit()
 8309        };
 8310
 8311        let text_layout_details = &self.text_layout_details(window);
 8312
 8313        self.change_selections(Some(autoscroll), window, cx, |s| {
 8314            let line_mode = s.line_mode;
 8315            s.move_with(|map, selection| {
 8316                if !selection.is_empty() && !line_mode {
 8317                    selection.goal = SelectionGoal::None;
 8318                }
 8319                let (cursor, goal) = movement::up_by_rows(
 8320                    map,
 8321                    selection.end,
 8322                    row_count,
 8323                    selection.goal,
 8324                    false,
 8325                    text_layout_details,
 8326                );
 8327                selection.collapse_to(cursor, goal);
 8328            });
 8329        });
 8330    }
 8331
 8332    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8333        let text_layout_details = &self.text_layout_details(window);
 8334        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8335            s.move_heads_with(|map, head, goal| {
 8336                movement::up(map, head, goal, false, text_layout_details)
 8337            })
 8338        })
 8339    }
 8340
 8341    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8342        self.take_rename(true, window, cx);
 8343
 8344        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8345            cx.propagate();
 8346            return;
 8347        }
 8348
 8349        let text_layout_details = &self.text_layout_details(window);
 8350        let selection_count = self.selections.count();
 8351        let first_selection = self.selections.first_anchor();
 8352
 8353        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8354            let line_mode = s.line_mode;
 8355            s.move_with(|map, selection| {
 8356                if !selection.is_empty() && !line_mode {
 8357                    selection.goal = SelectionGoal::None;
 8358                }
 8359                let (cursor, goal) = movement::down(
 8360                    map,
 8361                    selection.end,
 8362                    selection.goal,
 8363                    false,
 8364                    text_layout_details,
 8365                );
 8366                selection.collapse_to(cursor, goal);
 8367            });
 8368        });
 8369
 8370        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8371        {
 8372            cx.propagate();
 8373        }
 8374    }
 8375
 8376    pub fn select_page_down(
 8377        &mut self,
 8378        _: &SelectPageDown,
 8379        window: &mut Window,
 8380        cx: &mut Context<Self>,
 8381    ) {
 8382        let Some(row_count) = self.visible_row_count() else {
 8383            return;
 8384        };
 8385
 8386        let text_layout_details = &self.text_layout_details(window);
 8387
 8388        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8389            s.move_heads_with(|map, head, goal| {
 8390                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8391            })
 8392        })
 8393    }
 8394
 8395    pub fn move_page_down(
 8396        &mut self,
 8397        action: &MovePageDown,
 8398        window: &mut Window,
 8399        cx: &mut Context<Self>,
 8400    ) {
 8401        if self.take_rename(true, window, cx).is_some() {
 8402            return;
 8403        }
 8404
 8405        if self
 8406            .context_menu
 8407            .borrow_mut()
 8408            .as_mut()
 8409            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8410            .unwrap_or(false)
 8411        {
 8412            return;
 8413        }
 8414
 8415        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8416            cx.propagate();
 8417            return;
 8418        }
 8419
 8420        let Some(row_count) = self.visible_row_count() else {
 8421            return;
 8422        };
 8423
 8424        let autoscroll = if action.center_cursor {
 8425            Autoscroll::center()
 8426        } else {
 8427            Autoscroll::fit()
 8428        };
 8429
 8430        let text_layout_details = &self.text_layout_details(window);
 8431        self.change_selections(Some(autoscroll), window, cx, |s| {
 8432            let line_mode = s.line_mode;
 8433            s.move_with(|map, selection| {
 8434                if !selection.is_empty() && !line_mode {
 8435                    selection.goal = SelectionGoal::None;
 8436                }
 8437                let (cursor, goal) = movement::down_by_rows(
 8438                    map,
 8439                    selection.end,
 8440                    row_count,
 8441                    selection.goal,
 8442                    false,
 8443                    text_layout_details,
 8444                );
 8445                selection.collapse_to(cursor, goal);
 8446            });
 8447        });
 8448    }
 8449
 8450    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8451        let text_layout_details = &self.text_layout_details(window);
 8452        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8453            s.move_heads_with(|map, head, goal| {
 8454                movement::down(map, head, goal, false, text_layout_details)
 8455            })
 8456        });
 8457    }
 8458
 8459    pub fn context_menu_first(
 8460        &mut self,
 8461        _: &ContextMenuFirst,
 8462        _window: &mut Window,
 8463        cx: &mut Context<Self>,
 8464    ) {
 8465        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8466            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8467        }
 8468    }
 8469
 8470    pub fn context_menu_prev(
 8471        &mut self,
 8472        _: &ContextMenuPrev,
 8473        _window: &mut Window,
 8474        cx: &mut Context<Self>,
 8475    ) {
 8476        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8477            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8478        }
 8479    }
 8480
 8481    pub fn context_menu_next(
 8482        &mut self,
 8483        _: &ContextMenuNext,
 8484        _window: &mut Window,
 8485        cx: &mut Context<Self>,
 8486    ) {
 8487        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8488            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8489        }
 8490    }
 8491
 8492    pub fn context_menu_last(
 8493        &mut self,
 8494        _: &ContextMenuLast,
 8495        _window: &mut Window,
 8496        cx: &mut Context<Self>,
 8497    ) {
 8498        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8499            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8500        }
 8501    }
 8502
 8503    pub fn move_to_previous_word_start(
 8504        &mut self,
 8505        _: &MoveToPreviousWordStart,
 8506        window: &mut Window,
 8507        cx: &mut Context<Self>,
 8508    ) {
 8509        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8510            s.move_cursors_with(|map, head, _| {
 8511                (
 8512                    movement::previous_word_start(map, head),
 8513                    SelectionGoal::None,
 8514                )
 8515            });
 8516        })
 8517    }
 8518
 8519    pub fn move_to_previous_subword_start(
 8520        &mut self,
 8521        _: &MoveToPreviousSubwordStart,
 8522        window: &mut Window,
 8523        cx: &mut Context<Self>,
 8524    ) {
 8525        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8526            s.move_cursors_with(|map, head, _| {
 8527                (
 8528                    movement::previous_subword_start(map, head),
 8529                    SelectionGoal::None,
 8530                )
 8531            });
 8532        })
 8533    }
 8534
 8535    pub fn select_to_previous_word_start(
 8536        &mut self,
 8537        _: &SelectToPreviousWordStart,
 8538        window: &mut Window,
 8539        cx: &mut Context<Self>,
 8540    ) {
 8541        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8542            s.move_heads_with(|map, head, _| {
 8543                (
 8544                    movement::previous_word_start(map, head),
 8545                    SelectionGoal::None,
 8546                )
 8547            });
 8548        })
 8549    }
 8550
 8551    pub fn select_to_previous_subword_start(
 8552        &mut self,
 8553        _: &SelectToPreviousSubwordStart,
 8554        window: &mut Window,
 8555        cx: &mut Context<Self>,
 8556    ) {
 8557        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8558            s.move_heads_with(|map, head, _| {
 8559                (
 8560                    movement::previous_subword_start(map, head),
 8561                    SelectionGoal::None,
 8562                )
 8563            });
 8564        })
 8565    }
 8566
 8567    pub fn delete_to_previous_word_start(
 8568        &mut self,
 8569        action: &DeleteToPreviousWordStart,
 8570        window: &mut Window,
 8571        cx: &mut Context<Self>,
 8572    ) {
 8573        self.transact(window, cx, |this, window, cx| {
 8574            this.select_autoclose_pair(window, cx);
 8575            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8576                let line_mode = s.line_mode;
 8577                s.move_with(|map, selection| {
 8578                    if selection.is_empty() && !line_mode {
 8579                        let cursor = if action.ignore_newlines {
 8580                            movement::previous_word_start(map, selection.head())
 8581                        } else {
 8582                            movement::previous_word_start_or_newline(map, selection.head())
 8583                        };
 8584                        selection.set_head(cursor, SelectionGoal::None);
 8585                    }
 8586                });
 8587            });
 8588            this.insert("", window, cx);
 8589        });
 8590    }
 8591
 8592    pub fn delete_to_previous_subword_start(
 8593        &mut self,
 8594        _: &DeleteToPreviousSubwordStart,
 8595        window: &mut Window,
 8596        cx: &mut Context<Self>,
 8597    ) {
 8598        self.transact(window, cx, |this, window, cx| {
 8599            this.select_autoclose_pair(window, cx);
 8600            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8601                let line_mode = s.line_mode;
 8602                s.move_with(|map, selection| {
 8603                    if selection.is_empty() && !line_mode {
 8604                        let cursor = movement::previous_subword_start(map, selection.head());
 8605                        selection.set_head(cursor, SelectionGoal::None);
 8606                    }
 8607                });
 8608            });
 8609            this.insert("", window, cx);
 8610        });
 8611    }
 8612
 8613    pub fn move_to_next_word_end(
 8614        &mut self,
 8615        _: &MoveToNextWordEnd,
 8616        window: &mut Window,
 8617        cx: &mut Context<Self>,
 8618    ) {
 8619        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8620            s.move_cursors_with(|map, head, _| {
 8621                (movement::next_word_end(map, head), SelectionGoal::None)
 8622            });
 8623        })
 8624    }
 8625
 8626    pub fn move_to_next_subword_end(
 8627        &mut self,
 8628        _: &MoveToNextSubwordEnd,
 8629        window: &mut Window,
 8630        cx: &mut Context<Self>,
 8631    ) {
 8632        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8633            s.move_cursors_with(|map, head, _| {
 8634                (movement::next_subword_end(map, head), SelectionGoal::None)
 8635            });
 8636        })
 8637    }
 8638
 8639    pub fn select_to_next_word_end(
 8640        &mut self,
 8641        _: &SelectToNextWordEnd,
 8642        window: &mut Window,
 8643        cx: &mut Context<Self>,
 8644    ) {
 8645        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8646            s.move_heads_with(|map, head, _| {
 8647                (movement::next_word_end(map, head), SelectionGoal::None)
 8648            });
 8649        })
 8650    }
 8651
 8652    pub fn select_to_next_subword_end(
 8653        &mut self,
 8654        _: &SelectToNextSubwordEnd,
 8655        window: &mut Window,
 8656        cx: &mut Context<Self>,
 8657    ) {
 8658        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8659            s.move_heads_with(|map, head, _| {
 8660                (movement::next_subword_end(map, head), SelectionGoal::None)
 8661            });
 8662        })
 8663    }
 8664
 8665    pub fn delete_to_next_word_end(
 8666        &mut self,
 8667        action: &DeleteToNextWordEnd,
 8668        window: &mut Window,
 8669        cx: &mut Context<Self>,
 8670    ) {
 8671        self.transact(window, cx, |this, window, cx| {
 8672            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8673                let line_mode = s.line_mode;
 8674                s.move_with(|map, selection| {
 8675                    if selection.is_empty() && !line_mode {
 8676                        let cursor = if action.ignore_newlines {
 8677                            movement::next_word_end(map, selection.head())
 8678                        } else {
 8679                            movement::next_word_end_or_newline(map, selection.head())
 8680                        };
 8681                        selection.set_head(cursor, SelectionGoal::None);
 8682                    }
 8683                });
 8684            });
 8685            this.insert("", window, cx);
 8686        });
 8687    }
 8688
 8689    pub fn delete_to_next_subword_end(
 8690        &mut self,
 8691        _: &DeleteToNextSubwordEnd,
 8692        window: &mut Window,
 8693        cx: &mut Context<Self>,
 8694    ) {
 8695        self.transact(window, cx, |this, window, cx| {
 8696            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8697                s.move_with(|map, selection| {
 8698                    if selection.is_empty() {
 8699                        let cursor = movement::next_subword_end(map, selection.head());
 8700                        selection.set_head(cursor, SelectionGoal::None);
 8701                    }
 8702                });
 8703            });
 8704            this.insert("", window, cx);
 8705        });
 8706    }
 8707
 8708    pub fn move_to_beginning_of_line(
 8709        &mut self,
 8710        action: &MoveToBeginningOfLine,
 8711        window: &mut Window,
 8712        cx: &mut Context<Self>,
 8713    ) {
 8714        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8715            s.move_cursors_with(|map, head, _| {
 8716                (
 8717                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8718                    SelectionGoal::None,
 8719                )
 8720            });
 8721        })
 8722    }
 8723
 8724    pub fn select_to_beginning_of_line(
 8725        &mut self,
 8726        action: &SelectToBeginningOfLine,
 8727        window: &mut Window,
 8728        cx: &mut Context<Self>,
 8729    ) {
 8730        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8731            s.move_heads_with(|map, head, _| {
 8732                (
 8733                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8734                    SelectionGoal::None,
 8735                )
 8736            });
 8737        });
 8738    }
 8739
 8740    pub fn delete_to_beginning_of_line(
 8741        &mut self,
 8742        _: &DeleteToBeginningOfLine,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) {
 8746        self.transact(window, cx, |this, window, cx| {
 8747            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8748                s.move_with(|_, selection| {
 8749                    selection.reversed = true;
 8750                });
 8751            });
 8752
 8753            this.select_to_beginning_of_line(
 8754                &SelectToBeginningOfLine {
 8755                    stop_at_soft_wraps: false,
 8756                },
 8757                window,
 8758                cx,
 8759            );
 8760            this.backspace(&Backspace, window, cx);
 8761        });
 8762    }
 8763
 8764    pub fn move_to_end_of_line(
 8765        &mut self,
 8766        action: &MoveToEndOfLine,
 8767        window: &mut Window,
 8768        cx: &mut Context<Self>,
 8769    ) {
 8770        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8771            s.move_cursors_with(|map, head, _| {
 8772                (
 8773                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8774                    SelectionGoal::None,
 8775                )
 8776            });
 8777        })
 8778    }
 8779
 8780    pub fn select_to_end_of_line(
 8781        &mut self,
 8782        action: &SelectToEndOfLine,
 8783        window: &mut Window,
 8784        cx: &mut Context<Self>,
 8785    ) {
 8786        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8787            s.move_heads_with(|map, head, _| {
 8788                (
 8789                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8790                    SelectionGoal::None,
 8791                )
 8792            });
 8793        })
 8794    }
 8795
 8796    pub fn delete_to_end_of_line(
 8797        &mut self,
 8798        _: &DeleteToEndOfLine,
 8799        window: &mut Window,
 8800        cx: &mut Context<Self>,
 8801    ) {
 8802        self.transact(window, cx, |this, window, cx| {
 8803            this.select_to_end_of_line(
 8804                &SelectToEndOfLine {
 8805                    stop_at_soft_wraps: false,
 8806                },
 8807                window,
 8808                cx,
 8809            );
 8810            this.delete(&Delete, window, cx);
 8811        });
 8812    }
 8813
 8814    pub fn cut_to_end_of_line(
 8815        &mut self,
 8816        _: &CutToEndOfLine,
 8817        window: &mut Window,
 8818        cx: &mut Context<Self>,
 8819    ) {
 8820        self.transact(window, cx, |this, window, cx| {
 8821            this.select_to_end_of_line(
 8822                &SelectToEndOfLine {
 8823                    stop_at_soft_wraps: false,
 8824                },
 8825                window,
 8826                cx,
 8827            );
 8828            this.cut(&Cut, window, cx);
 8829        });
 8830    }
 8831
 8832    pub fn move_to_start_of_paragraph(
 8833        &mut self,
 8834        _: &MoveToStartOfParagraph,
 8835        window: &mut Window,
 8836        cx: &mut Context<Self>,
 8837    ) {
 8838        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8839            cx.propagate();
 8840            return;
 8841        }
 8842
 8843        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8844            s.move_with(|map, selection| {
 8845                selection.collapse_to(
 8846                    movement::start_of_paragraph(map, selection.head(), 1),
 8847                    SelectionGoal::None,
 8848                )
 8849            });
 8850        })
 8851    }
 8852
 8853    pub fn move_to_end_of_paragraph(
 8854        &mut self,
 8855        _: &MoveToEndOfParagraph,
 8856        window: &mut Window,
 8857        cx: &mut Context<Self>,
 8858    ) {
 8859        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8860            cx.propagate();
 8861            return;
 8862        }
 8863
 8864        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8865            s.move_with(|map, selection| {
 8866                selection.collapse_to(
 8867                    movement::end_of_paragraph(map, selection.head(), 1),
 8868                    SelectionGoal::None,
 8869                )
 8870            });
 8871        })
 8872    }
 8873
 8874    pub fn select_to_start_of_paragraph(
 8875        &mut self,
 8876        _: &SelectToStartOfParagraph,
 8877        window: &mut Window,
 8878        cx: &mut Context<Self>,
 8879    ) {
 8880        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8881            cx.propagate();
 8882            return;
 8883        }
 8884
 8885        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8886            s.move_heads_with(|map, head, _| {
 8887                (
 8888                    movement::start_of_paragraph(map, head, 1),
 8889                    SelectionGoal::None,
 8890                )
 8891            });
 8892        })
 8893    }
 8894
 8895    pub fn select_to_end_of_paragraph(
 8896        &mut self,
 8897        _: &SelectToEndOfParagraph,
 8898        window: &mut Window,
 8899        cx: &mut Context<Self>,
 8900    ) {
 8901        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8902            cx.propagate();
 8903            return;
 8904        }
 8905
 8906        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8907            s.move_heads_with(|map, head, _| {
 8908                (
 8909                    movement::end_of_paragraph(map, head, 1),
 8910                    SelectionGoal::None,
 8911                )
 8912            });
 8913        })
 8914    }
 8915
 8916    pub fn move_to_beginning(
 8917        &mut self,
 8918        _: &MoveToBeginning,
 8919        window: &mut Window,
 8920        cx: &mut Context<Self>,
 8921    ) {
 8922        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8923            cx.propagate();
 8924            return;
 8925        }
 8926
 8927        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8928            s.select_ranges(vec![0..0]);
 8929        });
 8930    }
 8931
 8932    pub fn select_to_beginning(
 8933        &mut self,
 8934        _: &SelectToBeginning,
 8935        window: &mut Window,
 8936        cx: &mut Context<Self>,
 8937    ) {
 8938        let mut selection = self.selections.last::<Point>(cx);
 8939        selection.set_head(Point::zero(), SelectionGoal::None);
 8940
 8941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8942            s.select(vec![selection]);
 8943        });
 8944    }
 8945
 8946    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8947        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8948            cx.propagate();
 8949            return;
 8950        }
 8951
 8952        let cursor = self.buffer.read(cx).read(cx).len();
 8953        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8954            s.select_ranges(vec![cursor..cursor])
 8955        });
 8956    }
 8957
 8958    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8959        self.nav_history = nav_history;
 8960    }
 8961
 8962    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8963        self.nav_history.as_ref()
 8964    }
 8965
 8966    fn push_to_nav_history(
 8967        &mut self,
 8968        cursor_anchor: Anchor,
 8969        new_position: Option<Point>,
 8970        cx: &mut Context<Self>,
 8971    ) {
 8972        if let Some(nav_history) = self.nav_history.as_mut() {
 8973            let buffer = self.buffer.read(cx).read(cx);
 8974            let cursor_position = cursor_anchor.to_point(&buffer);
 8975            let scroll_state = self.scroll_manager.anchor();
 8976            let scroll_top_row = scroll_state.top_row(&buffer);
 8977            drop(buffer);
 8978
 8979            if let Some(new_position) = new_position {
 8980                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8981                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8982                    return;
 8983                }
 8984            }
 8985
 8986            nav_history.push(
 8987                Some(NavigationData {
 8988                    cursor_anchor,
 8989                    cursor_position,
 8990                    scroll_anchor: scroll_state,
 8991                    scroll_top_row,
 8992                }),
 8993                cx,
 8994            );
 8995        }
 8996    }
 8997
 8998    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8999        let buffer = self.buffer.read(cx).snapshot(cx);
 9000        let mut selection = self.selections.first::<usize>(cx);
 9001        selection.set_head(buffer.len(), SelectionGoal::None);
 9002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9003            s.select(vec![selection]);
 9004        });
 9005    }
 9006
 9007    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9008        let end = self.buffer.read(cx).read(cx).len();
 9009        self.change_selections(None, window, cx, |s| {
 9010            s.select_ranges(vec![0..end]);
 9011        });
 9012    }
 9013
 9014    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9015        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9016        let mut selections = self.selections.all::<Point>(cx);
 9017        let max_point = display_map.buffer_snapshot.max_point();
 9018        for selection in &mut selections {
 9019            let rows = selection.spanned_rows(true, &display_map);
 9020            selection.start = Point::new(rows.start.0, 0);
 9021            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9022            selection.reversed = false;
 9023        }
 9024        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9025            s.select(selections);
 9026        });
 9027    }
 9028
 9029    pub fn split_selection_into_lines(
 9030        &mut self,
 9031        _: &SplitSelectionIntoLines,
 9032        window: &mut Window,
 9033        cx: &mut Context<Self>,
 9034    ) {
 9035        let mut to_unfold = Vec::new();
 9036        let mut new_selection_ranges = Vec::new();
 9037        {
 9038            let selections = self.selections.all::<Point>(cx);
 9039            let buffer = self.buffer.read(cx).read(cx);
 9040            for selection in selections {
 9041                for row in selection.start.row..selection.end.row {
 9042                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9043                    new_selection_ranges.push(cursor..cursor);
 9044                }
 9045                new_selection_ranges.push(selection.end..selection.end);
 9046                to_unfold.push(selection.start..selection.end);
 9047            }
 9048        }
 9049        self.unfold_ranges(&to_unfold, true, true, cx);
 9050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9051            s.select_ranges(new_selection_ranges);
 9052        });
 9053    }
 9054
 9055    pub fn add_selection_above(
 9056        &mut self,
 9057        _: &AddSelectionAbove,
 9058        window: &mut Window,
 9059        cx: &mut Context<Self>,
 9060    ) {
 9061        self.add_selection(true, window, cx);
 9062    }
 9063
 9064    pub fn add_selection_below(
 9065        &mut self,
 9066        _: &AddSelectionBelow,
 9067        window: &mut Window,
 9068        cx: &mut Context<Self>,
 9069    ) {
 9070        self.add_selection(false, window, cx);
 9071    }
 9072
 9073    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9074        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9075        let mut selections = self.selections.all::<Point>(cx);
 9076        let text_layout_details = self.text_layout_details(window);
 9077        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9078            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9079            let range = oldest_selection.display_range(&display_map).sorted();
 9080
 9081            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9082            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9083            let positions = start_x.min(end_x)..start_x.max(end_x);
 9084
 9085            selections.clear();
 9086            let mut stack = Vec::new();
 9087            for row in range.start.row().0..=range.end.row().0 {
 9088                if let Some(selection) = self.selections.build_columnar_selection(
 9089                    &display_map,
 9090                    DisplayRow(row),
 9091                    &positions,
 9092                    oldest_selection.reversed,
 9093                    &text_layout_details,
 9094                ) {
 9095                    stack.push(selection.id);
 9096                    selections.push(selection);
 9097                }
 9098            }
 9099
 9100            if above {
 9101                stack.reverse();
 9102            }
 9103
 9104            AddSelectionsState { above, stack }
 9105        });
 9106
 9107        let last_added_selection = *state.stack.last().unwrap();
 9108        let mut new_selections = Vec::new();
 9109        if above == state.above {
 9110            let end_row = if above {
 9111                DisplayRow(0)
 9112            } else {
 9113                display_map.max_point().row()
 9114            };
 9115
 9116            'outer: for selection in selections {
 9117                if selection.id == last_added_selection {
 9118                    let range = selection.display_range(&display_map).sorted();
 9119                    debug_assert_eq!(range.start.row(), range.end.row());
 9120                    let mut row = range.start.row();
 9121                    let positions =
 9122                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9123                            px(start)..px(end)
 9124                        } else {
 9125                            let start_x =
 9126                                display_map.x_for_display_point(range.start, &text_layout_details);
 9127                            let end_x =
 9128                                display_map.x_for_display_point(range.end, &text_layout_details);
 9129                            start_x.min(end_x)..start_x.max(end_x)
 9130                        };
 9131
 9132                    while row != end_row {
 9133                        if above {
 9134                            row.0 -= 1;
 9135                        } else {
 9136                            row.0 += 1;
 9137                        }
 9138
 9139                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9140                            &display_map,
 9141                            row,
 9142                            &positions,
 9143                            selection.reversed,
 9144                            &text_layout_details,
 9145                        ) {
 9146                            state.stack.push(new_selection.id);
 9147                            if above {
 9148                                new_selections.push(new_selection);
 9149                                new_selections.push(selection);
 9150                            } else {
 9151                                new_selections.push(selection);
 9152                                new_selections.push(new_selection);
 9153                            }
 9154
 9155                            continue 'outer;
 9156                        }
 9157                    }
 9158                }
 9159
 9160                new_selections.push(selection);
 9161            }
 9162        } else {
 9163            new_selections = selections;
 9164            new_selections.retain(|s| s.id != last_added_selection);
 9165            state.stack.pop();
 9166        }
 9167
 9168        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9169            s.select(new_selections);
 9170        });
 9171        if state.stack.len() > 1 {
 9172            self.add_selections_state = Some(state);
 9173        }
 9174    }
 9175
 9176    pub fn select_next_match_internal(
 9177        &mut self,
 9178        display_map: &DisplaySnapshot,
 9179        replace_newest: bool,
 9180        autoscroll: Option<Autoscroll>,
 9181        window: &mut Window,
 9182        cx: &mut Context<Self>,
 9183    ) -> Result<()> {
 9184        fn select_next_match_ranges(
 9185            this: &mut Editor,
 9186            range: Range<usize>,
 9187            replace_newest: bool,
 9188            auto_scroll: Option<Autoscroll>,
 9189            window: &mut Window,
 9190            cx: &mut Context<Editor>,
 9191        ) {
 9192            this.unfold_ranges(&[range.clone()], false, true, cx);
 9193            this.change_selections(auto_scroll, window, cx, |s| {
 9194                if replace_newest {
 9195                    s.delete(s.newest_anchor().id);
 9196                }
 9197                s.insert_range(range.clone());
 9198            });
 9199        }
 9200
 9201        let buffer = &display_map.buffer_snapshot;
 9202        let mut selections = self.selections.all::<usize>(cx);
 9203        if let Some(mut select_next_state) = self.select_next_state.take() {
 9204            let query = &select_next_state.query;
 9205            if !select_next_state.done {
 9206                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9207                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9208                let mut next_selected_range = None;
 9209
 9210                let bytes_after_last_selection =
 9211                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9212                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9213                let query_matches = query
 9214                    .stream_find_iter(bytes_after_last_selection)
 9215                    .map(|result| (last_selection.end, result))
 9216                    .chain(
 9217                        query
 9218                            .stream_find_iter(bytes_before_first_selection)
 9219                            .map(|result| (0, result)),
 9220                    );
 9221
 9222                for (start_offset, query_match) in query_matches {
 9223                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9224                    let offset_range =
 9225                        start_offset + query_match.start()..start_offset + query_match.end();
 9226                    let display_range = offset_range.start.to_display_point(display_map)
 9227                        ..offset_range.end.to_display_point(display_map);
 9228
 9229                    if !select_next_state.wordwise
 9230                        || (!movement::is_inside_word(display_map, display_range.start)
 9231                            && !movement::is_inside_word(display_map, display_range.end))
 9232                    {
 9233                        // TODO: This is n^2, because we might check all the selections
 9234                        if !selections
 9235                            .iter()
 9236                            .any(|selection| selection.range().overlaps(&offset_range))
 9237                        {
 9238                            next_selected_range = Some(offset_range);
 9239                            break;
 9240                        }
 9241                    }
 9242                }
 9243
 9244                if let Some(next_selected_range) = next_selected_range {
 9245                    select_next_match_ranges(
 9246                        self,
 9247                        next_selected_range,
 9248                        replace_newest,
 9249                        autoscroll,
 9250                        window,
 9251                        cx,
 9252                    );
 9253                } else {
 9254                    select_next_state.done = true;
 9255                }
 9256            }
 9257
 9258            self.select_next_state = Some(select_next_state);
 9259        } else {
 9260            let mut only_carets = true;
 9261            let mut same_text_selected = true;
 9262            let mut selected_text = None;
 9263
 9264            let mut selections_iter = selections.iter().peekable();
 9265            while let Some(selection) = selections_iter.next() {
 9266                if selection.start != selection.end {
 9267                    only_carets = false;
 9268                }
 9269
 9270                if same_text_selected {
 9271                    if selected_text.is_none() {
 9272                        selected_text =
 9273                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9274                    }
 9275
 9276                    if let Some(next_selection) = selections_iter.peek() {
 9277                        if next_selection.range().len() == selection.range().len() {
 9278                            let next_selected_text = buffer
 9279                                .text_for_range(next_selection.range())
 9280                                .collect::<String>();
 9281                            if Some(next_selected_text) != selected_text {
 9282                                same_text_selected = false;
 9283                                selected_text = None;
 9284                            }
 9285                        } else {
 9286                            same_text_selected = false;
 9287                            selected_text = None;
 9288                        }
 9289                    }
 9290                }
 9291            }
 9292
 9293            if only_carets {
 9294                for selection in &mut selections {
 9295                    let word_range = movement::surrounding_word(
 9296                        display_map,
 9297                        selection.start.to_display_point(display_map),
 9298                    );
 9299                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9300                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9301                    selection.goal = SelectionGoal::None;
 9302                    selection.reversed = false;
 9303                    select_next_match_ranges(
 9304                        self,
 9305                        selection.start..selection.end,
 9306                        replace_newest,
 9307                        autoscroll,
 9308                        window,
 9309                        cx,
 9310                    );
 9311                }
 9312
 9313                if selections.len() == 1 {
 9314                    let selection = selections
 9315                        .last()
 9316                        .expect("ensured that there's only one selection");
 9317                    let query = buffer
 9318                        .text_for_range(selection.start..selection.end)
 9319                        .collect::<String>();
 9320                    let is_empty = query.is_empty();
 9321                    let select_state = SelectNextState {
 9322                        query: AhoCorasick::new(&[query])?,
 9323                        wordwise: true,
 9324                        done: is_empty,
 9325                    };
 9326                    self.select_next_state = Some(select_state);
 9327                } else {
 9328                    self.select_next_state = None;
 9329                }
 9330            } else if let Some(selected_text) = selected_text {
 9331                self.select_next_state = Some(SelectNextState {
 9332                    query: AhoCorasick::new(&[selected_text])?,
 9333                    wordwise: false,
 9334                    done: false,
 9335                });
 9336                self.select_next_match_internal(
 9337                    display_map,
 9338                    replace_newest,
 9339                    autoscroll,
 9340                    window,
 9341                    cx,
 9342                )?;
 9343            }
 9344        }
 9345        Ok(())
 9346    }
 9347
 9348    pub fn select_all_matches(
 9349        &mut self,
 9350        _action: &SelectAllMatches,
 9351        window: &mut Window,
 9352        cx: &mut Context<Self>,
 9353    ) -> Result<()> {
 9354        self.push_to_selection_history();
 9355        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9356
 9357        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9358        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9359            return Ok(());
 9360        };
 9361        if select_next_state.done {
 9362            return Ok(());
 9363        }
 9364
 9365        let mut new_selections = self.selections.all::<usize>(cx);
 9366
 9367        let buffer = &display_map.buffer_snapshot;
 9368        let query_matches = select_next_state
 9369            .query
 9370            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9371
 9372        for query_match in query_matches {
 9373            let query_match = query_match.unwrap(); // can only fail due to I/O
 9374            let offset_range = query_match.start()..query_match.end();
 9375            let display_range = offset_range.start.to_display_point(&display_map)
 9376                ..offset_range.end.to_display_point(&display_map);
 9377
 9378            if !select_next_state.wordwise
 9379                || (!movement::is_inside_word(&display_map, display_range.start)
 9380                    && !movement::is_inside_word(&display_map, display_range.end))
 9381            {
 9382                self.selections.change_with(cx, |selections| {
 9383                    new_selections.push(Selection {
 9384                        id: selections.new_selection_id(),
 9385                        start: offset_range.start,
 9386                        end: offset_range.end,
 9387                        reversed: false,
 9388                        goal: SelectionGoal::None,
 9389                    });
 9390                });
 9391            }
 9392        }
 9393
 9394        new_selections.sort_by_key(|selection| selection.start);
 9395        let mut ix = 0;
 9396        while ix + 1 < new_selections.len() {
 9397            let current_selection = &new_selections[ix];
 9398            let next_selection = &new_selections[ix + 1];
 9399            if current_selection.range().overlaps(&next_selection.range()) {
 9400                if current_selection.id < next_selection.id {
 9401                    new_selections.remove(ix + 1);
 9402                } else {
 9403                    new_selections.remove(ix);
 9404                }
 9405            } else {
 9406                ix += 1;
 9407            }
 9408        }
 9409
 9410        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9411
 9412        for selection in new_selections.iter_mut() {
 9413            selection.reversed = reversed;
 9414        }
 9415
 9416        select_next_state.done = true;
 9417        self.unfold_ranges(
 9418            &new_selections
 9419                .iter()
 9420                .map(|selection| selection.range())
 9421                .collect::<Vec<_>>(),
 9422            false,
 9423            false,
 9424            cx,
 9425        );
 9426        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9427            selections.select(new_selections)
 9428        });
 9429
 9430        Ok(())
 9431    }
 9432
 9433    pub fn select_next(
 9434        &mut self,
 9435        action: &SelectNext,
 9436        window: &mut Window,
 9437        cx: &mut Context<Self>,
 9438    ) -> Result<()> {
 9439        self.push_to_selection_history();
 9440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9441        self.select_next_match_internal(
 9442            &display_map,
 9443            action.replace_newest,
 9444            Some(Autoscroll::newest()),
 9445            window,
 9446            cx,
 9447        )?;
 9448        Ok(())
 9449    }
 9450
 9451    pub fn select_previous(
 9452        &mut self,
 9453        action: &SelectPrevious,
 9454        window: &mut Window,
 9455        cx: &mut Context<Self>,
 9456    ) -> Result<()> {
 9457        self.push_to_selection_history();
 9458        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9459        let buffer = &display_map.buffer_snapshot;
 9460        let mut selections = self.selections.all::<usize>(cx);
 9461        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9462            let query = &select_prev_state.query;
 9463            if !select_prev_state.done {
 9464                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9465                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9466                let mut next_selected_range = None;
 9467                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9468                let bytes_before_last_selection =
 9469                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9470                let bytes_after_first_selection =
 9471                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9472                let query_matches = query
 9473                    .stream_find_iter(bytes_before_last_selection)
 9474                    .map(|result| (last_selection.start, result))
 9475                    .chain(
 9476                        query
 9477                            .stream_find_iter(bytes_after_first_selection)
 9478                            .map(|result| (buffer.len(), result)),
 9479                    );
 9480                for (end_offset, query_match) in query_matches {
 9481                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9482                    let offset_range =
 9483                        end_offset - query_match.end()..end_offset - query_match.start();
 9484                    let display_range = offset_range.start.to_display_point(&display_map)
 9485                        ..offset_range.end.to_display_point(&display_map);
 9486
 9487                    if !select_prev_state.wordwise
 9488                        || (!movement::is_inside_word(&display_map, display_range.start)
 9489                            && !movement::is_inside_word(&display_map, display_range.end))
 9490                    {
 9491                        next_selected_range = Some(offset_range);
 9492                        break;
 9493                    }
 9494                }
 9495
 9496                if let Some(next_selected_range) = next_selected_range {
 9497                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9498                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9499                        if action.replace_newest {
 9500                            s.delete(s.newest_anchor().id);
 9501                        }
 9502                        s.insert_range(next_selected_range);
 9503                    });
 9504                } else {
 9505                    select_prev_state.done = true;
 9506                }
 9507            }
 9508
 9509            self.select_prev_state = Some(select_prev_state);
 9510        } else {
 9511            let mut only_carets = true;
 9512            let mut same_text_selected = true;
 9513            let mut selected_text = None;
 9514
 9515            let mut selections_iter = selections.iter().peekable();
 9516            while let Some(selection) = selections_iter.next() {
 9517                if selection.start != selection.end {
 9518                    only_carets = false;
 9519                }
 9520
 9521                if same_text_selected {
 9522                    if selected_text.is_none() {
 9523                        selected_text =
 9524                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9525                    }
 9526
 9527                    if let Some(next_selection) = selections_iter.peek() {
 9528                        if next_selection.range().len() == selection.range().len() {
 9529                            let next_selected_text = buffer
 9530                                .text_for_range(next_selection.range())
 9531                                .collect::<String>();
 9532                            if Some(next_selected_text) != selected_text {
 9533                                same_text_selected = false;
 9534                                selected_text = None;
 9535                            }
 9536                        } else {
 9537                            same_text_selected = false;
 9538                            selected_text = None;
 9539                        }
 9540                    }
 9541                }
 9542            }
 9543
 9544            if only_carets {
 9545                for selection in &mut selections {
 9546                    let word_range = movement::surrounding_word(
 9547                        &display_map,
 9548                        selection.start.to_display_point(&display_map),
 9549                    );
 9550                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9551                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9552                    selection.goal = SelectionGoal::None;
 9553                    selection.reversed = false;
 9554                }
 9555                if selections.len() == 1 {
 9556                    let selection = selections
 9557                        .last()
 9558                        .expect("ensured that there's only one selection");
 9559                    let query = buffer
 9560                        .text_for_range(selection.start..selection.end)
 9561                        .collect::<String>();
 9562                    let is_empty = query.is_empty();
 9563                    let select_state = SelectNextState {
 9564                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9565                        wordwise: true,
 9566                        done: is_empty,
 9567                    };
 9568                    self.select_prev_state = Some(select_state);
 9569                } else {
 9570                    self.select_prev_state = None;
 9571                }
 9572
 9573                self.unfold_ranges(
 9574                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9575                    false,
 9576                    true,
 9577                    cx,
 9578                );
 9579                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9580                    s.select(selections);
 9581                });
 9582            } else if let Some(selected_text) = selected_text {
 9583                self.select_prev_state = Some(SelectNextState {
 9584                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9585                    wordwise: false,
 9586                    done: false,
 9587                });
 9588                self.select_previous(action, window, cx)?;
 9589            }
 9590        }
 9591        Ok(())
 9592    }
 9593
 9594    pub fn toggle_comments(
 9595        &mut self,
 9596        action: &ToggleComments,
 9597        window: &mut Window,
 9598        cx: &mut Context<Self>,
 9599    ) {
 9600        if self.read_only(cx) {
 9601            return;
 9602        }
 9603        let text_layout_details = &self.text_layout_details(window);
 9604        self.transact(window, cx, |this, window, cx| {
 9605            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9606            let mut edits = Vec::new();
 9607            let mut selection_edit_ranges = Vec::new();
 9608            let mut last_toggled_row = None;
 9609            let snapshot = this.buffer.read(cx).read(cx);
 9610            let empty_str: Arc<str> = Arc::default();
 9611            let mut suffixes_inserted = Vec::new();
 9612            let ignore_indent = action.ignore_indent;
 9613
 9614            fn comment_prefix_range(
 9615                snapshot: &MultiBufferSnapshot,
 9616                row: MultiBufferRow,
 9617                comment_prefix: &str,
 9618                comment_prefix_whitespace: &str,
 9619                ignore_indent: bool,
 9620            ) -> Range<Point> {
 9621                let indent_size = if ignore_indent {
 9622                    0
 9623                } else {
 9624                    snapshot.indent_size_for_line(row).len
 9625                };
 9626
 9627                let start = Point::new(row.0, indent_size);
 9628
 9629                let mut line_bytes = snapshot
 9630                    .bytes_in_range(start..snapshot.max_point())
 9631                    .flatten()
 9632                    .copied();
 9633
 9634                // If this line currently begins with the line comment prefix, then record
 9635                // the range containing the prefix.
 9636                if line_bytes
 9637                    .by_ref()
 9638                    .take(comment_prefix.len())
 9639                    .eq(comment_prefix.bytes())
 9640                {
 9641                    // Include any whitespace that matches the comment prefix.
 9642                    let matching_whitespace_len = line_bytes
 9643                        .zip(comment_prefix_whitespace.bytes())
 9644                        .take_while(|(a, b)| a == b)
 9645                        .count() as u32;
 9646                    let end = Point::new(
 9647                        start.row,
 9648                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9649                    );
 9650                    start..end
 9651                } else {
 9652                    start..start
 9653                }
 9654            }
 9655
 9656            fn comment_suffix_range(
 9657                snapshot: &MultiBufferSnapshot,
 9658                row: MultiBufferRow,
 9659                comment_suffix: &str,
 9660                comment_suffix_has_leading_space: bool,
 9661            ) -> Range<Point> {
 9662                let end = Point::new(row.0, snapshot.line_len(row));
 9663                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9664
 9665                let mut line_end_bytes = snapshot
 9666                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9667                    .flatten()
 9668                    .copied();
 9669
 9670                let leading_space_len = if suffix_start_column > 0
 9671                    && line_end_bytes.next() == Some(b' ')
 9672                    && comment_suffix_has_leading_space
 9673                {
 9674                    1
 9675                } else {
 9676                    0
 9677                };
 9678
 9679                // If this line currently begins with the line comment prefix, then record
 9680                // the range containing the prefix.
 9681                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9682                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9683                    start..end
 9684                } else {
 9685                    end..end
 9686                }
 9687            }
 9688
 9689            // TODO: Handle selections that cross excerpts
 9690            for selection in &mut selections {
 9691                let start_column = snapshot
 9692                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9693                    .len;
 9694                let language = if let Some(language) =
 9695                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9696                {
 9697                    language
 9698                } else {
 9699                    continue;
 9700                };
 9701
 9702                selection_edit_ranges.clear();
 9703
 9704                // If multiple selections contain a given row, avoid processing that
 9705                // row more than once.
 9706                let mut start_row = MultiBufferRow(selection.start.row);
 9707                if last_toggled_row == Some(start_row) {
 9708                    start_row = start_row.next_row();
 9709                }
 9710                let end_row =
 9711                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9712                        MultiBufferRow(selection.end.row - 1)
 9713                    } else {
 9714                        MultiBufferRow(selection.end.row)
 9715                    };
 9716                last_toggled_row = Some(end_row);
 9717
 9718                if start_row > end_row {
 9719                    continue;
 9720                }
 9721
 9722                // If the language has line comments, toggle those.
 9723                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9724
 9725                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9726                if ignore_indent {
 9727                    full_comment_prefixes = full_comment_prefixes
 9728                        .into_iter()
 9729                        .map(|s| Arc::from(s.trim_end()))
 9730                        .collect();
 9731                }
 9732
 9733                if !full_comment_prefixes.is_empty() {
 9734                    let first_prefix = full_comment_prefixes
 9735                        .first()
 9736                        .expect("prefixes is non-empty");
 9737                    let prefix_trimmed_lengths = full_comment_prefixes
 9738                        .iter()
 9739                        .map(|p| p.trim_end_matches(' ').len())
 9740                        .collect::<SmallVec<[usize; 4]>>();
 9741
 9742                    let mut all_selection_lines_are_comments = true;
 9743
 9744                    for row in start_row.0..=end_row.0 {
 9745                        let row = MultiBufferRow(row);
 9746                        if start_row < end_row && snapshot.is_line_blank(row) {
 9747                            continue;
 9748                        }
 9749
 9750                        let prefix_range = full_comment_prefixes
 9751                            .iter()
 9752                            .zip(prefix_trimmed_lengths.iter().copied())
 9753                            .map(|(prefix, trimmed_prefix_len)| {
 9754                                comment_prefix_range(
 9755                                    snapshot.deref(),
 9756                                    row,
 9757                                    &prefix[..trimmed_prefix_len],
 9758                                    &prefix[trimmed_prefix_len..],
 9759                                    ignore_indent,
 9760                                )
 9761                            })
 9762                            .max_by_key(|range| range.end.column - range.start.column)
 9763                            .expect("prefixes is non-empty");
 9764
 9765                        if prefix_range.is_empty() {
 9766                            all_selection_lines_are_comments = false;
 9767                        }
 9768
 9769                        selection_edit_ranges.push(prefix_range);
 9770                    }
 9771
 9772                    if all_selection_lines_are_comments {
 9773                        edits.extend(
 9774                            selection_edit_ranges
 9775                                .iter()
 9776                                .cloned()
 9777                                .map(|range| (range, empty_str.clone())),
 9778                        );
 9779                    } else {
 9780                        let min_column = selection_edit_ranges
 9781                            .iter()
 9782                            .map(|range| range.start.column)
 9783                            .min()
 9784                            .unwrap_or(0);
 9785                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9786                            let position = Point::new(range.start.row, min_column);
 9787                            (position..position, first_prefix.clone())
 9788                        }));
 9789                    }
 9790                } else if let Some((full_comment_prefix, comment_suffix)) =
 9791                    language.block_comment_delimiters()
 9792                {
 9793                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9794                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9795                    let prefix_range = comment_prefix_range(
 9796                        snapshot.deref(),
 9797                        start_row,
 9798                        comment_prefix,
 9799                        comment_prefix_whitespace,
 9800                        ignore_indent,
 9801                    );
 9802                    let suffix_range = comment_suffix_range(
 9803                        snapshot.deref(),
 9804                        end_row,
 9805                        comment_suffix.trim_start_matches(' '),
 9806                        comment_suffix.starts_with(' '),
 9807                    );
 9808
 9809                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9810                        edits.push((
 9811                            prefix_range.start..prefix_range.start,
 9812                            full_comment_prefix.clone(),
 9813                        ));
 9814                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9815                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9816                    } else {
 9817                        edits.push((prefix_range, empty_str.clone()));
 9818                        edits.push((suffix_range, empty_str.clone()));
 9819                    }
 9820                } else {
 9821                    continue;
 9822                }
 9823            }
 9824
 9825            drop(snapshot);
 9826            this.buffer.update(cx, |buffer, cx| {
 9827                buffer.edit(edits, None, cx);
 9828            });
 9829
 9830            // Adjust selections so that they end before any comment suffixes that
 9831            // were inserted.
 9832            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9833            let mut selections = this.selections.all::<Point>(cx);
 9834            let snapshot = this.buffer.read(cx).read(cx);
 9835            for selection in &mut selections {
 9836                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9837                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9838                        Ordering::Less => {
 9839                            suffixes_inserted.next();
 9840                            continue;
 9841                        }
 9842                        Ordering::Greater => break,
 9843                        Ordering::Equal => {
 9844                            if selection.end.column == snapshot.line_len(row) {
 9845                                if selection.is_empty() {
 9846                                    selection.start.column -= suffix_len as u32;
 9847                                }
 9848                                selection.end.column -= suffix_len as u32;
 9849                            }
 9850                            break;
 9851                        }
 9852                    }
 9853                }
 9854            }
 9855
 9856            drop(snapshot);
 9857            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9858                s.select(selections)
 9859            });
 9860
 9861            let selections = this.selections.all::<Point>(cx);
 9862            let selections_on_single_row = selections.windows(2).all(|selections| {
 9863                selections[0].start.row == selections[1].start.row
 9864                    && selections[0].end.row == selections[1].end.row
 9865                    && selections[0].start.row == selections[0].end.row
 9866            });
 9867            let selections_selecting = selections
 9868                .iter()
 9869                .any(|selection| selection.start != selection.end);
 9870            let advance_downwards = action.advance_downwards
 9871                && selections_on_single_row
 9872                && !selections_selecting
 9873                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9874
 9875            if advance_downwards {
 9876                let snapshot = this.buffer.read(cx).snapshot(cx);
 9877
 9878                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9879                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9880                        let mut point = display_point.to_point(display_snapshot);
 9881                        point.row += 1;
 9882                        point = snapshot.clip_point(point, Bias::Left);
 9883                        let display_point = point.to_display_point(display_snapshot);
 9884                        let goal = SelectionGoal::HorizontalPosition(
 9885                            display_snapshot
 9886                                .x_for_display_point(display_point, text_layout_details)
 9887                                .into(),
 9888                        );
 9889                        (display_point, goal)
 9890                    })
 9891                });
 9892            }
 9893        });
 9894    }
 9895
 9896    pub fn select_enclosing_symbol(
 9897        &mut self,
 9898        _: &SelectEnclosingSymbol,
 9899        window: &mut Window,
 9900        cx: &mut Context<Self>,
 9901    ) {
 9902        let buffer = self.buffer.read(cx).snapshot(cx);
 9903        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9904
 9905        fn update_selection(
 9906            selection: &Selection<usize>,
 9907            buffer_snap: &MultiBufferSnapshot,
 9908        ) -> Option<Selection<usize>> {
 9909            let cursor = selection.head();
 9910            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9911            for symbol in symbols.iter().rev() {
 9912                let start = symbol.range.start.to_offset(buffer_snap);
 9913                let end = symbol.range.end.to_offset(buffer_snap);
 9914                let new_range = start..end;
 9915                if start < selection.start || end > selection.end {
 9916                    return Some(Selection {
 9917                        id: selection.id,
 9918                        start: new_range.start,
 9919                        end: new_range.end,
 9920                        goal: SelectionGoal::None,
 9921                        reversed: selection.reversed,
 9922                    });
 9923                }
 9924            }
 9925            None
 9926        }
 9927
 9928        let mut selected_larger_symbol = false;
 9929        let new_selections = old_selections
 9930            .iter()
 9931            .map(|selection| match update_selection(selection, &buffer) {
 9932                Some(new_selection) => {
 9933                    if new_selection.range() != selection.range() {
 9934                        selected_larger_symbol = true;
 9935                    }
 9936                    new_selection
 9937                }
 9938                None => selection.clone(),
 9939            })
 9940            .collect::<Vec<_>>();
 9941
 9942        if selected_larger_symbol {
 9943            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9944                s.select(new_selections);
 9945            });
 9946        }
 9947    }
 9948
 9949    pub fn select_larger_syntax_node(
 9950        &mut self,
 9951        _: &SelectLargerSyntaxNode,
 9952        window: &mut Window,
 9953        cx: &mut Context<Self>,
 9954    ) {
 9955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9956        let buffer = self.buffer.read(cx).snapshot(cx);
 9957        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9958
 9959        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9960        let mut selected_larger_node = false;
 9961        let new_selections = old_selections
 9962            .iter()
 9963            .map(|selection| {
 9964                let old_range = selection.start..selection.end;
 9965                let mut new_range = old_range.clone();
 9966                let mut new_node = None;
 9967                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9968                {
 9969                    new_node = Some(node);
 9970                    new_range = containing_range;
 9971                    if !display_map.intersects_fold(new_range.start)
 9972                        && !display_map.intersects_fold(new_range.end)
 9973                    {
 9974                        break;
 9975                    }
 9976                }
 9977
 9978                if let Some(node) = new_node {
 9979                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9980                    // nodes. Parent and grandparent are also logged because this operation will not
 9981                    // visit nodes that have the same range as their parent.
 9982                    log::info!("Node: {node:?}");
 9983                    let parent = node.parent();
 9984                    log::info!("Parent: {parent:?}");
 9985                    let grandparent = parent.and_then(|x| x.parent());
 9986                    log::info!("Grandparent: {grandparent:?}");
 9987                }
 9988
 9989                selected_larger_node |= new_range != old_range;
 9990                Selection {
 9991                    id: selection.id,
 9992                    start: new_range.start,
 9993                    end: new_range.end,
 9994                    goal: SelectionGoal::None,
 9995                    reversed: selection.reversed,
 9996                }
 9997            })
 9998            .collect::<Vec<_>>();
 9999
10000        if selected_larger_node {
10001            stack.push(old_selections);
10002            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10003                s.select(new_selections);
10004            });
10005        }
10006        self.select_larger_syntax_node_stack = stack;
10007    }
10008
10009    pub fn select_smaller_syntax_node(
10010        &mut self,
10011        _: &SelectSmallerSyntaxNode,
10012        window: &mut Window,
10013        cx: &mut Context<Self>,
10014    ) {
10015        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10016        if let Some(selections) = stack.pop() {
10017            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10018                s.select(selections.to_vec());
10019            });
10020        }
10021        self.select_larger_syntax_node_stack = stack;
10022    }
10023
10024    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10025        if !EditorSettings::get_global(cx).gutter.runnables {
10026            self.clear_tasks();
10027            return Task::ready(());
10028        }
10029        let project = self.project.as_ref().map(Entity::downgrade);
10030        cx.spawn_in(window, |this, mut cx| async move {
10031            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10032            let Some(project) = project.and_then(|p| p.upgrade()) else {
10033                return;
10034            };
10035            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10036                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10037            }) else {
10038                return;
10039            };
10040
10041            let hide_runnables = project
10042                .update(&mut cx, |project, cx| {
10043                    // Do not display any test indicators in non-dev server remote projects.
10044                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10045                })
10046                .unwrap_or(true);
10047            if hide_runnables {
10048                return;
10049            }
10050            let new_rows =
10051                cx.background_executor()
10052                    .spawn({
10053                        let snapshot = display_snapshot.clone();
10054                        async move {
10055                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10056                        }
10057                    })
10058                    .await;
10059
10060            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10061            this.update(&mut cx, |this, _| {
10062                this.clear_tasks();
10063                for (key, value) in rows {
10064                    this.insert_tasks(key, value);
10065                }
10066            })
10067            .ok();
10068        })
10069    }
10070    fn fetch_runnable_ranges(
10071        snapshot: &DisplaySnapshot,
10072        range: Range<Anchor>,
10073    ) -> Vec<language::RunnableRange> {
10074        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10075    }
10076
10077    fn runnable_rows(
10078        project: Entity<Project>,
10079        snapshot: DisplaySnapshot,
10080        runnable_ranges: Vec<RunnableRange>,
10081        mut cx: AsyncWindowContext,
10082    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10083        runnable_ranges
10084            .into_iter()
10085            .filter_map(|mut runnable| {
10086                let tasks = cx
10087                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10088                    .ok()?;
10089                if tasks.is_empty() {
10090                    return None;
10091                }
10092
10093                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10094
10095                let row = snapshot
10096                    .buffer_snapshot
10097                    .buffer_line_for_row(MultiBufferRow(point.row))?
10098                    .1
10099                    .start
10100                    .row;
10101
10102                let context_range =
10103                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10104                Some((
10105                    (runnable.buffer_id, row),
10106                    RunnableTasks {
10107                        templates: tasks,
10108                        offset: MultiBufferOffset(runnable.run_range.start),
10109                        context_range,
10110                        column: point.column,
10111                        extra_variables: runnable.extra_captures,
10112                    },
10113                ))
10114            })
10115            .collect()
10116    }
10117
10118    fn templates_with_tags(
10119        project: &Entity<Project>,
10120        runnable: &mut Runnable,
10121        cx: &mut App,
10122    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10123        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10124            let (worktree_id, file) = project
10125                .buffer_for_id(runnable.buffer, cx)
10126                .and_then(|buffer| buffer.read(cx).file())
10127                .map(|file| (file.worktree_id(cx), file.clone()))
10128                .unzip();
10129
10130            (
10131                project.task_store().read(cx).task_inventory().cloned(),
10132                worktree_id,
10133                file,
10134            )
10135        });
10136
10137        let tags = mem::take(&mut runnable.tags);
10138        let mut tags: Vec<_> = tags
10139            .into_iter()
10140            .flat_map(|tag| {
10141                let tag = tag.0.clone();
10142                inventory
10143                    .as_ref()
10144                    .into_iter()
10145                    .flat_map(|inventory| {
10146                        inventory.read(cx).list_tasks(
10147                            file.clone(),
10148                            Some(runnable.language.clone()),
10149                            worktree_id,
10150                            cx,
10151                        )
10152                    })
10153                    .filter(move |(_, template)| {
10154                        template.tags.iter().any(|source_tag| source_tag == &tag)
10155                    })
10156            })
10157            .sorted_by_key(|(kind, _)| kind.to_owned())
10158            .collect();
10159        if let Some((leading_tag_source, _)) = tags.first() {
10160            // Strongest source wins; if we have worktree tag binding, prefer that to
10161            // global and language bindings;
10162            // if we have a global binding, prefer that to language binding.
10163            let first_mismatch = tags
10164                .iter()
10165                .position(|(tag_source, _)| tag_source != leading_tag_source);
10166            if let Some(index) = first_mismatch {
10167                tags.truncate(index);
10168            }
10169        }
10170
10171        tags
10172    }
10173
10174    pub fn move_to_enclosing_bracket(
10175        &mut self,
10176        _: &MoveToEnclosingBracket,
10177        window: &mut Window,
10178        cx: &mut Context<Self>,
10179    ) {
10180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10181            s.move_offsets_with(|snapshot, selection| {
10182                let Some(enclosing_bracket_ranges) =
10183                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10184                else {
10185                    return;
10186                };
10187
10188                let mut best_length = usize::MAX;
10189                let mut best_inside = false;
10190                let mut best_in_bracket_range = false;
10191                let mut best_destination = None;
10192                for (open, close) in enclosing_bracket_ranges {
10193                    let close = close.to_inclusive();
10194                    let length = close.end() - open.start;
10195                    let inside = selection.start >= open.end && selection.end <= *close.start();
10196                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10197                        || close.contains(&selection.head());
10198
10199                    // If best is next to a bracket and current isn't, skip
10200                    if !in_bracket_range && best_in_bracket_range {
10201                        continue;
10202                    }
10203
10204                    // Prefer smaller lengths unless best is inside and current isn't
10205                    if length > best_length && (best_inside || !inside) {
10206                        continue;
10207                    }
10208
10209                    best_length = length;
10210                    best_inside = inside;
10211                    best_in_bracket_range = in_bracket_range;
10212                    best_destination = Some(
10213                        if close.contains(&selection.start) && close.contains(&selection.end) {
10214                            if inside {
10215                                open.end
10216                            } else {
10217                                open.start
10218                            }
10219                        } else if inside {
10220                            *close.start()
10221                        } else {
10222                            *close.end()
10223                        },
10224                    );
10225                }
10226
10227                if let Some(destination) = best_destination {
10228                    selection.collapse_to(destination, SelectionGoal::None);
10229                }
10230            })
10231        });
10232    }
10233
10234    pub fn undo_selection(
10235        &mut self,
10236        _: &UndoSelection,
10237        window: &mut Window,
10238        cx: &mut Context<Self>,
10239    ) {
10240        self.end_selection(window, cx);
10241        self.selection_history.mode = SelectionHistoryMode::Undoing;
10242        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10243            self.change_selections(None, window, cx, |s| {
10244                s.select_anchors(entry.selections.to_vec())
10245            });
10246            self.select_next_state = entry.select_next_state;
10247            self.select_prev_state = entry.select_prev_state;
10248            self.add_selections_state = entry.add_selections_state;
10249            self.request_autoscroll(Autoscroll::newest(), cx);
10250        }
10251        self.selection_history.mode = SelectionHistoryMode::Normal;
10252    }
10253
10254    pub fn redo_selection(
10255        &mut self,
10256        _: &RedoSelection,
10257        window: &mut Window,
10258        cx: &mut Context<Self>,
10259    ) {
10260        self.end_selection(window, cx);
10261        self.selection_history.mode = SelectionHistoryMode::Redoing;
10262        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10263            self.change_selections(None, window, cx, |s| {
10264                s.select_anchors(entry.selections.to_vec())
10265            });
10266            self.select_next_state = entry.select_next_state;
10267            self.select_prev_state = entry.select_prev_state;
10268            self.add_selections_state = entry.add_selections_state;
10269            self.request_autoscroll(Autoscroll::newest(), cx);
10270        }
10271        self.selection_history.mode = SelectionHistoryMode::Normal;
10272    }
10273
10274    pub fn expand_excerpts(
10275        &mut self,
10276        action: &ExpandExcerpts,
10277        _: &mut Window,
10278        cx: &mut Context<Self>,
10279    ) {
10280        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10281    }
10282
10283    pub fn expand_excerpts_down(
10284        &mut self,
10285        action: &ExpandExcerptsDown,
10286        _: &mut Window,
10287        cx: &mut Context<Self>,
10288    ) {
10289        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10290    }
10291
10292    pub fn expand_excerpts_up(
10293        &mut self,
10294        action: &ExpandExcerptsUp,
10295        _: &mut Window,
10296        cx: &mut Context<Self>,
10297    ) {
10298        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10299    }
10300
10301    pub fn expand_excerpts_for_direction(
10302        &mut self,
10303        lines: u32,
10304        direction: ExpandExcerptDirection,
10305
10306        cx: &mut Context<Self>,
10307    ) {
10308        let selections = self.selections.disjoint_anchors();
10309
10310        let lines = if lines == 0 {
10311            EditorSettings::get_global(cx).expand_excerpt_lines
10312        } else {
10313            lines
10314        };
10315
10316        self.buffer.update(cx, |buffer, cx| {
10317            let snapshot = buffer.snapshot(cx);
10318            let mut excerpt_ids = selections
10319                .iter()
10320                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10321                .collect::<Vec<_>>();
10322            excerpt_ids.sort();
10323            excerpt_ids.dedup();
10324            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10325        })
10326    }
10327
10328    pub fn expand_excerpt(
10329        &mut self,
10330        excerpt: ExcerptId,
10331        direction: ExpandExcerptDirection,
10332        cx: &mut Context<Self>,
10333    ) {
10334        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10335        self.buffer.update(cx, |buffer, cx| {
10336            buffer.expand_excerpts([excerpt], lines, direction, cx)
10337        })
10338    }
10339
10340    pub fn go_to_singleton_buffer_point(
10341        &mut self,
10342        point: Point,
10343        window: &mut Window,
10344        cx: &mut Context<Self>,
10345    ) {
10346        self.go_to_singleton_buffer_range(point..point, window, cx);
10347    }
10348
10349    pub fn go_to_singleton_buffer_range(
10350        &mut self,
10351        range: Range<Point>,
10352        window: &mut Window,
10353        cx: &mut Context<Self>,
10354    ) {
10355        let multibuffer = self.buffer().read(cx);
10356        let Some(buffer) = multibuffer.as_singleton() else {
10357            return;
10358        };
10359        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10360            return;
10361        };
10362        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10363            return;
10364        };
10365        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10366            s.select_anchor_ranges([start..end])
10367        });
10368    }
10369
10370    fn go_to_diagnostic(
10371        &mut self,
10372        _: &GoToDiagnostic,
10373        window: &mut Window,
10374        cx: &mut Context<Self>,
10375    ) {
10376        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10377    }
10378
10379    fn go_to_prev_diagnostic(
10380        &mut self,
10381        _: &GoToPrevDiagnostic,
10382        window: &mut Window,
10383        cx: &mut Context<Self>,
10384    ) {
10385        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10386    }
10387
10388    pub fn go_to_diagnostic_impl(
10389        &mut self,
10390        direction: Direction,
10391        window: &mut Window,
10392        cx: &mut Context<Self>,
10393    ) {
10394        let buffer = self.buffer.read(cx).snapshot(cx);
10395        let selection = self.selections.newest::<usize>(cx);
10396
10397        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10398        if direction == Direction::Next {
10399            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10400                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10401                    return;
10402                };
10403                self.activate_diagnostics(
10404                    buffer_id,
10405                    popover.local_diagnostic.diagnostic.group_id,
10406                    window,
10407                    cx,
10408                );
10409                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10410                    let primary_range_start = active_diagnostics.primary_range.start;
10411                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10412                        let mut new_selection = s.newest_anchor().clone();
10413                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10414                        s.select_anchors(vec![new_selection.clone()]);
10415                    });
10416                    self.refresh_inline_completion(false, true, window, cx);
10417                }
10418                return;
10419            }
10420        }
10421
10422        let active_group_id = self
10423            .active_diagnostics
10424            .as_ref()
10425            .map(|active_group| active_group.group_id);
10426        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10427            active_diagnostics
10428                .primary_range
10429                .to_offset(&buffer)
10430                .to_inclusive()
10431        });
10432        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10433            if active_primary_range.contains(&selection.head()) {
10434                *active_primary_range.start()
10435            } else {
10436                selection.head()
10437            }
10438        } else {
10439            selection.head()
10440        };
10441
10442        let snapshot = self.snapshot(window, cx);
10443        let primary_diagnostics_before = buffer
10444            .diagnostics_in_range::<usize>(0..search_start)
10445            .filter(|entry| entry.diagnostic.is_primary)
10446            .filter(|entry| entry.range.start != entry.range.end)
10447            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10448            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10449            .collect::<Vec<_>>();
10450        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10451            primary_diagnostics_before
10452                .iter()
10453                .position(|entry| entry.diagnostic.group_id == active_group_id)
10454        });
10455
10456        let primary_diagnostics_after = buffer
10457            .diagnostics_in_range::<usize>(search_start..buffer.len())
10458            .filter(|entry| entry.diagnostic.is_primary)
10459            .filter(|entry| entry.range.start != entry.range.end)
10460            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10461            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10462            .collect::<Vec<_>>();
10463        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10464            primary_diagnostics_after
10465                .iter()
10466                .enumerate()
10467                .rev()
10468                .find_map(|(i, entry)| {
10469                    if entry.diagnostic.group_id == active_group_id {
10470                        Some(i)
10471                    } else {
10472                        None
10473                    }
10474                })
10475        });
10476
10477        let next_primary_diagnostic = match direction {
10478            Direction::Prev => primary_diagnostics_before
10479                .iter()
10480                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10481                .rev()
10482                .next(),
10483            Direction::Next => primary_diagnostics_after
10484                .iter()
10485                .skip(
10486                    last_same_group_diagnostic_after
10487                        .map(|index| index + 1)
10488                        .unwrap_or(0),
10489                )
10490                .next(),
10491        };
10492
10493        // Cycle around to the start of the buffer, potentially moving back to the start of
10494        // the currently active diagnostic.
10495        let cycle_around = || match direction {
10496            Direction::Prev => primary_diagnostics_after
10497                .iter()
10498                .rev()
10499                .chain(primary_diagnostics_before.iter().rev())
10500                .next(),
10501            Direction::Next => primary_diagnostics_before
10502                .iter()
10503                .chain(primary_diagnostics_after.iter())
10504                .next(),
10505        };
10506
10507        if let Some((primary_range, group_id)) = next_primary_diagnostic
10508            .or_else(cycle_around)
10509            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10510        {
10511            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10512                return;
10513            };
10514            self.activate_diagnostics(buffer_id, group_id, window, cx);
10515            if self.active_diagnostics.is_some() {
10516                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10517                    s.select(vec![Selection {
10518                        id: selection.id,
10519                        start: primary_range.start,
10520                        end: primary_range.start,
10521                        reversed: false,
10522                        goal: SelectionGoal::None,
10523                    }]);
10524                });
10525                self.refresh_inline_completion(false, true, window, cx);
10526            }
10527        }
10528    }
10529
10530    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10531        let snapshot = self.snapshot(window, cx);
10532        let selection = self.selections.newest::<Point>(cx);
10533        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10534    }
10535
10536    fn go_to_hunk_after_position(
10537        &mut self,
10538        snapshot: &EditorSnapshot,
10539        position: Point,
10540        window: &mut Window,
10541        cx: &mut Context<Editor>,
10542    ) -> Option<MultiBufferDiffHunk> {
10543        let mut hunk = snapshot
10544            .buffer_snapshot
10545            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10546            .find(|hunk| hunk.row_range.start.0 > position.row);
10547        if hunk.is_none() {
10548            hunk = snapshot
10549                .buffer_snapshot
10550                .diff_hunks_in_range(Point::zero()..position)
10551                .find(|hunk| hunk.row_range.end.0 < position.row)
10552        }
10553        if let Some(hunk) = &hunk {
10554            let destination = Point::new(hunk.row_range.start.0, 0);
10555            self.unfold_ranges(&[destination..destination], false, false, cx);
10556            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10557                s.select_ranges(vec![destination..destination]);
10558            });
10559        }
10560
10561        hunk
10562    }
10563
10564    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10565        let snapshot = self.snapshot(window, cx);
10566        let selection = self.selections.newest::<Point>(cx);
10567        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10568    }
10569
10570    fn go_to_hunk_before_position(
10571        &mut self,
10572        snapshot: &EditorSnapshot,
10573        position: Point,
10574        window: &mut Window,
10575        cx: &mut Context<Editor>,
10576    ) -> Option<MultiBufferDiffHunk> {
10577        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10578        if hunk.is_none() {
10579            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10580        }
10581        if let Some(hunk) = &hunk {
10582            let destination = Point::new(hunk.row_range.start.0, 0);
10583            self.unfold_ranges(&[destination..destination], false, false, cx);
10584            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10585                s.select_ranges(vec![destination..destination]);
10586            });
10587        }
10588
10589        hunk
10590    }
10591
10592    pub fn go_to_definition(
10593        &mut self,
10594        _: &GoToDefinition,
10595        window: &mut Window,
10596        cx: &mut Context<Self>,
10597    ) -> Task<Result<Navigated>> {
10598        let definition =
10599            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10600        cx.spawn_in(window, |editor, mut cx| async move {
10601            if definition.await? == Navigated::Yes {
10602                return Ok(Navigated::Yes);
10603            }
10604            match editor.update_in(&mut cx, |editor, window, cx| {
10605                editor.find_all_references(&FindAllReferences, window, cx)
10606            })? {
10607                Some(references) => references.await,
10608                None => Ok(Navigated::No),
10609            }
10610        })
10611    }
10612
10613    pub fn go_to_declaration(
10614        &mut self,
10615        _: &GoToDeclaration,
10616        window: &mut Window,
10617        cx: &mut Context<Self>,
10618    ) -> Task<Result<Navigated>> {
10619        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10620    }
10621
10622    pub fn go_to_declaration_split(
10623        &mut self,
10624        _: &GoToDeclaration,
10625        window: &mut Window,
10626        cx: &mut Context<Self>,
10627    ) -> Task<Result<Navigated>> {
10628        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10629    }
10630
10631    pub fn go_to_implementation(
10632        &mut self,
10633        _: &GoToImplementation,
10634        window: &mut Window,
10635        cx: &mut Context<Self>,
10636    ) -> Task<Result<Navigated>> {
10637        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10638    }
10639
10640    pub fn go_to_implementation_split(
10641        &mut self,
10642        _: &GoToImplementationSplit,
10643        window: &mut Window,
10644        cx: &mut Context<Self>,
10645    ) -> Task<Result<Navigated>> {
10646        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10647    }
10648
10649    pub fn go_to_type_definition(
10650        &mut self,
10651        _: &GoToTypeDefinition,
10652        window: &mut Window,
10653        cx: &mut Context<Self>,
10654    ) -> Task<Result<Navigated>> {
10655        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10656    }
10657
10658    pub fn go_to_definition_split(
10659        &mut self,
10660        _: &GoToDefinitionSplit,
10661        window: &mut Window,
10662        cx: &mut Context<Self>,
10663    ) -> Task<Result<Navigated>> {
10664        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10665    }
10666
10667    pub fn go_to_type_definition_split(
10668        &mut self,
10669        _: &GoToTypeDefinitionSplit,
10670        window: &mut Window,
10671        cx: &mut Context<Self>,
10672    ) -> Task<Result<Navigated>> {
10673        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10674    }
10675
10676    fn go_to_definition_of_kind(
10677        &mut self,
10678        kind: GotoDefinitionKind,
10679        split: bool,
10680        window: &mut Window,
10681        cx: &mut Context<Self>,
10682    ) -> Task<Result<Navigated>> {
10683        let Some(provider) = self.semantics_provider.clone() else {
10684            return Task::ready(Ok(Navigated::No));
10685        };
10686        let head = self.selections.newest::<usize>(cx).head();
10687        let buffer = self.buffer.read(cx);
10688        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10689            text_anchor
10690        } else {
10691            return Task::ready(Ok(Navigated::No));
10692        };
10693
10694        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10695            return Task::ready(Ok(Navigated::No));
10696        };
10697
10698        cx.spawn_in(window, |editor, mut cx| async move {
10699            let definitions = definitions.await?;
10700            let navigated = editor
10701                .update_in(&mut cx, |editor, window, cx| {
10702                    editor.navigate_to_hover_links(
10703                        Some(kind),
10704                        definitions
10705                            .into_iter()
10706                            .filter(|location| {
10707                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10708                            })
10709                            .map(HoverLink::Text)
10710                            .collect::<Vec<_>>(),
10711                        split,
10712                        window,
10713                        cx,
10714                    )
10715                })?
10716                .await?;
10717            anyhow::Ok(navigated)
10718        })
10719    }
10720
10721    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10722        let selection = self.selections.newest_anchor();
10723        let head = selection.head();
10724        let tail = selection.tail();
10725
10726        let Some((buffer, start_position)) =
10727            self.buffer.read(cx).text_anchor_for_position(head, cx)
10728        else {
10729            return;
10730        };
10731
10732        let end_position = if head != tail {
10733            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10734                return;
10735            };
10736            Some(pos)
10737        } else {
10738            None
10739        };
10740
10741        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10742            let url = if let Some(end_pos) = end_position {
10743                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10744            } else {
10745                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10746            };
10747
10748            if let Some(url) = url {
10749                editor.update(&mut cx, |_, cx| {
10750                    cx.open_url(&url);
10751                })
10752            } else {
10753                Ok(())
10754            }
10755        });
10756
10757        url_finder.detach();
10758    }
10759
10760    pub fn open_selected_filename(
10761        &mut self,
10762        _: &OpenSelectedFilename,
10763        window: &mut Window,
10764        cx: &mut Context<Self>,
10765    ) {
10766        let Some(workspace) = self.workspace() else {
10767            return;
10768        };
10769
10770        let position = self.selections.newest_anchor().head();
10771
10772        let Some((buffer, buffer_position)) =
10773            self.buffer.read(cx).text_anchor_for_position(position, cx)
10774        else {
10775            return;
10776        };
10777
10778        let project = self.project.clone();
10779
10780        cx.spawn_in(window, |_, mut cx| async move {
10781            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10782
10783            if let Some((_, path)) = result {
10784                workspace
10785                    .update_in(&mut cx, |workspace, window, cx| {
10786                        workspace.open_resolved_path(path, window, cx)
10787                    })?
10788                    .await?;
10789            }
10790            anyhow::Ok(())
10791        })
10792        .detach();
10793    }
10794
10795    pub(crate) fn navigate_to_hover_links(
10796        &mut self,
10797        kind: Option<GotoDefinitionKind>,
10798        mut definitions: Vec<HoverLink>,
10799        split: bool,
10800        window: &mut Window,
10801        cx: &mut Context<Editor>,
10802    ) -> Task<Result<Navigated>> {
10803        // If there is one definition, just open it directly
10804        if definitions.len() == 1 {
10805            let definition = definitions.pop().unwrap();
10806
10807            enum TargetTaskResult {
10808                Location(Option<Location>),
10809                AlreadyNavigated,
10810            }
10811
10812            let target_task = match definition {
10813                HoverLink::Text(link) => {
10814                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10815                }
10816                HoverLink::InlayHint(lsp_location, server_id) => {
10817                    let computation =
10818                        self.compute_target_location(lsp_location, server_id, window, cx);
10819                    cx.background_executor().spawn(async move {
10820                        let location = computation.await?;
10821                        Ok(TargetTaskResult::Location(location))
10822                    })
10823                }
10824                HoverLink::Url(url) => {
10825                    cx.open_url(&url);
10826                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10827                }
10828                HoverLink::File(path) => {
10829                    if let Some(workspace) = self.workspace() {
10830                        cx.spawn_in(window, |_, mut cx| async move {
10831                            workspace
10832                                .update_in(&mut cx, |workspace, window, cx| {
10833                                    workspace.open_resolved_path(path, window, cx)
10834                                })?
10835                                .await
10836                                .map(|_| TargetTaskResult::AlreadyNavigated)
10837                        })
10838                    } else {
10839                        Task::ready(Ok(TargetTaskResult::Location(None)))
10840                    }
10841                }
10842            };
10843            cx.spawn_in(window, |editor, mut cx| async move {
10844                let target = match target_task.await.context("target resolution task")? {
10845                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10846                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10847                    TargetTaskResult::Location(Some(target)) => target,
10848                };
10849
10850                editor.update_in(&mut cx, |editor, window, cx| {
10851                    let Some(workspace) = editor.workspace() else {
10852                        return Navigated::No;
10853                    };
10854                    let pane = workspace.read(cx).active_pane().clone();
10855
10856                    let range = target.range.to_point(target.buffer.read(cx));
10857                    let range = editor.range_for_match(&range);
10858                    let range = collapse_multiline_range(range);
10859
10860                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10861                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10862                    } else {
10863                        window.defer(cx, move |window, cx| {
10864                            let target_editor: Entity<Self> =
10865                                workspace.update(cx, |workspace, cx| {
10866                                    let pane = if split {
10867                                        workspace.adjacent_pane(window, cx)
10868                                    } else {
10869                                        workspace.active_pane().clone()
10870                                    };
10871
10872                                    workspace.open_project_item(
10873                                        pane,
10874                                        target.buffer.clone(),
10875                                        true,
10876                                        true,
10877                                        window,
10878                                        cx,
10879                                    )
10880                                });
10881                            target_editor.update(cx, |target_editor, cx| {
10882                                // When selecting a definition in a different buffer, disable the nav history
10883                                // to avoid creating a history entry at the previous cursor location.
10884                                pane.update(cx, |pane, _| pane.disable_history());
10885                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10886                                pane.update(cx, |pane, _| pane.enable_history());
10887                            });
10888                        });
10889                    }
10890                    Navigated::Yes
10891                })
10892            })
10893        } else if !definitions.is_empty() {
10894            cx.spawn_in(window, |editor, mut cx| async move {
10895                let (title, location_tasks, workspace) = editor
10896                    .update_in(&mut cx, |editor, window, cx| {
10897                        let tab_kind = match kind {
10898                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10899                            _ => "Definitions",
10900                        };
10901                        let title = definitions
10902                            .iter()
10903                            .find_map(|definition| match definition {
10904                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10905                                    let buffer = origin.buffer.read(cx);
10906                                    format!(
10907                                        "{} for {}",
10908                                        tab_kind,
10909                                        buffer
10910                                            .text_for_range(origin.range.clone())
10911                                            .collect::<String>()
10912                                    )
10913                                }),
10914                                HoverLink::InlayHint(_, _) => None,
10915                                HoverLink::Url(_) => None,
10916                                HoverLink::File(_) => None,
10917                            })
10918                            .unwrap_or(tab_kind.to_string());
10919                        let location_tasks = definitions
10920                            .into_iter()
10921                            .map(|definition| match definition {
10922                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10923                                HoverLink::InlayHint(lsp_location, server_id) => editor
10924                                    .compute_target_location(lsp_location, server_id, window, cx),
10925                                HoverLink::Url(_) => Task::ready(Ok(None)),
10926                                HoverLink::File(_) => Task::ready(Ok(None)),
10927                            })
10928                            .collect::<Vec<_>>();
10929                        (title, location_tasks, editor.workspace().clone())
10930                    })
10931                    .context("location tasks preparation")?;
10932
10933                let locations = future::join_all(location_tasks)
10934                    .await
10935                    .into_iter()
10936                    .filter_map(|location| location.transpose())
10937                    .collect::<Result<_>>()
10938                    .context("location tasks")?;
10939
10940                let Some(workspace) = workspace else {
10941                    return Ok(Navigated::No);
10942                };
10943                let opened = workspace
10944                    .update_in(&mut cx, |workspace, window, cx| {
10945                        Self::open_locations_in_multibuffer(
10946                            workspace,
10947                            locations,
10948                            title,
10949                            split,
10950                            MultibufferSelectionMode::First,
10951                            window,
10952                            cx,
10953                        )
10954                    })
10955                    .ok();
10956
10957                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10958            })
10959        } else {
10960            Task::ready(Ok(Navigated::No))
10961        }
10962    }
10963
10964    fn compute_target_location(
10965        &self,
10966        lsp_location: lsp::Location,
10967        server_id: LanguageServerId,
10968        window: &mut Window,
10969        cx: &mut Context<Self>,
10970    ) -> Task<anyhow::Result<Option<Location>>> {
10971        let Some(project) = self.project.clone() else {
10972            return Task::ready(Ok(None));
10973        };
10974
10975        cx.spawn_in(window, move |editor, mut cx| async move {
10976            let location_task = editor.update(&mut cx, |_, cx| {
10977                project.update(cx, |project, cx| {
10978                    let language_server_name = project
10979                        .language_server_statuses(cx)
10980                        .find(|(id, _)| server_id == *id)
10981                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10982                    language_server_name.map(|language_server_name| {
10983                        project.open_local_buffer_via_lsp(
10984                            lsp_location.uri.clone(),
10985                            server_id,
10986                            language_server_name,
10987                            cx,
10988                        )
10989                    })
10990                })
10991            })?;
10992            let location = match location_task {
10993                Some(task) => Some({
10994                    let target_buffer_handle = task.await.context("open local buffer")?;
10995                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10996                        let target_start = target_buffer
10997                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10998                        let target_end = target_buffer
10999                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11000                        target_buffer.anchor_after(target_start)
11001                            ..target_buffer.anchor_before(target_end)
11002                    })?;
11003                    Location {
11004                        buffer: target_buffer_handle,
11005                        range,
11006                    }
11007                }),
11008                None => None,
11009            };
11010            Ok(location)
11011        })
11012    }
11013
11014    pub fn find_all_references(
11015        &mut self,
11016        _: &FindAllReferences,
11017        window: &mut Window,
11018        cx: &mut Context<Self>,
11019    ) -> Option<Task<Result<Navigated>>> {
11020        let selection = self.selections.newest::<usize>(cx);
11021        let multi_buffer = self.buffer.read(cx);
11022        let head = selection.head();
11023
11024        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11025        let head_anchor = multi_buffer_snapshot.anchor_at(
11026            head,
11027            if head < selection.tail() {
11028                Bias::Right
11029            } else {
11030                Bias::Left
11031            },
11032        );
11033
11034        match self
11035            .find_all_references_task_sources
11036            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11037        {
11038            Ok(_) => {
11039                log::info!(
11040                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11041                );
11042                return None;
11043            }
11044            Err(i) => {
11045                self.find_all_references_task_sources.insert(i, head_anchor);
11046            }
11047        }
11048
11049        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11050        let workspace = self.workspace()?;
11051        let project = workspace.read(cx).project().clone();
11052        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11053        Some(cx.spawn_in(window, |editor, mut cx| async move {
11054            let _cleanup = defer({
11055                let mut cx = cx.clone();
11056                move || {
11057                    let _ = editor.update(&mut cx, |editor, _| {
11058                        if let Ok(i) =
11059                            editor
11060                                .find_all_references_task_sources
11061                                .binary_search_by(|anchor| {
11062                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11063                                })
11064                        {
11065                            editor.find_all_references_task_sources.remove(i);
11066                        }
11067                    });
11068                }
11069            });
11070
11071            let locations = references.await?;
11072            if locations.is_empty() {
11073                return anyhow::Ok(Navigated::No);
11074            }
11075
11076            workspace.update_in(&mut cx, |workspace, window, cx| {
11077                let title = locations
11078                    .first()
11079                    .as_ref()
11080                    .map(|location| {
11081                        let buffer = location.buffer.read(cx);
11082                        format!(
11083                            "References to `{}`",
11084                            buffer
11085                                .text_for_range(location.range.clone())
11086                                .collect::<String>()
11087                        )
11088                    })
11089                    .unwrap();
11090                Self::open_locations_in_multibuffer(
11091                    workspace,
11092                    locations,
11093                    title,
11094                    false,
11095                    MultibufferSelectionMode::First,
11096                    window,
11097                    cx,
11098                );
11099                Navigated::Yes
11100            })
11101        }))
11102    }
11103
11104    /// Opens a multibuffer with the given project locations in it
11105    pub fn open_locations_in_multibuffer(
11106        workspace: &mut Workspace,
11107        mut locations: Vec<Location>,
11108        title: String,
11109        split: bool,
11110        multibuffer_selection_mode: MultibufferSelectionMode,
11111        window: &mut Window,
11112        cx: &mut Context<Workspace>,
11113    ) {
11114        // If there are multiple definitions, open them in a multibuffer
11115        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11116        let mut locations = locations.into_iter().peekable();
11117        let mut ranges = Vec::new();
11118        let capability = workspace.project().read(cx).capability();
11119
11120        let excerpt_buffer = cx.new(|cx| {
11121            let mut multibuffer = MultiBuffer::new(capability);
11122            while let Some(location) = locations.next() {
11123                let buffer = location.buffer.read(cx);
11124                let mut ranges_for_buffer = Vec::new();
11125                let range = location.range.to_offset(buffer);
11126                ranges_for_buffer.push(range.clone());
11127
11128                while let Some(next_location) = locations.peek() {
11129                    if next_location.buffer == location.buffer {
11130                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11131                        locations.next();
11132                    } else {
11133                        break;
11134                    }
11135                }
11136
11137                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11138                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11139                    location.buffer.clone(),
11140                    ranges_for_buffer,
11141                    DEFAULT_MULTIBUFFER_CONTEXT,
11142                    cx,
11143                ))
11144            }
11145
11146            multibuffer.with_title(title)
11147        });
11148
11149        let editor = cx.new(|cx| {
11150            Editor::for_multibuffer(
11151                excerpt_buffer,
11152                Some(workspace.project().clone()),
11153                true,
11154                window,
11155                cx,
11156            )
11157        });
11158        editor.update(cx, |editor, cx| {
11159            match multibuffer_selection_mode {
11160                MultibufferSelectionMode::First => {
11161                    if let Some(first_range) = ranges.first() {
11162                        editor.change_selections(None, window, cx, |selections| {
11163                            selections.clear_disjoint();
11164                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11165                        });
11166                    }
11167                    editor.highlight_background::<Self>(
11168                        &ranges,
11169                        |theme| theme.editor_highlighted_line_background,
11170                        cx,
11171                    );
11172                }
11173                MultibufferSelectionMode::All => {
11174                    editor.change_selections(None, window, cx, |selections| {
11175                        selections.clear_disjoint();
11176                        selections.select_anchor_ranges(ranges);
11177                    });
11178                }
11179            }
11180            editor.register_buffers_with_language_servers(cx);
11181        });
11182
11183        let item = Box::new(editor);
11184        let item_id = item.item_id();
11185
11186        if split {
11187            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11188        } else {
11189            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11190                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11191                    pane.close_current_preview_item(window, cx)
11192                } else {
11193                    None
11194                }
11195            });
11196            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11197        }
11198        workspace.active_pane().update(cx, |pane, cx| {
11199            pane.set_preview_item_id(Some(item_id), cx);
11200        });
11201    }
11202
11203    pub fn rename(
11204        &mut self,
11205        _: &Rename,
11206        window: &mut Window,
11207        cx: &mut Context<Self>,
11208    ) -> Option<Task<Result<()>>> {
11209        use language::ToOffset as _;
11210
11211        let provider = self.semantics_provider.clone()?;
11212        let selection = self.selections.newest_anchor().clone();
11213        let (cursor_buffer, cursor_buffer_position) = self
11214            .buffer
11215            .read(cx)
11216            .text_anchor_for_position(selection.head(), cx)?;
11217        let (tail_buffer, cursor_buffer_position_end) = self
11218            .buffer
11219            .read(cx)
11220            .text_anchor_for_position(selection.tail(), cx)?;
11221        if tail_buffer != cursor_buffer {
11222            return None;
11223        }
11224
11225        let snapshot = cursor_buffer.read(cx).snapshot();
11226        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11227        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11228        let prepare_rename = provider
11229            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11230            .unwrap_or_else(|| Task::ready(Ok(None)));
11231        drop(snapshot);
11232
11233        Some(cx.spawn_in(window, |this, mut cx| async move {
11234            let rename_range = if let Some(range) = prepare_rename.await? {
11235                Some(range)
11236            } else {
11237                this.update(&mut cx, |this, cx| {
11238                    let buffer = this.buffer.read(cx).snapshot(cx);
11239                    let mut buffer_highlights = this
11240                        .document_highlights_for_position(selection.head(), &buffer)
11241                        .filter(|highlight| {
11242                            highlight.start.excerpt_id == selection.head().excerpt_id
11243                                && highlight.end.excerpt_id == selection.head().excerpt_id
11244                        });
11245                    buffer_highlights
11246                        .next()
11247                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11248                })?
11249            };
11250            if let Some(rename_range) = rename_range {
11251                this.update_in(&mut cx, |this, window, cx| {
11252                    let snapshot = cursor_buffer.read(cx).snapshot();
11253                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11254                    let cursor_offset_in_rename_range =
11255                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11256                    let cursor_offset_in_rename_range_end =
11257                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11258
11259                    this.take_rename(false, window, cx);
11260                    let buffer = this.buffer.read(cx).read(cx);
11261                    let cursor_offset = selection.head().to_offset(&buffer);
11262                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11263                    let rename_end = rename_start + rename_buffer_range.len();
11264                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11265                    let mut old_highlight_id = None;
11266                    let old_name: Arc<str> = buffer
11267                        .chunks(rename_start..rename_end, true)
11268                        .map(|chunk| {
11269                            if old_highlight_id.is_none() {
11270                                old_highlight_id = chunk.syntax_highlight_id;
11271                            }
11272                            chunk.text
11273                        })
11274                        .collect::<String>()
11275                        .into();
11276
11277                    drop(buffer);
11278
11279                    // Position the selection in the rename editor so that it matches the current selection.
11280                    this.show_local_selections = false;
11281                    let rename_editor = cx.new(|cx| {
11282                        let mut editor = Editor::single_line(window, cx);
11283                        editor.buffer.update(cx, |buffer, cx| {
11284                            buffer.edit([(0..0, old_name.clone())], None, cx)
11285                        });
11286                        let rename_selection_range = match cursor_offset_in_rename_range
11287                            .cmp(&cursor_offset_in_rename_range_end)
11288                        {
11289                            Ordering::Equal => {
11290                                editor.select_all(&SelectAll, window, cx);
11291                                return editor;
11292                            }
11293                            Ordering::Less => {
11294                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11295                            }
11296                            Ordering::Greater => {
11297                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11298                            }
11299                        };
11300                        if rename_selection_range.end > old_name.len() {
11301                            editor.select_all(&SelectAll, window, cx);
11302                        } else {
11303                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11304                                s.select_ranges([rename_selection_range]);
11305                            });
11306                        }
11307                        editor
11308                    });
11309                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11310                        if e == &EditorEvent::Focused {
11311                            cx.emit(EditorEvent::FocusedIn)
11312                        }
11313                    })
11314                    .detach();
11315
11316                    let write_highlights =
11317                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11318                    let read_highlights =
11319                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11320                    let ranges = write_highlights
11321                        .iter()
11322                        .flat_map(|(_, ranges)| ranges.iter())
11323                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11324                        .cloned()
11325                        .collect();
11326
11327                    this.highlight_text::<Rename>(
11328                        ranges,
11329                        HighlightStyle {
11330                            fade_out: Some(0.6),
11331                            ..Default::default()
11332                        },
11333                        cx,
11334                    );
11335                    let rename_focus_handle = rename_editor.focus_handle(cx);
11336                    window.focus(&rename_focus_handle);
11337                    let block_id = this.insert_blocks(
11338                        [BlockProperties {
11339                            style: BlockStyle::Flex,
11340                            placement: BlockPlacement::Below(range.start),
11341                            height: 1,
11342                            render: Arc::new({
11343                                let rename_editor = rename_editor.clone();
11344                                move |cx: &mut BlockContext| {
11345                                    let mut text_style = cx.editor_style.text.clone();
11346                                    if let Some(highlight_style) = old_highlight_id
11347                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11348                                    {
11349                                        text_style = text_style.highlight(highlight_style);
11350                                    }
11351                                    div()
11352                                        .block_mouse_down()
11353                                        .pl(cx.anchor_x)
11354                                        .child(EditorElement::new(
11355                                            &rename_editor,
11356                                            EditorStyle {
11357                                                background: cx.theme().system().transparent,
11358                                                local_player: cx.editor_style.local_player,
11359                                                text: text_style,
11360                                                scrollbar_width: cx.editor_style.scrollbar_width,
11361                                                syntax: cx.editor_style.syntax.clone(),
11362                                                status: cx.editor_style.status.clone(),
11363                                                inlay_hints_style: HighlightStyle {
11364                                                    font_weight: Some(FontWeight::BOLD),
11365                                                    ..make_inlay_hints_style(cx.app)
11366                                                },
11367                                                inline_completion_styles: make_suggestion_styles(
11368                                                    cx.app,
11369                                                ),
11370                                                ..EditorStyle::default()
11371                                            },
11372                                        ))
11373                                        .into_any_element()
11374                                }
11375                            }),
11376                            priority: 0,
11377                        }],
11378                        Some(Autoscroll::fit()),
11379                        cx,
11380                    )[0];
11381                    this.pending_rename = Some(RenameState {
11382                        range,
11383                        old_name,
11384                        editor: rename_editor,
11385                        block_id,
11386                    });
11387                })?;
11388            }
11389
11390            Ok(())
11391        }))
11392    }
11393
11394    pub fn confirm_rename(
11395        &mut self,
11396        _: &ConfirmRename,
11397        window: &mut Window,
11398        cx: &mut Context<Self>,
11399    ) -> Option<Task<Result<()>>> {
11400        let rename = self.take_rename(false, window, cx)?;
11401        let workspace = self.workspace()?.downgrade();
11402        let (buffer, start) = self
11403            .buffer
11404            .read(cx)
11405            .text_anchor_for_position(rename.range.start, cx)?;
11406        let (end_buffer, _) = self
11407            .buffer
11408            .read(cx)
11409            .text_anchor_for_position(rename.range.end, cx)?;
11410        if buffer != end_buffer {
11411            return None;
11412        }
11413
11414        let old_name = rename.old_name;
11415        let new_name = rename.editor.read(cx).text(cx);
11416
11417        let rename = self.semantics_provider.as_ref()?.perform_rename(
11418            &buffer,
11419            start,
11420            new_name.clone(),
11421            cx,
11422        )?;
11423
11424        Some(cx.spawn_in(window, |editor, mut cx| async move {
11425            let project_transaction = rename.await?;
11426            Self::open_project_transaction(
11427                &editor,
11428                workspace,
11429                project_transaction,
11430                format!("Rename: {}{}", old_name, new_name),
11431                cx.clone(),
11432            )
11433            .await?;
11434
11435            editor.update(&mut cx, |editor, cx| {
11436                editor.refresh_document_highlights(cx);
11437            })?;
11438            Ok(())
11439        }))
11440    }
11441
11442    fn take_rename(
11443        &mut self,
11444        moving_cursor: bool,
11445        window: &mut Window,
11446        cx: &mut Context<Self>,
11447    ) -> Option<RenameState> {
11448        let rename = self.pending_rename.take()?;
11449        if rename.editor.focus_handle(cx).is_focused(window) {
11450            window.focus(&self.focus_handle);
11451        }
11452
11453        self.remove_blocks(
11454            [rename.block_id].into_iter().collect(),
11455            Some(Autoscroll::fit()),
11456            cx,
11457        );
11458        self.clear_highlights::<Rename>(cx);
11459        self.show_local_selections = true;
11460
11461        if moving_cursor {
11462            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11463                editor.selections.newest::<usize>(cx).head()
11464            });
11465
11466            // Update the selection to match the position of the selection inside
11467            // the rename editor.
11468            let snapshot = self.buffer.read(cx).read(cx);
11469            let rename_range = rename.range.to_offset(&snapshot);
11470            let cursor_in_editor = snapshot
11471                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11472                .min(rename_range.end);
11473            drop(snapshot);
11474
11475            self.change_selections(None, window, cx, |s| {
11476                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11477            });
11478        } else {
11479            self.refresh_document_highlights(cx);
11480        }
11481
11482        Some(rename)
11483    }
11484
11485    pub fn pending_rename(&self) -> Option<&RenameState> {
11486        self.pending_rename.as_ref()
11487    }
11488
11489    fn format(
11490        &mut self,
11491        _: &Format,
11492        window: &mut Window,
11493        cx: &mut Context<Self>,
11494    ) -> Option<Task<Result<()>>> {
11495        let project = match &self.project {
11496            Some(project) => project.clone(),
11497            None => return None,
11498        };
11499
11500        Some(self.perform_format(
11501            project,
11502            FormatTrigger::Manual,
11503            FormatTarget::Buffers,
11504            window,
11505            cx,
11506        ))
11507    }
11508
11509    fn format_selections(
11510        &mut self,
11511        _: &FormatSelections,
11512        window: &mut Window,
11513        cx: &mut Context<Self>,
11514    ) -> Option<Task<Result<()>>> {
11515        let project = match &self.project {
11516            Some(project) => project.clone(),
11517            None => return None,
11518        };
11519
11520        let ranges = self
11521            .selections
11522            .all_adjusted(cx)
11523            .into_iter()
11524            .map(|selection| selection.range())
11525            .collect_vec();
11526
11527        Some(self.perform_format(
11528            project,
11529            FormatTrigger::Manual,
11530            FormatTarget::Ranges(ranges),
11531            window,
11532            cx,
11533        ))
11534    }
11535
11536    fn perform_format(
11537        &mut self,
11538        project: Entity<Project>,
11539        trigger: FormatTrigger,
11540        target: FormatTarget,
11541        window: &mut Window,
11542        cx: &mut Context<Self>,
11543    ) -> Task<Result<()>> {
11544        let buffer = self.buffer.clone();
11545        let (buffers, target) = match target {
11546            FormatTarget::Buffers => {
11547                let mut buffers = buffer.read(cx).all_buffers();
11548                if trigger == FormatTrigger::Save {
11549                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11550                }
11551                (buffers, LspFormatTarget::Buffers)
11552            }
11553            FormatTarget::Ranges(selection_ranges) => {
11554                let multi_buffer = buffer.read(cx);
11555                let snapshot = multi_buffer.read(cx);
11556                let mut buffers = HashSet::default();
11557                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11558                    BTreeMap::new();
11559                for selection_range in selection_ranges {
11560                    for (buffer, buffer_range, _) in
11561                        snapshot.range_to_buffer_ranges(selection_range)
11562                    {
11563                        let buffer_id = buffer.remote_id();
11564                        let start = buffer.anchor_before(buffer_range.start);
11565                        let end = buffer.anchor_after(buffer_range.end);
11566                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11567                        buffer_id_to_ranges
11568                            .entry(buffer_id)
11569                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11570                            .or_insert_with(|| vec![start..end]);
11571                    }
11572                }
11573                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11574            }
11575        };
11576
11577        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11578        let format = project.update(cx, |project, cx| {
11579            project.format(buffers, target, true, trigger, cx)
11580        });
11581
11582        cx.spawn_in(window, |_, mut cx| async move {
11583            let transaction = futures::select_biased! {
11584                () = timeout => {
11585                    log::warn!("timed out waiting for formatting");
11586                    None
11587                }
11588                transaction = format.log_err().fuse() => transaction,
11589            };
11590
11591            buffer
11592                .update(&mut cx, |buffer, cx| {
11593                    if let Some(transaction) = transaction {
11594                        if !buffer.is_singleton() {
11595                            buffer.push_transaction(&transaction.0, cx);
11596                        }
11597                    }
11598
11599                    cx.notify();
11600                })
11601                .ok();
11602
11603            Ok(())
11604        })
11605    }
11606
11607    fn restart_language_server(
11608        &mut self,
11609        _: &RestartLanguageServer,
11610        _: &mut Window,
11611        cx: &mut Context<Self>,
11612    ) {
11613        if let Some(project) = self.project.clone() {
11614            self.buffer.update(cx, |multi_buffer, cx| {
11615                project.update(cx, |project, cx| {
11616                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11617                });
11618            })
11619        }
11620    }
11621
11622    fn cancel_language_server_work(
11623        workspace: &mut Workspace,
11624        _: &actions::CancelLanguageServerWork,
11625        _: &mut Window,
11626        cx: &mut Context<Workspace>,
11627    ) {
11628        let project = workspace.project();
11629        let buffers = workspace
11630            .active_item(cx)
11631            .and_then(|item| item.act_as::<Editor>(cx))
11632            .map_or(HashSet::default(), |editor| {
11633                editor.read(cx).buffer.read(cx).all_buffers()
11634            });
11635        project.update(cx, |project, cx| {
11636            project.cancel_language_server_work_for_buffers(buffers, cx);
11637        });
11638    }
11639
11640    fn show_character_palette(
11641        &mut self,
11642        _: &ShowCharacterPalette,
11643        window: &mut Window,
11644        _: &mut Context<Self>,
11645    ) {
11646        window.show_character_palette();
11647    }
11648
11649    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11650        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11651            let buffer = self.buffer.read(cx).snapshot(cx);
11652            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11653            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11654            let is_valid = buffer
11655                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11656                .any(|entry| {
11657                    entry.diagnostic.is_primary
11658                        && !entry.range.is_empty()
11659                        && entry.range.start == primary_range_start
11660                        && entry.diagnostic.message == active_diagnostics.primary_message
11661                });
11662
11663            if is_valid != active_diagnostics.is_valid {
11664                active_diagnostics.is_valid = is_valid;
11665                let mut new_styles = HashMap::default();
11666                for (block_id, diagnostic) in &active_diagnostics.blocks {
11667                    new_styles.insert(
11668                        *block_id,
11669                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11670                    );
11671                }
11672                self.display_map.update(cx, |display_map, _cx| {
11673                    display_map.replace_blocks(new_styles)
11674                });
11675            }
11676        }
11677    }
11678
11679    fn activate_diagnostics(
11680        &mut self,
11681        buffer_id: BufferId,
11682        group_id: usize,
11683        window: &mut Window,
11684        cx: &mut Context<Self>,
11685    ) {
11686        self.dismiss_diagnostics(cx);
11687        let snapshot = self.snapshot(window, cx);
11688        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11689            let buffer = self.buffer.read(cx).snapshot(cx);
11690
11691            let mut primary_range = None;
11692            let mut primary_message = None;
11693            let diagnostic_group = buffer
11694                .diagnostic_group(buffer_id, group_id)
11695                .filter_map(|entry| {
11696                    let start = entry.range.start;
11697                    let end = entry.range.end;
11698                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11699                        && (start.row == end.row
11700                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11701                    {
11702                        return None;
11703                    }
11704                    if entry.diagnostic.is_primary {
11705                        primary_range = Some(entry.range.clone());
11706                        primary_message = Some(entry.diagnostic.message.clone());
11707                    }
11708                    Some(entry)
11709                })
11710                .collect::<Vec<_>>();
11711            let primary_range = primary_range?;
11712            let primary_message = primary_message?;
11713
11714            let blocks = display_map
11715                .insert_blocks(
11716                    diagnostic_group.iter().map(|entry| {
11717                        let diagnostic = entry.diagnostic.clone();
11718                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11719                        BlockProperties {
11720                            style: BlockStyle::Fixed,
11721                            placement: BlockPlacement::Below(
11722                                buffer.anchor_after(entry.range.start),
11723                            ),
11724                            height: message_height,
11725                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11726                            priority: 0,
11727                        }
11728                    }),
11729                    cx,
11730                )
11731                .into_iter()
11732                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11733                .collect();
11734
11735            Some(ActiveDiagnosticGroup {
11736                primary_range: buffer.anchor_before(primary_range.start)
11737                    ..buffer.anchor_after(primary_range.end),
11738                primary_message,
11739                group_id,
11740                blocks,
11741                is_valid: true,
11742            })
11743        });
11744    }
11745
11746    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11747        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11748            self.display_map.update(cx, |display_map, cx| {
11749                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11750            });
11751            cx.notify();
11752        }
11753    }
11754
11755    pub fn set_selections_from_remote(
11756        &mut self,
11757        selections: Vec<Selection<Anchor>>,
11758        pending_selection: Option<Selection<Anchor>>,
11759        window: &mut Window,
11760        cx: &mut Context<Self>,
11761    ) {
11762        let old_cursor_position = self.selections.newest_anchor().head();
11763        self.selections.change_with(cx, |s| {
11764            s.select_anchors(selections);
11765            if let Some(pending_selection) = pending_selection {
11766                s.set_pending(pending_selection, SelectMode::Character);
11767            } else {
11768                s.clear_pending();
11769            }
11770        });
11771        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11772    }
11773
11774    fn push_to_selection_history(&mut self) {
11775        self.selection_history.push(SelectionHistoryEntry {
11776            selections: self.selections.disjoint_anchors(),
11777            select_next_state: self.select_next_state.clone(),
11778            select_prev_state: self.select_prev_state.clone(),
11779            add_selections_state: self.add_selections_state.clone(),
11780        });
11781    }
11782
11783    pub fn transact(
11784        &mut self,
11785        window: &mut Window,
11786        cx: &mut Context<Self>,
11787        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11788    ) -> Option<TransactionId> {
11789        self.start_transaction_at(Instant::now(), window, cx);
11790        update(self, window, cx);
11791        self.end_transaction_at(Instant::now(), cx)
11792    }
11793
11794    pub fn start_transaction_at(
11795        &mut self,
11796        now: Instant,
11797        window: &mut Window,
11798        cx: &mut Context<Self>,
11799    ) {
11800        self.end_selection(window, cx);
11801        if let Some(tx_id) = self
11802            .buffer
11803            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11804        {
11805            self.selection_history
11806                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11807            cx.emit(EditorEvent::TransactionBegun {
11808                transaction_id: tx_id,
11809            })
11810        }
11811    }
11812
11813    pub fn end_transaction_at(
11814        &mut self,
11815        now: Instant,
11816        cx: &mut Context<Self>,
11817    ) -> Option<TransactionId> {
11818        if let Some(transaction_id) = self
11819            .buffer
11820            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11821        {
11822            if let Some((_, end_selections)) =
11823                self.selection_history.transaction_mut(transaction_id)
11824            {
11825                *end_selections = Some(self.selections.disjoint_anchors());
11826            } else {
11827                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11828            }
11829
11830            cx.emit(EditorEvent::Edited { transaction_id });
11831            Some(transaction_id)
11832        } else {
11833            None
11834        }
11835    }
11836
11837    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11838        if self.selection_mark_mode {
11839            self.change_selections(None, window, cx, |s| {
11840                s.move_with(|_, sel| {
11841                    sel.collapse_to(sel.head(), SelectionGoal::None);
11842                });
11843            })
11844        }
11845        self.selection_mark_mode = true;
11846        cx.notify();
11847    }
11848
11849    pub fn swap_selection_ends(
11850        &mut self,
11851        _: &actions::SwapSelectionEnds,
11852        window: &mut Window,
11853        cx: &mut Context<Self>,
11854    ) {
11855        self.change_selections(None, window, cx, |s| {
11856            s.move_with(|_, sel| {
11857                if sel.start != sel.end {
11858                    sel.reversed = !sel.reversed
11859                }
11860            });
11861        });
11862        self.request_autoscroll(Autoscroll::newest(), cx);
11863        cx.notify();
11864    }
11865
11866    pub fn toggle_fold(
11867        &mut self,
11868        _: &actions::ToggleFold,
11869        window: &mut Window,
11870        cx: &mut Context<Self>,
11871    ) {
11872        if self.is_singleton(cx) {
11873            let selection = self.selections.newest::<Point>(cx);
11874
11875            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11876            let range = if selection.is_empty() {
11877                let point = selection.head().to_display_point(&display_map);
11878                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11879                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11880                    .to_point(&display_map);
11881                start..end
11882            } else {
11883                selection.range()
11884            };
11885            if display_map.folds_in_range(range).next().is_some() {
11886                self.unfold_lines(&Default::default(), window, cx)
11887            } else {
11888                self.fold(&Default::default(), window, cx)
11889            }
11890        } else {
11891            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11892            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11893                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11894                .map(|(snapshot, _, _)| snapshot.remote_id())
11895                .collect();
11896
11897            for buffer_id in buffer_ids {
11898                if self.is_buffer_folded(buffer_id, cx) {
11899                    self.unfold_buffer(buffer_id, cx);
11900                } else {
11901                    self.fold_buffer(buffer_id, cx);
11902                }
11903            }
11904        }
11905    }
11906
11907    pub fn toggle_fold_recursive(
11908        &mut self,
11909        _: &actions::ToggleFoldRecursive,
11910        window: &mut Window,
11911        cx: &mut Context<Self>,
11912    ) {
11913        let selection = self.selections.newest::<Point>(cx);
11914
11915        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11916        let range = if selection.is_empty() {
11917            let point = selection.head().to_display_point(&display_map);
11918            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11919            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11920                .to_point(&display_map);
11921            start..end
11922        } else {
11923            selection.range()
11924        };
11925        if display_map.folds_in_range(range).next().is_some() {
11926            self.unfold_recursive(&Default::default(), window, cx)
11927        } else {
11928            self.fold_recursive(&Default::default(), window, cx)
11929        }
11930    }
11931
11932    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11933        if self.is_singleton(cx) {
11934            let mut to_fold = Vec::new();
11935            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11936            let selections = self.selections.all_adjusted(cx);
11937
11938            for selection in selections {
11939                let range = selection.range().sorted();
11940                let buffer_start_row = range.start.row;
11941
11942                if range.start.row != range.end.row {
11943                    let mut found = false;
11944                    let mut row = range.start.row;
11945                    while row <= range.end.row {
11946                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11947                        {
11948                            found = true;
11949                            row = crease.range().end.row + 1;
11950                            to_fold.push(crease);
11951                        } else {
11952                            row += 1
11953                        }
11954                    }
11955                    if found {
11956                        continue;
11957                    }
11958                }
11959
11960                for row in (0..=range.start.row).rev() {
11961                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11962                        if crease.range().end.row >= buffer_start_row {
11963                            to_fold.push(crease);
11964                            if row <= range.start.row {
11965                                break;
11966                            }
11967                        }
11968                    }
11969                }
11970            }
11971
11972            self.fold_creases(to_fold, true, window, cx);
11973        } else {
11974            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11975
11976            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11977                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11978                .map(|(snapshot, _, _)| snapshot.remote_id())
11979                .collect();
11980            for buffer_id in buffer_ids {
11981                self.fold_buffer(buffer_id, cx);
11982            }
11983        }
11984    }
11985
11986    fn fold_at_level(
11987        &mut self,
11988        fold_at: &FoldAtLevel,
11989        window: &mut Window,
11990        cx: &mut Context<Self>,
11991    ) {
11992        if !self.buffer.read(cx).is_singleton() {
11993            return;
11994        }
11995
11996        let fold_at_level = fold_at.0;
11997        let snapshot = self.buffer.read(cx).snapshot(cx);
11998        let mut to_fold = Vec::new();
11999        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12000
12001        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12002            while start_row < end_row {
12003                match self
12004                    .snapshot(window, cx)
12005                    .crease_for_buffer_row(MultiBufferRow(start_row))
12006                {
12007                    Some(crease) => {
12008                        let nested_start_row = crease.range().start.row + 1;
12009                        let nested_end_row = crease.range().end.row;
12010
12011                        if current_level < fold_at_level {
12012                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12013                        } else if current_level == fold_at_level {
12014                            to_fold.push(crease);
12015                        }
12016
12017                        start_row = nested_end_row + 1;
12018                    }
12019                    None => start_row += 1,
12020                }
12021            }
12022        }
12023
12024        self.fold_creases(to_fold, true, window, cx);
12025    }
12026
12027    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12028        if self.buffer.read(cx).is_singleton() {
12029            let mut fold_ranges = Vec::new();
12030            let snapshot = self.buffer.read(cx).snapshot(cx);
12031
12032            for row in 0..snapshot.max_row().0 {
12033                if let Some(foldable_range) = self
12034                    .snapshot(window, cx)
12035                    .crease_for_buffer_row(MultiBufferRow(row))
12036                {
12037                    fold_ranges.push(foldable_range);
12038                }
12039            }
12040
12041            self.fold_creases(fold_ranges, true, window, cx);
12042        } else {
12043            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12044                editor
12045                    .update_in(&mut cx, |editor, _, cx| {
12046                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12047                            editor.fold_buffer(buffer_id, cx);
12048                        }
12049                    })
12050                    .ok();
12051            });
12052        }
12053    }
12054
12055    pub fn fold_function_bodies(
12056        &mut self,
12057        _: &actions::FoldFunctionBodies,
12058        window: &mut Window,
12059        cx: &mut Context<Self>,
12060    ) {
12061        let snapshot = self.buffer.read(cx).snapshot(cx);
12062
12063        let ranges = snapshot
12064            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12065            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12066            .collect::<Vec<_>>();
12067
12068        let creases = ranges
12069            .into_iter()
12070            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12071            .collect();
12072
12073        self.fold_creases(creases, true, window, cx);
12074    }
12075
12076    pub fn fold_recursive(
12077        &mut self,
12078        _: &actions::FoldRecursive,
12079        window: &mut Window,
12080        cx: &mut Context<Self>,
12081    ) {
12082        let mut to_fold = Vec::new();
12083        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12084        let selections = self.selections.all_adjusted(cx);
12085
12086        for selection in selections {
12087            let range = selection.range().sorted();
12088            let buffer_start_row = range.start.row;
12089
12090            if range.start.row != range.end.row {
12091                let mut found = false;
12092                for row in range.start.row..=range.end.row {
12093                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12094                        found = true;
12095                        to_fold.push(crease);
12096                    }
12097                }
12098                if found {
12099                    continue;
12100                }
12101            }
12102
12103            for row in (0..=range.start.row).rev() {
12104                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12105                    if crease.range().end.row >= buffer_start_row {
12106                        to_fold.push(crease);
12107                    } else {
12108                        break;
12109                    }
12110                }
12111            }
12112        }
12113
12114        self.fold_creases(to_fold, true, window, cx);
12115    }
12116
12117    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12118        let buffer_row = fold_at.buffer_row;
12119        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12120
12121        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12122            let autoscroll = self
12123                .selections
12124                .all::<Point>(cx)
12125                .iter()
12126                .any(|selection| crease.range().overlaps(&selection.range()));
12127
12128            self.fold_creases(vec![crease], autoscroll, window, cx);
12129        }
12130    }
12131
12132    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12133        if self.is_singleton(cx) {
12134            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12135            let buffer = &display_map.buffer_snapshot;
12136            let selections = self.selections.all::<Point>(cx);
12137            let ranges = selections
12138                .iter()
12139                .map(|s| {
12140                    let range = s.display_range(&display_map).sorted();
12141                    let mut start = range.start.to_point(&display_map);
12142                    let mut end = range.end.to_point(&display_map);
12143                    start.column = 0;
12144                    end.column = buffer.line_len(MultiBufferRow(end.row));
12145                    start..end
12146                })
12147                .collect::<Vec<_>>();
12148
12149            self.unfold_ranges(&ranges, true, true, cx);
12150        } else {
12151            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12152            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12153                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12154                .map(|(snapshot, _, _)| snapshot.remote_id())
12155                .collect();
12156            for buffer_id in buffer_ids {
12157                self.unfold_buffer(buffer_id, cx);
12158            }
12159        }
12160    }
12161
12162    pub fn unfold_recursive(
12163        &mut self,
12164        _: &UnfoldRecursive,
12165        _window: &mut Window,
12166        cx: &mut Context<Self>,
12167    ) {
12168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12169        let selections = self.selections.all::<Point>(cx);
12170        let ranges = selections
12171            .iter()
12172            .map(|s| {
12173                let mut range = s.display_range(&display_map).sorted();
12174                *range.start.column_mut() = 0;
12175                *range.end.column_mut() = display_map.line_len(range.end.row());
12176                let start = range.start.to_point(&display_map);
12177                let end = range.end.to_point(&display_map);
12178                start..end
12179            })
12180            .collect::<Vec<_>>();
12181
12182        self.unfold_ranges(&ranges, true, true, cx);
12183    }
12184
12185    pub fn unfold_at(
12186        &mut self,
12187        unfold_at: &UnfoldAt,
12188        _window: &mut Window,
12189        cx: &mut Context<Self>,
12190    ) {
12191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12192
12193        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12194            ..Point::new(
12195                unfold_at.buffer_row.0,
12196                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12197            );
12198
12199        let autoscroll = self
12200            .selections
12201            .all::<Point>(cx)
12202            .iter()
12203            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12204
12205        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12206    }
12207
12208    pub fn unfold_all(
12209        &mut self,
12210        _: &actions::UnfoldAll,
12211        _window: &mut Window,
12212        cx: &mut Context<Self>,
12213    ) {
12214        if self.buffer.read(cx).is_singleton() {
12215            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12216            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12217        } else {
12218            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12219                editor
12220                    .update(&mut cx, |editor, cx| {
12221                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12222                            editor.unfold_buffer(buffer_id, cx);
12223                        }
12224                    })
12225                    .ok();
12226            });
12227        }
12228    }
12229
12230    pub fn fold_selected_ranges(
12231        &mut self,
12232        _: &FoldSelectedRanges,
12233        window: &mut Window,
12234        cx: &mut Context<Self>,
12235    ) {
12236        let selections = self.selections.all::<Point>(cx);
12237        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12238        let line_mode = self.selections.line_mode;
12239        let ranges = selections
12240            .into_iter()
12241            .map(|s| {
12242                if line_mode {
12243                    let start = Point::new(s.start.row, 0);
12244                    let end = Point::new(
12245                        s.end.row,
12246                        display_map
12247                            .buffer_snapshot
12248                            .line_len(MultiBufferRow(s.end.row)),
12249                    );
12250                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12251                } else {
12252                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12253                }
12254            })
12255            .collect::<Vec<_>>();
12256        self.fold_creases(ranges, true, window, cx);
12257    }
12258
12259    pub fn fold_ranges<T: ToOffset + Clone>(
12260        &mut self,
12261        ranges: Vec<Range<T>>,
12262        auto_scroll: bool,
12263        window: &mut Window,
12264        cx: &mut Context<Self>,
12265    ) {
12266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12267        let ranges = ranges
12268            .into_iter()
12269            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12270            .collect::<Vec<_>>();
12271        self.fold_creases(ranges, auto_scroll, window, cx);
12272    }
12273
12274    pub fn fold_creases<T: ToOffset + Clone>(
12275        &mut self,
12276        creases: Vec<Crease<T>>,
12277        auto_scroll: bool,
12278        window: &mut Window,
12279        cx: &mut Context<Self>,
12280    ) {
12281        if creases.is_empty() {
12282            return;
12283        }
12284
12285        let mut buffers_affected = HashSet::default();
12286        let multi_buffer = self.buffer().read(cx);
12287        for crease in &creases {
12288            if let Some((_, buffer, _)) =
12289                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12290            {
12291                buffers_affected.insert(buffer.read(cx).remote_id());
12292            };
12293        }
12294
12295        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12296
12297        if auto_scroll {
12298            self.request_autoscroll(Autoscroll::fit(), cx);
12299        }
12300
12301        cx.notify();
12302
12303        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12304            // Clear diagnostics block when folding a range that contains it.
12305            let snapshot = self.snapshot(window, cx);
12306            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12307                drop(snapshot);
12308                self.active_diagnostics = Some(active_diagnostics);
12309                self.dismiss_diagnostics(cx);
12310            } else {
12311                self.active_diagnostics = Some(active_diagnostics);
12312            }
12313        }
12314
12315        self.scrollbar_marker_state.dirty = true;
12316    }
12317
12318    /// Removes any folds whose ranges intersect any of the given ranges.
12319    pub fn unfold_ranges<T: ToOffset + Clone>(
12320        &mut self,
12321        ranges: &[Range<T>],
12322        inclusive: bool,
12323        auto_scroll: bool,
12324        cx: &mut Context<Self>,
12325    ) {
12326        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12327            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12328        });
12329    }
12330
12331    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12332        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12333            return;
12334        }
12335        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12336        self.display_map
12337            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12338        cx.emit(EditorEvent::BufferFoldToggled {
12339            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12340            folded: true,
12341        });
12342        cx.notify();
12343    }
12344
12345    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12346        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12347            return;
12348        }
12349        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12350        self.display_map.update(cx, |display_map, cx| {
12351            display_map.unfold_buffer(buffer_id, cx);
12352        });
12353        cx.emit(EditorEvent::BufferFoldToggled {
12354            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12355            folded: false,
12356        });
12357        cx.notify();
12358    }
12359
12360    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12361        self.display_map.read(cx).is_buffer_folded(buffer)
12362    }
12363
12364    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12365        self.display_map.read(cx).folded_buffers()
12366    }
12367
12368    /// Removes any folds with the given ranges.
12369    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12370        &mut self,
12371        ranges: &[Range<T>],
12372        type_id: TypeId,
12373        auto_scroll: bool,
12374        cx: &mut Context<Self>,
12375    ) {
12376        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12377            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12378        });
12379    }
12380
12381    fn remove_folds_with<T: ToOffset + Clone>(
12382        &mut self,
12383        ranges: &[Range<T>],
12384        auto_scroll: bool,
12385        cx: &mut Context<Self>,
12386        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12387    ) {
12388        if ranges.is_empty() {
12389            return;
12390        }
12391
12392        let mut buffers_affected = HashSet::default();
12393        let multi_buffer = self.buffer().read(cx);
12394        for range in ranges {
12395            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12396                buffers_affected.insert(buffer.read(cx).remote_id());
12397            };
12398        }
12399
12400        self.display_map.update(cx, update);
12401
12402        if auto_scroll {
12403            self.request_autoscroll(Autoscroll::fit(), cx);
12404        }
12405
12406        cx.notify();
12407        self.scrollbar_marker_state.dirty = true;
12408        self.active_indent_guides_state.dirty = true;
12409    }
12410
12411    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12412        self.display_map.read(cx).fold_placeholder.clone()
12413    }
12414
12415    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12416        self.buffer.update(cx, |buffer, cx| {
12417            buffer.set_all_diff_hunks_expanded(cx);
12418        });
12419    }
12420
12421    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12422        self.distinguish_unstaged_diff_hunks = true;
12423    }
12424
12425    pub fn expand_all_diff_hunks(
12426        &mut self,
12427        _: &ExpandAllHunkDiffs,
12428        _window: &mut Window,
12429        cx: &mut Context<Self>,
12430    ) {
12431        self.buffer.update(cx, |buffer, cx| {
12432            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12433        });
12434    }
12435
12436    pub fn toggle_selected_diff_hunks(
12437        &mut self,
12438        _: &ToggleSelectedDiffHunks,
12439        _window: &mut Window,
12440        cx: &mut Context<Self>,
12441    ) {
12442        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12443        self.toggle_diff_hunks_in_ranges(ranges, cx);
12444    }
12445
12446    fn diff_hunks_in_ranges<'a>(
12447        &'a self,
12448        ranges: &'a [Range<Anchor>],
12449        buffer: &'a MultiBufferSnapshot,
12450    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12451        ranges.iter().flat_map(move |range| {
12452            let end_excerpt_id = range.end.excerpt_id;
12453            let range = range.to_point(buffer);
12454            let mut peek_end = range.end;
12455            if range.end.row < buffer.max_row().0 {
12456                peek_end = Point::new(range.end.row + 1, 0);
12457            }
12458            buffer
12459                .diff_hunks_in_range(range.start..peek_end)
12460                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12461        })
12462    }
12463
12464    pub fn has_stageable_diff_hunks_in_ranges(
12465        &self,
12466        ranges: &[Range<Anchor>],
12467        snapshot: &MultiBufferSnapshot,
12468    ) -> bool {
12469        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12470        hunks.any(|hunk| {
12471            log::debug!("considering {hunk:?}");
12472            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12473        })
12474    }
12475
12476    pub fn toggle_staged_selected_diff_hunks(
12477        &mut self,
12478        _: &ToggleStagedSelectedDiffHunks,
12479        _window: &mut Window,
12480        cx: &mut Context<Self>,
12481    ) {
12482        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12483        self.stage_or_unstage_diff_hunks(&ranges, cx);
12484    }
12485
12486    pub fn stage_or_unstage_diff_hunks(
12487        &mut self,
12488        ranges: &[Range<Anchor>],
12489        cx: &mut Context<Self>,
12490    ) {
12491        let Some(project) = &self.project else {
12492            return;
12493        };
12494        let snapshot = self.buffer.read(cx).snapshot(cx);
12495        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12496
12497        let chunk_by = self
12498            .diff_hunks_in_ranges(&ranges, &snapshot)
12499            .chunk_by(|hunk| hunk.buffer_id);
12500        for (buffer_id, hunks) in &chunk_by {
12501            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12502                log::debug!("no buffer for id");
12503                continue;
12504            };
12505            let buffer = buffer.read(cx).snapshot();
12506            let Some((repo, path)) = project
12507                .read(cx)
12508                .repository_and_path_for_buffer_id(buffer_id, cx)
12509            else {
12510                log::debug!("no git repo for buffer id");
12511                continue;
12512            };
12513            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12514                log::debug!("no diff for buffer id");
12515                continue;
12516            };
12517            let Some(secondary_diff) = diff.secondary_diff() else {
12518                log::debug!("no secondary diff for buffer id");
12519                continue;
12520            };
12521
12522            let edits = diff.secondary_edits_for_stage_or_unstage(
12523                stage,
12524                hunks.map(|hunk| {
12525                    (
12526                        hunk.diff_base_byte_range.clone(),
12527                        hunk.secondary_diff_base_byte_range.clone(),
12528                        hunk.buffer_range.clone(),
12529                    )
12530                }),
12531                &buffer,
12532            );
12533
12534            let index_base = secondary_diff.base_text().map_or_else(
12535                || Rope::from(""),
12536                |snapshot| snapshot.text.as_rope().clone(),
12537            );
12538            let index_buffer = cx.new(|cx| {
12539                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12540            });
12541            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12542                index_buffer.edit(edits, None, cx);
12543                index_buffer.snapshot().as_rope().to_string()
12544            });
12545            let new_index_text = if new_index_text.is_empty()
12546                && (diff.is_single_insertion
12547                    || buffer
12548                        .file()
12549                        .map_or(false, |file| file.disk_state() == DiskState::New))
12550            {
12551                log::debug!("removing from index");
12552                None
12553            } else {
12554                Some(new_index_text)
12555            };
12556
12557            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12558        }
12559    }
12560
12561    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12562        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12563        self.buffer
12564            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12565    }
12566
12567    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12568        self.buffer.update(cx, |buffer, cx| {
12569            let ranges = vec![Anchor::min()..Anchor::max()];
12570            if !buffer.all_diff_hunks_expanded()
12571                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12572            {
12573                buffer.collapse_diff_hunks(ranges, cx);
12574                true
12575            } else {
12576                false
12577            }
12578        })
12579    }
12580
12581    fn toggle_diff_hunks_in_ranges(
12582        &mut self,
12583        ranges: Vec<Range<Anchor>>,
12584        cx: &mut Context<'_, Editor>,
12585    ) {
12586        self.buffer.update(cx, |buffer, cx| {
12587            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12588            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12589        })
12590    }
12591
12592    fn toggle_diff_hunks_in_ranges_narrow(
12593        &mut self,
12594        ranges: Vec<Range<Anchor>>,
12595        cx: &mut Context<'_, Editor>,
12596    ) {
12597        self.buffer.update(cx, |buffer, cx| {
12598            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12599            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12600        })
12601    }
12602
12603    pub(crate) fn apply_all_diff_hunks(
12604        &mut self,
12605        _: &ApplyAllDiffHunks,
12606        window: &mut Window,
12607        cx: &mut Context<Self>,
12608    ) {
12609        let buffers = self.buffer.read(cx).all_buffers();
12610        for branch_buffer in buffers {
12611            branch_buffer.update(cx, |branch_buffer, cx| {
12612                branch_buffer.merge_into_base(Vec::new(), cx);
12613            });
12614        }
12615
12616        if let Some(project) = self.project.clone() {
12617            self.save(true, project, window, cx).detach_and_log_err(cx);
12618        }
12619    }
12620
12621    pub(crate) fn apply_selected_diff_hunks(
12622        &mut self,
12623        _: &ApplyDiffHunk,
12624        window: &mut Window,
12625        cx: &mut Context<Self>,
12626    ) {
12627        let snapshot = self.snapshot(window, cx);
12628        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12629        let mut ranges_by_buffer = HashMap::default();
12630        self.transact(window, cx, |editor, _window, cx| {
12631            for hunk in hunks {
12632                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12633                    ranges_by_buffer
12634                        .entry(buffer.clone())
12635                        .or_insert_with(Vec::new)
12636                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12637                }
12638            }
12639
12640            for (buffer, ranges) in ranges_by_buffer {
12641                buffer.update(cx, |buffer, cx| {
12642                    buffer.merge_into_base(ranges, cx);
12643                });
12644            }
12645        });
12646
12647        if let Some(project) = self.project.clone() {
12648            self.save(true, project, window, cx).detach_and_log_err(cx);
12649        }
12650    }
12651
12652    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12653        if hovered != self.gutter_hovered {
12654            self.gutter_hovered = hovered;
12655            cx.notify();
12656        }
12657    }
12658
12659    pub fn insert_blocks(
12660        &mut self,
12661        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12662        autoscroll: Option<Autoscroll>,
12663        cx: &mut Context<Self>,
12664    ) -> Vec<CustomBlockId> {
12665        let blocks = self
12666            .display_map
12667            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12668        if let Some(autoscroll) = autoscroll {
12669            self.request_autoscroll(autoscroll, cx);
12670        }
12671        cx.notify();
12672        blocks
12673    }
12674
12675    pub fn resize_blocks(
12676        &mut self,
12677        heights: HashMap<CustomBlockId, u32>,
12678        autoscroll: Option<Autoscroll>,
12679        cx: &mut Context<Self>,
12680    ) {
12681        self.display_map
12682            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12683        if let Some(autoscroll) = autoscroll {
12684            self.request_autoscroll(autoscroll, cx);
12685        }
12686        cx.notify();
12687    }
12688
12689    pub fn replace_blocks(
12690        &mut self,
12691        renderers: HashMap<CustomBlockId, RenderBlock>,
12692        autoscroll: Option<Autoscroll>,
12693        cx: &mut Context<Self>,
12694    ) {
12695        self.display_map
12696            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12697        if let Some(autoscroll) = autoscroll {
12698            self.request_autoscroll(autoscroll, cx);
12699        }
12700        cx.notify();
12701    }
12702
12703    pub fn remove_blocks(
12704        &mut self,
12705        block_ids: HashSet<CustomBlockId>,
12706        autoscroll: Option<Autoscroll>,
12707        cx: &mut Context<Self>,
12708    ) {
12709        self.display_map.update(cx, |display_map, cx| {
12710            display_map.remove_blocks(block_ids, cx)
12711        });
12712        if let Some(autoscroll) = autoscroll {
12713            self.request_autoscroll(autoscroll, cx);
12714        }
12715        cx.notify();
12716    }
12717
12718    pub fn row_for_block(
12719        &self,
12720        block_id: CustomBlockId,
12721        cx: &mut Context<Self>,
12722    ) -> Option<DisplayRow> {
12723        self.display_map
12724            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12725    }
12726
12727    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12728        self.focused_block = Some(focused_block);
12729    }
12730
12731    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12732        self.focused_block.take()
12733    }
12734
12735    pub fn insert_creases(
12736        &mut self,
12737        creases: impl IntoIterator<Item = Crease<Anchor>>,
12738        cx: &mut Context<Self>,
12739    ) -> Vec<CreaseId> {
12740        self.display_map
12741            .update(cx, |map, cx| map.insert_creases(creases, cx))
12742    }
12743
12744    pub fn remove_creases(
12745        &mut self,
12746        ids: impl IntoIterator<Item = CreaseId>,
12747        cx: &mut Context<Self>,
12748    ) {
12749        self.display_map
12750            .update(cx, |map, cx| map.remove_creases(ids, cx));
12751    }
12752
12753    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12754        self.display_map
12755            .update(cx, |map, cx| map.snapshot(cx))
12756            .longest_row()
12757    }
12758
12759    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12760        self.display_map
12761            .update(cx, |map, cx| map.snapshot(cx))
12762            .max_point()
12763    }
12764
12765    pub fn text(&self, cx: &App) -> String {
12766        self.buffer.read(cx).read(cx).text()
12767    }
12768
12769    pub fn is_empty(&self, cx: &App) -> bool {
12770        self.buffer.read(cx).read(cx).is_empty()
12771    }
12772
12773    pub fn text_option(&self, cx: &App) -> Option<String> {
12774        let text = self.text(cx);
12775        let text = text.trim();
12776
12777        if text.is_empty() {
12778            return None;
12779        }
12780
12781        Some(text.to_string())
12782    }
12783
12784    pub fn set_text(
12785        &mut self,
12786        text: impl Into<Arc<str>>,
12787        window: &mut Window,
12788        cx: &mut Context<Self>,
12789    ) {
12790        self.transact(window, cx, |this, _, cx| {
12791            this.buffer
12792                .read(cx)
12793                .as_singleton()
12794                .expect("you can only call set_text on editors for singleton buffers")
12795                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12796        });
12797    }
12798
12799    pub fn display_text(&self, cx: &mut App) -> String {
12800        self.display_map
12801            .update(cx, |map, cx| map.snapshot(cx))
12802            .text()
12803    }
12804
12805    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12806        let mut wrap_guides = smallvec::smallvec![];
12807
12808        if self.show_wrap_guides == Some(false) {
12809            return wrap_guides;
12810        }
12811
12812        let settings = self.buffer.read(cx).settings_at(0, cx);
12813        if settings.show_wrap_guides {
12814            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12815                wrap_guides.push((soft_wrap as usize, true));
12816            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12817                wrap_guides.push((soft_wrap as usize, true));
12818            }
12819            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12820        }
12821
12822        wrap_guides
12823    }
12824
12825    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12826        let settings = self.buffer.read(cx).settings_at(0, cx);
12827        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12828        match mode {
12829            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12830                SoftWrap::None
12831            }
12832            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12833            language_settings::SoftWrap::PreferredLineLength => {
12834                SoftWrap::Column(settings.preferred_line_length)
12835            }
12836            language_settings::SoftWrap::Bounded => {
12837                SoftWrap::Bounded(settings.preferred_line_length)
12838            }
12839        }
12840    }
12841
12842    pub fn set_soft_wrap_mode(
12843        &mut self,
12844        mode: language_settings::SoftWrap,
12845
12846        cx: &mut Context<Self>,
12847    ) {
12848        self.soft_wrap_mode_override = Some(mode);
12849        cx.notify();
12850    }
12851
12852    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12853        self.text_style_refinement = Some(style);
12854    }
12855
12856    /// called by the Element so we know what style we were most recently rendered with.
12857    pub(crate) fn set_style(
12858        &mut self,
12859        style: EditorStyle,
12860        window: &mut Window,
12861        cx: &mut Context<Self>,
12862    ) {
12863        let rem_size = window.rem_size();
12864        self.display_map.update(cx, |map, cx| {
12865            map.set_font(
12866                style.text.font(),
12867                style.text.font_size.to_pixels(rem_size),
12868                cx,
12869            )
12870        });
12871        self.style = Some(style);
12872    }
12873
12874    pub fn style(&self) -> Option<&EditorStyle> {
12875        self.style.as_ref()
12876    }
12877
12878    // Called by the element. This method is not designed to be called outside of the editor
12879    // element's layout code because it does not notify when rewrapping is computed synchronously.
12880    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12881        self.display_map
12882            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12883    }
12884
12885    pub fn set_soft_wrap(&mut self) {
12886        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12887    }
12888
12889    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12890        if self.soft_wrap_mode_override.is_some() {
12891            self.soft_wrap_mode_override.take();
12892        } else {
12893            let soft_wrap = match self.soft_wrap_mode(cx) {
12894                SoftWrap::GitDiff => return,
12895                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12896                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12897                    language_settings::SoftWrap::None
12898                }
12899            };
12900            self.soft_wrap_mode_override = Some(soft_wrap);
12901        }
12902        cx.notify();
12903    }
12904
12905    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12906        let Some(workspace) = self.workspace() else {
12907            return;
12908        };
12909        let fs = workspace.read(cx).app_state().fs.clone();
12910        let current_show = TabBarSettings::get_global(cx).show;
12911        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12912            setting.show = Some(!current_show);
12913        });
12914    }
12915
12916    pub fn toggle_indent_guides(
12917        &mut self,
12918        _: &ToggleIndentGuides,
12919        _: &mut Window,
12920        cx: &mut Context<Self>,
12921    ) {
12922        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12923            self.buffer
12924                .read(cx)
12925                .settings_at(0, cx)
12926                .indent_guides
12927                .enabled
12928        });
12929        self.show_indent_guides = Some(!currently_enabled);
12930        cx.notify();
12931    }
12932
12933    fn should_show_indent_guides(&self) -> Option<bool> {
12934        self.show_indent_guides
12935    }
12936
12937    pub fn toggle_line_numbers(
12938        &mut self,
12939        _: &ToggleLineNumbers,
12940        _: &mut Window,
12941        cx: &mut Context<Self>,
12942    ) {
12943        let mut editor_settings = EditorSettings::get_global(cx).clone();
12944        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12945        EditorSettings::override_global(editor_settings, cx);
12946    }
12947
12948    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12949        self.use_relative_line_numbers
12950            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12951    }
12952
12953    pub fn toggle_relative_line_numbers(
12954        &mut self,
12955        _: &ToggleRelativeLineNumbers,
12956        _: &mut Window,
12957        cx: &mut Context<Self>,
12958    ) {
12959        let is_relative = self.should_use_relative_line_numbers(cx);
12960        self.set_relative_line_number(Some(!is_relative), cx)
12961    }
12962
12963    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12964        self.use_relative_line_numbers = is_relative;
12965        cx.notify();
12966    }
12967
12968    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12969        self.show_gutter = show_gutter;
12970        cx.notify();
12971    }
12972
12973    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12974        self.show_scrollbars = show_scrollbars;
12975        cx.notify();
12976    }
12977
12978    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12979        self.show_line_numbers = Some(show_line_numbers);
12980        cx.notify();
12981    }
12982
12983    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12984        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12985        cx.notify();
12986    }
12987
12988    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12989        self.show_code_actions = Some(show_code_actions);
12990        cx.notify();
12991    }
12992
12993    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12994        self.show_runnables = Some(show_runnables);
12995        cx.notify();
12996    }
12997
12998    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12999        if self.display_map.read(cx).masked != masked {
13000            self.display_map.update(cx, |map, _| map.masked = masked);
13001        }
13002        cx.notify()
13003    }
13004
13005    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13006        self.show_wrap_guides = Some(show_wrap_guides);
13007        cx.notify();
13008    }
13009
13010    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13011        self.show_indent_guides = Some(show_indent_guides);
13012        cx.notify();
13013    }
13014
13015    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13016        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13017            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13018                if let Some(dir) = file.abs_path(cx).parent() {
13019                    return Some(dir.to_owned());
13020                }
13021            }
13022
13023            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13024                return Some(project_path.path.to_path_buf());
13025            }
13026        }
13027
13028        None
13029    }
13030
13031    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13032        self.active_excerpt(cx)?
13033            .1
13034            .read(cx)
13035            .file()
13036            .and_then(|f| f.as_local())
13037    }
13038
13039    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13040        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13041            let buffer = buffer.read(cx);
13042            if let Some(project_path) = buffer.project_path(cx) {
13043                let project = self.project.as_ref()?.read(cx);
13044                project.absolute_path(&project_path, cx)
13045            } else {
13046                buffer
13047                    .file()
13048                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13049            }
13050        })
13051    }
13052
13053    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13054        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13055            let project_path = buffer.read(cx).project_path(cx)?;
13056            let project = self.project.as_ref()?.read(cx);
13057            let entry = project.entry_for_path(&project_path, cx)?;
13058            let path = entry.path.to_path_buf();
13059            Some(path)
13060        })
13061    }
13062
13063    pub fn reveal_in_finder(
13064        &mut self,
13065        _: &RevealInFileManager,
13066        _window: &mut Window,
13067        cx: &mut Context<Self>,
13068    ) {
13069        if let Some(target) = self.target_file(cx) {
13070            cx.reveal_path(&target.abs_path(cx));
13071        }
13072    }
13073
13074    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13075        if let Some(path) = self.target_file_abs_path(cx) {
13076            if let Some(path) = path.to_str() {
13077                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13078            }
13079        }
13080    }
13081
13082    pub fn copy_relative_path(
13083        &mut self,
13084        _: &CopyRelativePath,
13085        _window: &mut Window,
13086        cx: &mut Context<Self>,
13087    ) {
13088        if let Some(path) = self.target_file_path(cx) {
13089            if let Some(path) = path.to_str() {
13090                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13091            }
13092        }
13093    }
13094
13095    pub fn copy_file_name_without_extension(
13096        &mut self,
13097        _: &CopyFileNameWithoutExtension,
13098        _: &mut Window,
13099        cx: &mut Context<Self>,
13100    ) {
13101        if let Some(file) = self.target_file(cx) {
13102            if let Some(file_stem) = file.path().file_stem() {
13103                if let Some(name) = file_stem.to_str() {
13104                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13105                }
13106            }
13107        }
13108    }
13109
13110    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13111        if let Some(file) = self.target_file(cx) {
13112            if let Some(file_name) = file.path().file_name() {
13113                if let Some(name) = file_name.to_str() {
13114                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13115                }
13116            }
13117        }
13118    }
13119
13120    pub fn toggle_git_blame(
13121        &mut self,
13122        _: &ToggleGitBlame,
13123        window: &mut Window,
13124        cx: &mut Context<Self>,
13125    ) {
13126        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13127
13128        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13129            self.start_git_blame(true, window, cx);
13130        }
13131
13132        cx.notify();
13133    }
13134
13135    pub fn toggle_git_blame_inline(
13136        &mut self,
13137        _: &ToggleGitBlameInline,
13138        window: &mut Window,
13139        cx: &mut Context<Self>,
13140    ) {
13141        self.toggle_git_blame_inline_internal(true, window, cx);
13142        cx.notify();
13143    }
13144
13145    pub fn git_blame_inline_enabled(&self) -> bool {
13146        self.git_blame_inline_enabled
13147    }
13148
13149    pub fn toggle_selection_menu(
13150        &mut self,
13151        _: &ToggleSelectionMenu,
13152        _: &mut Window,
13153        cx: &mut Context<Self>,
13154    ) {
13155        self.show_selection_menu = self
13156            .show_selection_menu
13157            .map(|show_selections_menu| !show_selections_menu)
13158            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13159
13160        cx.notify();
13161    }
13162
13163    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13164        self.show_selection_menu
13165            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13166    }
13167
13168    fn start_git_blame(
13169        &mut self,
13170        user_triggered: bool,
13171        window: &mut Window,
13172        cx: &mut Context<Self>,
13173    ) {
13174        if let Some(project) = self.project.as_ref() {
13175            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13176                return;
13177            };
13178
13179            if buffer.read(cx).file().is_none() {
13180                return;
13181            }
13182
13183            let focused = self.focus_handle(cx).contains_focused(window, cx);
13184
13185            let project = project.clone();
13186            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13187            self.blame_subscription =
13188                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13189            self.blame = Some(blame);
13190        }
13191    }
13192
13193    fn toggle_git_blame_inline_internal(
13194        &mut self,
13195        user_triggered: bool,
13196        window: &mut Window,
13197        cx: &mut Context<Self>,
13198    ) {
13199        if self.git_blame_inline_enabled {
13200            self.git_blame_inline_enabled = false;
13201            self.show_git_blame_inline = false;
13202            self.show_git_blame_inline_delay_task.take();
13203        } else {
13204            self.git_blame_inline_enabled = true;
13205            self.start_git_blame_inline(user_triggered, window, cx);
13206        }
13207
13208        cx.notify();
13209    }
13210
13211    fn start_git_blame_inline(
13212        &mut self,
13213        user_triggered: bool,
13214        window: &mut Window,
13215        cx: &mut Context<Self>,
13216    ) {
13217        self.start_git_blame(user_triggered, window, cx);
13218
13219        if ProjectSettings::get_global(cx)
13220            .git
13221            .inline_blame_delay()
13222            .is_some()
13223        {
13224            self.start_inline_blame_timer(window, cx);
13225        } else {
13226            self.show_git_blame_inline = true
13227        }
13228    }
13229
13230    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13231        self.blame.as_ref()
13232    }
13233
13234    pub fn show_git_blame_gutter(&self) -> bool {
13235        self.show_git_blame_gutter
13236    }
13237
13238    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13239        self.show_git_blame_gutter && self.has_blame_entries(cx)
13240    }
13241
13242    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13243        self.show_git_blame_inline
13244            && self.focus_handle.is_focused(window)
13245            && !self.newest_selection_head_on_empty_line(cx)
13246            && self.has_blame_entries(cx)
13247    }
13248
13249    fn has_blame_entries(&self, cx: &App) -> bool {
13250        self.blame()
13251            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13252    }
13253
13254    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13255        let cursor_anchor = self.selections.newest_anchor().head();
13256
13257        let snapshot = self.buffer.read(cx).snapshot(cx);
13258        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13259
13260        snapshot.line_len(buffer_row) == 0
13261    }
13262
13263    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13264        let buffer_and_selection = maybe!({
13265            let selection = self.selections.newest::<Point>(cx);
13266            let selection_range = selection.range();
13267
13268            let multi_buffer = self.buffer().read(cx);
13269            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13270            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13271
13272            let (buffer, range, _) = if selection.reversed {
13273                buffer_ranges.first()
13274            } else {
13275                buffer_ranges.last()
13276            }?;
13277
13278            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13279                ..text::ToPoint::to_point(&range.end, &buffer).row;
13280            Some((
13281                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13282                selection,
13283            ))
13284        });
13285
13286        let Some((buffer, selection)) = buffer_and_selection else {
13287            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13288        };
13289
13290        let Some(project) = self.project.as_ref() else {
13291            return Task::ready(Err(anyhow!("editor does not have project")));
13292        };
13293
13294        project.update(cx, |project, cx| {
13295            project.get_permalink_to_line(&buffer, selection, cx)
13296        })
13297    }
13298
13299    pub fn copy_permalink_to_line(
13300        &mut self,
13301        _: &CopyPermalinkToLine,
13302        window: &mut Window,
13303        cx: &mut Context<Self>,
13304    ) {
13305        let permalink_task = self.get_permalink_to_line(cx);
13306        let workspace = self.workspace();
13307
13308        cx.spawn_in(window, |_, mut cx| async move {
13309            match permalink_task.await {
13310                Ok(permalink) => {
13311                    cx.update(|_, cx| {
13312                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13313                    })
13314                    .ok();
13315                }
13316                Err(err) => {
13317                    let message = format!("Failed to copy permalink: {err}");
13318
13319                    Err::<(), anyhow::Error>(err).log_err();
13320
13321                    if let Some(workspace) = workspace {
13322                        workspace
13323                            .update_in(&mut cx, |workspace, _, cx| {
13324                                struct CopyPermalinkToLine;
13325
13326                                workspace.show_toast(
13327                                    Toast::new(
13328                                        NotificationId::unique::<CopyPermalinkToLine>(),
13329                                        message,
13330                                    ),
13331                                    cx,
13332                                )
13333                            })
13334                            .ok();
13335                    }
13336                }
13337            }
13338        })
13339        .detach();
13340    }
13341
13342    pub fn copy_file_location(
13343        &mut self,
13344        _: &CopyFileLocation,
13345        _: &mut Window,
13346        cx: &mut Context<Self>,
13347    ) {
13348        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13349        if let Some(file) = self.target_file(cx) {
13350            if let Some(path) = file.path().to_str() {
13351                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13352            }
13353        }
13354    }
13355
13356    pub fn open_permalink_to_line(
13357        &mut self,
13358        _: &OpenPermalinkToLine,
13359        window: &mut Window,
13360        cx: &mut Context<Self>,
13361    ) {
13362        let permalink_task = self.get_permalink_to_line(cx);
13363        let workspace = self.workspace();
13364
13365        cx.spawn_in(window, |_, mut cx| async move {
13366            match permalink_task.await {
13367                Ok(permalink) => {
13368                    cx.update(|_, cx| {
13369                        cx.open_url(permalink.as_ref());
13370                    })
13371                    .ok();
13372                }
13373                Err(err) => {
13374                    let message = format!("Failed to open permalink: {err}");
13375
13376                    Err::<(), anyhow::Error>(err).log_err();
13377
13378                    if let Some(workspace) = workspace {
13379                        workspace
13380                            .update(&mut cx, |workspace, cx| {
13381                                struct OpenPermalinkToLine;
13382
13383                                workspace.show_toast(
13384                                    Toast::new(
13385                                        NotificationId::unique::<OpenPermalinkToLine>(),
13386                                        message,
13387                                    ),
13388                                    cx,
13389                                )
13390                            })
13391                            .ok();
13392                    }
13393                }
13394            }
13395        })
13396        .detach();
13397    }
13398
13399    pub fn insert_uuid_v4(
13400        &mut self,
13401        _: &InsertUuidV4,
13402        window: &mut Window,
13403        cx: &mut Context<Self>,
13404    ) {
13405        self.insert_uuid(UuidVersion::V4, window, cx);
13406    }
13407
13408    pub fn insert_uuid_v7(
13409        &mut self,
13410        _: &InsertUuidV7,
13411        window: &mut Window,
13412        cx: &mut Context<Self>,
13413    ) {
13414        self.insert_uuid(UuidVersion::V7, window, cx);
13415    }
13416
13417    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13418        self.transact(window, cx, |this, window, cx| {
13419            let edits = this
13420                .selections
13421                .all::<Point>(cx)
13422                .into_iter()
13423                .map(|selection| {
13424                    let uuid = match version {
13425                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13426                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13427                    };
13428
13429                    (selection.range(), uuid.to_string())
13430                });
13431            this.edit(edits, cx);
13432            this.refresh_inline_completion(true, false, window, cx);
13433        });
13434    }
13435
13436    pub fn open_selections_in_multibuffer(
13437        &mut self,
13438        _: &OpenSelectionsInMultibuffer,
13439        window: &mut Window,
13440        cx: &mut Context<Self>,
13441    ) {
13442        let multibuffer = self.buffer.read(cx);
13443
13444        let Some(buffer) = multibuffer.as_singleton() else {
13445            return;
13446        };
13447
13448        let Some(workspace) = self.workspace() else {
13449            return;
13450        };
13451
13452        let locations = self
13453            .selections
13454            .disjoint_anchors()
13455            .iter()
13456            .map(|range| Location {
13457                buffer: buffer.clone(),
13458                range: range.start.text_anchor..range.end.text_anchor,
13459            })
13460            .collect::<Vec<_>>();
13461
13462        let title = multibuffer.title(cx).to_string();
13463
13464        cx.spawn_in(window, |_, mut cx| async move {
13465            workspace.update_in(&mut cx, |workspace, window, cx| {
13466                Self::open_locations_in_multibuffer(
13467                    workspace,
13468                    locations,
13469                    format!("Selections for '{title}'"),
13470                    false,
13471                    MultibufferSelectionMode::All,
13472                    window,
13473                    cx,
13474                );
13475            })
13476        })
13477        .detach();
13478    }
13479
13480    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13481    /// last highlight added will be used.
13482    ///
13483    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13484    pub fn highlight_rows<T: 'static>(
13485        &mut self,
13486        range: Range<Anchor>,
13487        color: Hsla,
13488        should_autoscroll: bool,
13489        cx: &mut Context<Self>,
13490    ) {
13491        let snapshot = self.buffer().read(cx).snapshot(cx);
13492        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13493        let ix = row_highlights.binary_search_by(|highlight| {
13494            Ordering::Equal
13495                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13496                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13497        });
13498
13499        if let Err(mut ix) = ix {
13500            let index = post_inc(&mut self.highlight_order);
13501
13502            // If this range intersects with the preceding highlight, then merge it with
13503            // the preceding highlight. Otherwise insert a new highlight.
13504            let mut merged = false;
13505            if ix > 0 {
13506                let prev_highlight = &mut row_highlights[ix - 1];
13507                if prev_highlight
13508                    .range
13509                    .end
13510                    .cmp(&range.start, &snapshot)
13511                    .is_ge()
13512                {
13513                    ix -= 1;
13514                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13515                        prev_highlight.range.end = range.end;
13516                    }
13517                    merged = true;
13518                    prev_highlight.index = index;
13519                    prev_highlight.color = color;
13520                    prev_highlight.should_autoscroll = should_autoscroll;
13521                }
13522            }
13523
13524            if !merged {
13525                row_highlights.insert(
13526                    ix,
13527                    RowHighlight {
13528                        range: range.clone(),
13529                        index,
13530                        color,
13531                        should_autoscroll,
13532                    },
13533                );
13534            }
13535
13536            // If any of the following highlights intersect with this one, merge them.
13537            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13538                let highlight = &row_highlights[ix];
13539                if next_highlight
13540                    .range
13541                    .start
13542                    .cmp(&highlight.range.end, &snapshot)
13543                    .is_le()
13544                {
13545                    if next_highlight
13546                        .range
13547                        .end
13548                        .cmp(&highlight.range.end, &snapshot)
13549                        .is_gt()
13550                    {
13551                        row_highlights[ix].range.end = next_highlight.range.end;
13552                    }
13553                    row_highlights.remove(ix + 1);
13554                } else {
13555                    break;
13556                }
13557            }
13558        }
13559    }
13560
13561    /// Remove any highlighted row ranges of the given type that intersect the
13562    /// given ranges.
13563    pub fn remove_highlighted_rows<T: 'static>(
13564        &mut self,
13565        ranges_to_remove: Vec<Range<Anchor>>,
13566        cx: &mut Context<Self>,
13567    ) {
13568        let snapshot = self.buffer().read(cx).snapshot(cx);
13569        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13570        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13571        row_highlights.retain(|highlight| {
13572            while let Some(range_to_remove) = ranges_to_remove.peek() {
13573                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13574                    Ordering::Less | Ordering::Equal => {
13575                        ranges_to_remove.next();
13576                    }
13577                    Ordering::Greater => {
13578                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13579                            Ordering::Less | Ordering::Equal => {
13580                                return false;
13581                            }
13582                            Ordering::Greater => break,
13583                        }
13584                    }
13585                }
13586            }
13587
13588            true
13589        })
13590    }
13591
13592    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13593    pub fn clear_row_highlights<T: 'static>(&mut self) {
13594        self.highlighted_rows.remove(&TypeId::of::<T>());
13595    }
13596
13597    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13598    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13599        self.highlighted_rows
13600            .get(&TypeId::of::<T>())
13601            .map_or(&[] as &[_], |vec| vec.as_slice())
13602            .iter()
13603            .map(|highlight| (highlight.range.clone(), highlight.color))
13604    }
13605
13606    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13607    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13608    /// Allows to ignore certain kinds of highlights.
13609    pub fn highlighted_display_rows(
13610        &self,
13611        window: &mut Window,
13612        cx: &mut App,
13613    ) -> BTreeMap<DisplayRow, Background> {
13614        let snapshot = self.snapshot(window, cx);
13615        let mut used_highlight_orders = HashMap::default();
13616        self.highlighted_rows
13617            .iter()
13618            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13619            .fold(
13620                BTreeMap::<DisplayRow, Background>::new(),
13621                |mut unique_rows, highlight| {
13622                    let start = highlight.range.start.to_display_point(&snapshot);
13623                    let end = highlight.range.end.to_display_point(&snapshot);
13624                    let start_row = start.row().0;
13625                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13626                        && end.column() == 0
13627                    {
13628                        end.row().0.saturating_sub(1)
13629                    } else {
13630                        end.row().0
13631                    };
13632                    for row in start_row..=end_row {
13633                        let used_index =
13634                            used_highlight_orders.entry(row).or_insert(highlight.index);
13635                        if highlight.index >= *used_index {
13636                            *used_index = highlight.index;
13637                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13638                        }
13639                    }
13640                    unique_rows
13641                },
13642            )
13643    }
13644
13645    pub fn highlighted_display_row_for_autoscroll(
13646        &self,
13647        snapshot: &DisplaySnapshot,
13648    ) -> Option<DisplayRow> {
13649        self.highlighted_rows
13650            .values()
13651            .flat_map(|highlighted_rows| highlighted_rows.iter())
13652            .filter_map(|highlight| {
13653                if highlight.should_autoscroll {
13654                    Some(highlight.range.start.to_display_point(snapshot).row())
13655                } else {
13656                    None
13657                }
13658            })
13659            .min()
13660    }
13661
13662    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13663        self.highlight_background::<SearchWithinRange>(
13664            ranges,
13665            |colors| colors.editor_document_highlight_read_background,
13666            cx,
13667        )
13668    }
13669
13670    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13671        self.breadcrumb_header = Some(new_header);
13672    }
13673
13674    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13675        self.clear_background_highlights::<SearchWithinRange>(cx);
13676    }
13677
13678    pub fn highlight_background<T: 'static>(
13679        &mut self,
13680        ranges: &[Range<Anchor>],
13681        color_fetcher: fn(&ThemeColors) -> Hsla,
13682        cx: &mut Context<Self>,
13683    ) {
13684        self.background_highlights
13685            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13686        self.scrollbar_marker_state.dirty = true;
13687        cx.notify();
13688    }
13689
13690    pub fn clear_background_highlights<T: 'static>(
13691        &mut self,
13692        cx: &mut Context<Self>,
13693    ) -> Option<BackgroundHighlight> {
13694        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13695        if !text_highlights.1.is_empty() {
13696            self.scrollbar_marker_state.dirty = true;
13697            cx.notify();
13698        }
13699        Some(text_highlights)
13700    }
13701
13702    pub fn highlight_gutter<T: 'static>(
13703        &mut self,
13704        ranges: &[Range<Anchor>],
13705        color_fetcher: fn(&App) -> Hsla,
13706        cx: &mut Context<Self>,
13707    ) {
13708        self.gutter_highlights
13709            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13710        cx.notify();
13711    }
13712
13713    pub fn clear_gutter_highlights<T: 'static>(
13714        &mut self,
13715        cx: &mut Context<Self>,
13716    ) -> Option<GutterHighlight> {
13717        cx.notify();
13718        self.gutter_highlights.remove(&TypeId::of::<T>())
13719    }
13720
13721    #[cfg(feature = "test-support")]
13722    pub fn all_text_background_highlights(
13723        &self,
13724        window: &mut Window,
13725        cx: &mut Context<Self>,
13726    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13727        let snapshot = self.snapshot(window, cx);
13728        let buffer = &snapshot.buffer_snapshot;
13729        let start = buffer.anchor_before(0);
13730        let end = buffer.anchor_after(buffer.len());
13731        let theme = cx.theme().colors();
13732        self.background_highlights_in_range(start..end, &snapshot, theme)
13733    }
13734
13735    #[cfg(feature = "test-support")]
13736    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13737        let snapshot = self.buffer().read(cx).snapshot(cx);
13738
13739        let highlights = self
13740            .background_highlights
13741            .get(&TypeId::of::<items::BufferSearchHighlights>());
13742
13743        if let Some((_color, ranges)) = highlights {
13744            ranges
13745                .iter()
13746                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13747                .collect_vec()
13748        } else {
13749            vec![]
13750        }
13751    }
13752
13753    fn document_highlights_for_position<'a>(
13754        &'a self,
13755        position: Anchor,
13756        buffer: &'a MultiBufferSnapshot,
13757    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13758        let read_highlights = self
13759            .background_highlights
13760            .get(&TypeId::of::<DocumentHighlightRead>())
13761            .map(|h| &h.1);
13762        let write_highlights = self
13763            .background_highlights
13764            .get(&TypeId::of::<DocumentHighlightWrite>())
13765            .map(|h| &h.1);
13766        let left_position = position.bias_left(buffer);
13767        let right_position = position.bias_right(buffer);
13768        read_highlights
13769            .into_iter()
13770            .chain(write_highlights)
13771            .flat_map(move |ranges| {
13772                let start_ix = match ranges.binary_search_by(|probe| {
13773                    let cmp = probe.end.cmp(&left_position, buffer);
13774                    if cmp.is_ge() {
13775                        Ordering::Greater
13776                    } else {
13777                        Ordering::Less
13778                    }
13779                }) {
13780                    Ok(i) | Err(i) => i,
13781                };
13782
13783                ranges[start_ix..]
13784                    .iter()
13785                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13786            })
13787    }
13788
13789    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13790        self.background_highlights
13791            .get(&TypeId::of::<T>())
13792            .map_or(false, |(_, highlights)| !highlights.is_empty())
13793    }
13794
13795    pub fn background_highlights_in_range(
13796        &self,
13797        search_range: Range<Anchor>,
13798        display_snapshot: &DisplaySnapshot,
13799        theme: &ThemeColors,
13800    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13801        let mut results = Vec::new();
13802        for (color_fetcher, ranges) in self.background_highlights.values() {
13803            let color = color_fetcher(theme);
13804            let start_ix = match ranges.binary_search_by(|probe| {
13805                let cmp = probe
13806                    .end
13807                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13808                if cmp.is_gt() {
13809                    Ordering::Greater
13810                } else {
13811                    Ordering::Less
13812                }
13813            }) {
13814                Ok(i) | Err(i) => i,
13815            };
13816            for range in &ranges[start_ix..] {
13817                if range
13818                    .start
13819                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13820                    .is_ge()
13821                {
13822                    break;
13823                }
13824
13825                let start = range.start.to_display_point(display_snapshot);
13826                let end = range.end.to_display_point(display_snapshot);
13827                results.push((start..end, color))
13828            }
13829        }
13830        results
13831    }
13832
13833    pub fn background_highlight_row_ranges<T: 'static>(
13834        &self,
13835        search_range: Range<Anchor>,
13836        display_snapshot: &DisplaySnapshot,
13837        count: usize,
13838    ) -> Vec<RangeInclusive<DisplayPoint>> {
13839        let mut results = Vec::new();
13840        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13841            return vec![];
13842        };
13843
13844        let start_ix = match ranges.binary_search_by(|probe| {
13845            let cmp = probe
13846                .end
13847                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13848            if cmp.is_gt() {
13849                Ordering::Greater
13850            } else {
13851                Ordering::Less
13852            }
13853        }) {
13854            Ok(i) | Err(i) => i,
13855        };
13856        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13857            if let (Some(start_display), Some(end_display)) = (start, end) {
13858                results.push(
13859                    start_display.to_display_point(display_snapshot)
13860                        ..=end_display.to_display_point(display_snapshot),
13861                );
13862            }
13863        };
13864        let mut start_row: Option<Point> = None;
13865        let mut end_row: Option<Point> = None;
13866        if ranges.len() > count {
13867            return Vec::new();
13868        }
13869        for range in &ranges[start_ix..] {
13870            if range
13871                .start
13872                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13873                .is_ge()
13874            {
13875                break;
13876            }
13877            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13878            if let Some(current_row) = &end_row {
13879                if end.row == current_row.row {
13880                    continue;
13881                }
13882            }
13883            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13884            if start_row.is_none() {
13885                assert_eq!(end_row, None);
13886                start_row = Some(start);
13887                end_row = Some(end);
13888                continue;
13889            }
13890            if let Some(current_end) = end_row.as_mut() {
13891                if start.row > current_end.row + 1 {
13892                    push_region(start_row, end_row);
13893                    start_row = Some(start);
13894                    end_row = Some(end);
13895                } else {
13896                    // Merge two hunks.
13897                    *current_end = end;
13898                }
13899            } else {
13900                unreachable!();
13901            }
13902        }
13903        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13904        push_region(start_row, end_row);
13905        results
13906    }
13907
13908    pub fn gutter_highlights_in_range(
13909        &self,
13910        search_range: Range<Anchor>,
13911        display_snapshot: &DisplaySnapshot,
13912        cx: &App,
13913    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13914        let mut results = Vec::new();
13915        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13916            let color = color_fetcher(cx);
13917            let start_ix = match ranges.binary_search_by(|probe| {
13918                let cmp = probe
13919                    .end
13920                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13921                if cmp.is_gt() {
13922                    Ordering::Greater
13923                } else {
13924                    Ordering::Less
13925                }
13926            }) {
13927                Ok(i) | Err(i) => i,
13928            };
13929            for range in &ranges[start_ix..] {
13930                if range
13931                    .start
13932                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13933                    .is_ge()
13934                {
13935                    break;
13936                }
13937
13938                let start = range.start.to_display_point(display_snapshot);
13939                let end = range.end.to_display_point(display_snapshot);
13940                results.push((start..end, color))
13941            }
13942        }
13943        results
13944    }
13945
13946    /// Get the text ranges corresponding to the redaction query
13947    pub fn redacted_ranges(
13948        &self,
13949        search_range: Range<Anchor>,
13950        display_snapshot: &DisplaySnapshot,
13951        cx: &App,
13952    ) -> Vec<Range<DisplayPoint>> {
13953        display_snapshot
13954            .buffer_snapshot
13955            .redacted_ranges(search_range, |file| {
13956                if let Some(file) = file {
13957                    file.is_private()
13958                        && EditorSettings::get(
13959                            Some(SettingsLocation {
13960                                worktree_id: file.worktree_id(cx),
13961                                path: file.path().as_ref(),
13962                            }),
13963                            cx,
13964                        )
13965                        .redact_private_values
13966                } else {
13967                    false
13968                }
13969            })
13970            .map(|range| {
13971                range.start.to_display_point(display_snapshot)
13972                    ..range.end.to_display_point(display_snapshot)
13973            })
13974            .collect()
13975    }
13976
13977    pub fn highlight_text<T: 'static>(
13978        &mut self,
13979        ranges: Vec<Range<Anchor>>,
13980        style: HighlightStyle,
13981        cx: &mut Context<Self>,
13982    ) {
13983        self.display_map.update(cx, |map, _| {
13984            map.highlight_text(TypeId::of::<T>(), ranges, style)
13985        });
13986        cx.notify();
13987    }
13988
13989    pub(crate) fn highlight_inlays<T: 'static>(
13990        &mut self,
13991        highlights: Vec<InlayHighlight>,
13992        style: HighlightStyle,
13993        cx: &mut Context<Self>,
13994    ) {
13995        self.display_map.update(cx, |map, _| {
13996            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13997        });
13998        cx.notify();
13999    }
14000
14001    pub fn text_highlights<'a, T: 'static>(
14002        &'a self,
14003        cx: &'a App,
14004    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14005        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14006    }
14007
14008    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14009        let cleared = self
14010            .display_map
14011            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14012        if cleared {
14013            cx.notify();
14014        }
14015    }
14016
14017    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14018        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14019            && self.focus_handle.is_focused(window)
14020    }
14021
14022    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14023        self.show_cursor_when_unfocused = is_enabled;
14024        cx.notify();
14025    }
14026
14027    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14028        self.project
14029            .as_ref()
14030            .map(|project| project.read(cx).lsp_store())
14031    }
14032
14033    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14034        cx.notify();
14035    }
14036
14037    fn on_buffer_event(
14038        &mut self,
14039        multibuffer: &Entity<MultiBuffer>,
14040        event: &multi_buffer::Event,
14041        window: &mut Window,
14042        cx: &mut Context<Self>,
14043    ) {
14044        match event {
14045            multi_buffer::Event::Edited {
14046                singleton_buffer_edited,
14047                edited_buffer: buffer_edited,
14048            } => {
14049                self.scrollbar_marker_state.dirty = true;
14050                self.active_indent_guides_state.dirty = true;
14051                self.refresh_active_diagnostics(cx);
14052                self.refresh_code_actions(window, cx);
14053                if self.has_active_inline_completion() {
14054                    self.update_visible_inline_completion(window, cx);
14055                }
14056                if let Some(buffer) = buffer_edited {
14057                    let buffer_id = buffer.read(cx).remote_id();
14058                    if !self.registered_buffers.contains_key(&buffer_id) {
14059                        if let Some(lsp_store) = self.lsp_store(cx) {
14060                            lsp_store.update(cx, |lsp_store, cx| {
14061                                self.registered_buffers.insert(
14062                                    buffer_id,
14063                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14064                                );
14065                            })
14066                        }
14067                    }
14068                }
14069                cx.emit(EditorEvent::BufferEdited);
14070                cx.emit(SearchEvent::MatchesInvalidated);
14071                if *singleton_buffer_edited {
14072                    if let Some(project) = &self.project {
14073                        let project = project.read(cx);
14074                        #[allow(clippy::mutable_key_type)]
14075                        let languages_affected = multibuffer
14076                            .read(cx)
14077                            .all_buffers()
14078                            .into_iter()
14079                            .filter_map(|buffer| {
14080                                let buffer = buffer.read(cx);
14081                                let language = buffer.language()?;
14082                                if project.is_local()
14083                                    && project
14084                                        .language_servers_for_local_buffer(buffer, cx)
14085                                        .count()
14086                                        == 0
14087                                {
14088                                    None
14089                                } else {
14090                                    Some(language)
14091                                }
14092                            })
14093                            .cloned()
14094                            .collect::<HashSet<_>>();
14095                        if !languages_affected.is_empty() {
14096                            self.refresh_inlay_hints(
14097                                InlayHintRefreshReason::BufferEdited(languages_affected),
14098                                cx,
14099                            );
14100                        }
14101                    }
14102                }
14103
14104                let Some(project) = &self.project else { return };
14105                let (telemetry, is_via_ssh) = {
14106                    let project = project.read(cx);
14107                    let telemetry = project.client().telemetry().clone();
14108                    let is_via_ssh = project.is_via_ssh();
14109                    (telemetry, is_via_ssh)
14110                };
14111                refresh_linked_ranges(self, window, cx);
14112                telemetry.log_edit_event("editor", is_via_ssh);
14113            }
14114            multi_buffer::Event::ExcerptsAdded {
14115                buffer,
14116                predecessor,
14117                excerpts,
14118            } => {
14119                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14120                let buffer_id = buffer.read(cx).remote_id();
14121                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14122                    if let Some(project) = &self.project {
14123                        get_uncommitted_diff_for_buffer(
14124                            project,
14125                            [buffer.clone()],
14126                            self.buffer.clone(),
14127                            cx,
14128                        );
14129                    }
14130                }
14131                cx.emit(EditorEvent::ExcerptsAdded {
14132                    buffer: buffer.clone(),
14133                    predecessor: *predecessor,
14134                    excerpts: excerpts.clone(),
14135                });
14136                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14137            }
14138            multi_buffer::Event::ExcerptsRemoved { ids } => {
14139                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14140                let buffer = self.buffer.read(cx);
14141                self.registered_buffers
14142                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14143                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14144            }
14145            multi_buffer::Event::ExcerptsEdited { ids } => {
14146                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14147            }
14148            multi_buffer::Event::ExcerptsExpanded { ids } => {
14149                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14150                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14151            }
14152            multi_buffer::Event::Reparsed(buffer_id) => {
14153                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14154
14155                cx.emit(EditorEvent::Reparsed(*buffer_id));
14156            }
14157            multi_buffer::Event::DiffHunksToggled => {
14158                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14159            }
14160            multi_buffer::Event::LanguageChanged(buffer_id) => {
14161                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14162                cx.emit(EditorEvent::Reparsed(*buffer_id));
14163                cx.notify();
14164            }
14165            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14166            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14167            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14168                cx.emit(EditorEvent::TitleChanged)
14169            }
14170            // multi_buffer::Event::DiffBaseChanged => {
14171            //     self.scrollbar_marker_state.dirty = true;
14172            //     cx.emit(EditorEvent::DiffBaseChanged);
14173            //     cx.notify();
14174            // }
14175            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14176            multi_buffer::Event::DiagnosticsUpdated => {
14177                self.refresh_active_diagnostics(cx);
14178                self.scrollbar_marker_state.dirty = true;
14179                cx.notify();
14180            }
14181            _ => {}
14182        };
14183    }
14184
14185    fn on_display_map_changed(
14186        &mut self,
14187        _: Entity<DisplayMap>,
14188        _: &mut Window,
14189        cx: &mut Context<Self>,
14190    ) {
14191        cx.notify();
14192    }
14193
14194    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14195        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14196        self.refresh_inline_completion(true, false, window, cx);
14197        self.refresh_inlay_hints(
14198            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14199                self.selections.newest_anchor().head(),
14200                &self.buffer.read(cx).snapshot(cx),
14201                cx,
14202            )),
14203            cx,
14204        );
14205
14206        let old_cursor_shape = self.cursor_shape;
14207
14208        {
14209            let editor_settings = EditorSettings::get_global(cx);
14210            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14211            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14212            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14213        }
14214
14215        if old_cursor_shape != self.cursor_shape {
14216            cx.emit(EditorEvent::CursorShapeChanged);
14217        }
14218
14219        let project_settings = ProjectSettings::get_global(cx);
14220        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14221
14222        if self.mode == EditorMode::Full {
14223            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14224            if self.git_blame_inline_enabled != inline_blame_enabled {
14225                self.toggle_git_blame_inline_internal(false, window, cx);
14226            }
14227        }
14228
14229        cx.notify();
14230    }
14231
14232    pub fn set_searchable(&mut self, searchable: bool) {
14233        self.searchable = searchable;
14234    }
14235
14236    pub fn searchable(&self) -> bool {
14237        self.searchable
14238    }
14239
14240    fn open_proposed_changes_editor(
14241        &mut self,
14242        _: &OpenProposedChangesEditor,
14243        window: &mut Window,
14244        cx: &mut Context<Self>,
14245    ) {
14246        let Some(workspace) = self.workspace() else {
14247            cx.propagate();
14248            return;
14249        };
14250
14251        let selections = self.selections.all::<usize>(cx);
14252        let multi_buffer = self.buffer.read(cx);
14253        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14254        let mut new_selections_by_buffer = HashMap::default();
14255        for selection in selections {
14256            for (buffer, range, _) in
14257                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14258            {
14259                let mut range = range.to_point(buffer);
14260                range.start.column = 0;
14261                range.end.column = buffer.line_len(range.end.row);
14262                new_selections_by_buffer
14263                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14264                    .or_insert(Vec::new())
14265                    .push(range)
14266            }
14267        }
14268
14269        let proposed_changes_buffers = new_selections_by_buffer
14270            .into_iter()
14271            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14272            .collect::<Vec<_>>();
14273        let proposed_changes_editor = cx.new(|cx| {
14274            ProposedChangesEditor::new(
14275                "Proposed changes",
14276                proposed_changes_buffers,
14277                self.project.clone(),
14278                window,
14279                cx,
14280            )
14281        });
14282
14283        window.defer(cx, move |window, cx| {
14284            workspace.update(cx, |workspace, cx| {
14285                workspace.active_pane().update(cx, |pane, cx| {
14286                    pane.add_item(
14287                        Box::new(proposed_changes_editor),
14288                        true,
14289                        true,
14290                        None,
14291                        window,
14292                        cx,
14293                    );
14294                });
14295            });
14296        });
14297    }
14298
14299    pub fn open_excerpts_in_split(
14300        &mut self,
14301        _: &OpenExcerptsSplit,
14302        window: &mut Window,
14303        cx: &mut Context<Self>,
14304    ) {
14305        self.open_excerpts_common(None, true, window, cx)
14306    }
14307
14308    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14309        self.open_excerpts_common(None, false, window, cx)
14310    }
14311
14312    fn open_excerpts_common(
14313        &mut self,
14314        jump_data: Option<JumpData>,
14315        split: bool,
14316        window: &mut Window,
14317        cx: &mut Context<Self>,
14318    ) {
14319        let Some(workspace) = self.workspace() else {
14320            cx.propagate();
14321            return;
14322        };
14323
14324        if self.buffer.read(cx).is_singleton() {
14325            cx.propagate();
14326            return;
14327        }
14328
14329        let mut new_selections_by_buffer = HashMap::default();
14330        match &jump_data {
14331            Some(JumpData::MultiBufferPoint {
14332                excerpt_id,
14333                position,
14334                anchor,
14335                line_offset_from_top,
14336            }) => {
14337                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14338                if let Some(buffer) = multi_buffer_snapshot
14339                    .buffer_id_for_excerpt(*excerpt_id)
14340                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14341                {
14342                    let buffer_snapshot = buffer.read(cx).snapshot();
14343                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14344                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14345                    } else {
14346                        buffer_snapshot.clip_point(*position, Bias::Left)
14347                    };
14348                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14349                    new_selections_by_buffer.insert(
14350                        buffer,
14351                        (
14352                            vec![jump_to_offset..jump_to_offset],
14353                            Some(*line_offset_from_top),
14354                        ),
14355                    );
14356                }
14357            }
14358            Some(JumpData::MultiBufferRow {
14359                row,
14360                line_offset_from_top,
14361            }) => {
14362                let point = MultiBufferPoint::new(row.0, 0);
14363                if let Some((buffer, buffer_point, _)) =
14364                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14365                {
14366                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14367                    new_selections_by_buffer
14368                        .entry(buffer)
14369                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14370                        .0
14371                        .push(buffer_offset..buffer_offset)
14372                }
14373            }
14374            None => {
14375                let selections = self.selections.all::<usize>(cx);
14376                let multi_buffer = self.buffer.read(cx);
14377                for selection in selections {
14378                    for (buffer, mut range, _) in multi_buffer
14379                        .snapshot(cx)
14380                        .range_to_buffer_ranges(selection.range())
14381                    {
14382                        // When editing branch buffers, jump to the corresponding location
14383                        // in their base buffer.
14384                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14385                        let buffer = buffer_handle.read(cx);
14386                        if let Some(base_buffer) = buffer.base_buffer() {
14387                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14388                            buffer_handle = base_buffer;
14389                        }
14390
14391                        if selection.reversed {
14392                            mem::swap(&mut range.start, &mut range.end);
14393                        }
14394                        new_selections_by_buffer
14395                            .entry(buffer_handle)
14396                            .or_insert((Vec::new(), None))
14397                            .0
14398                            .push(range)
14399                    }
14400                }
14401            }
14402        }
14403
14404        if new_selections_by_buffer.is_empty() {
14405            return;
14406        }
14407
14408        // We defer the pane interaction because we ourselves are a workspace item
14409        // and activating a new item causes the pane to call a method on us reentrantly,
14410        // which panics if we're on the stack.
14411        window.defer(cx, move |window, cx| {
14412            workspace.update(cx, |workspace, cx| {
14413                let pane = if split {
14414                    workspace.adjacent_pane(window, cx)
14415                } else {
14416                    workspace.active_pane().clone()
14417                };
14418
14419                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14420                    let editor = buffer
14421                        .read(cx)
14422                        .file()
14423                        .is_none()
14424                        .then(|| {
14425                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14426                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14427                            // Instead, we try to activate the existing editor in the pane first.
14428                            let (editor, pane_item_index) =
14429                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14430                                    let editor = item.downcast::<Editor>()?;
14431                                    let singleton_buffer =
14432                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14433                                    if singleton_buffer == buffer {
14434                                        Some((editor, i))
14435                                    } else {
14436                                        None
14437                                    }
14438                                })?;
14439                            pane.update(cx, |pane, cx| {
14440                                pane.activate_item(pane_item_index, true, true, window, cx)
14441                            });
14442                            Some(editor)
14443                        })
14444                        .flatten()
14445                        .unwrap_or_else(|| {
14446                            workspace.open_project_item::<Self>(
14447                                pane.clone(),
14448                                buffer,
14449                                true,
14450                                true,
14451                                window,
14452                                cx,
14453                            )
14454                        });
14455
14456                    editor.update(cx, |editor, cx| {
14457                        let autoscroll = match scroll_offset {
14458                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14459                            None => Autoscroll::newest(),
14460                        };
14461                        let nav_history = editor.nav_history.take();
14462                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14463                            s.select_ranges(ranges);
14464                        });
14465                        editor.nav_history = nav_history;
14466                    });
14467                }
14468            })
14469        });
14470    }
14471
14472    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14473        let snapshot = self.buffer.read(cx).read(cx);
14474        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14475        Some(
14476            ranges
14477                .iter()
14478                .map(move |range| {
14479                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14480                })
14481                .collect(),
14482        )
14483    }
14484
14485    fn selection_replacement_ranges(
14486        &self,
14487        range: Range<OffsetUtf16>,
14488        cx: &mut App,
14489    ) -> Vec<Range<OffsetUtf16>> {
14490        let selections = self.selections.all::<OffsetUtf16>(cx);
14491        let newest_selection = selections
14492            .iter()
14493            .max_by_key(|selection| selection.id)
14494            .unwrap();
14495        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14496        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14497        let snapshot = self.buffer.read(cx).read(cx);
14498        selections
14499            .into_iter()
14500            .map(|mut selection| {
14501                selection.start.0 =
14502                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14503                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14504                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14505                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14506            })
14507            .collect()
14508    }
14509
14510    fn report_editor_event(
14511        &self,
14512        event_type: &'static str,
14513        file_extension: Option<String>,
14514        cx: &App,
14515    ) {
14516        if cfg!(any(test, feature = "test-support")) {
14517            return;
14518        }
14519
14520        let Some(project) = &self.project else { return };
14521
14522        // If None, we are in a file without an extension
14523        let file = self
14524            .buffer
14525            .read(cx)
14526            .as_singleton()
14527            .and_then(|b| b.read(cx).file());
14528        let file_extension = file_extension.or(file
14529            .as_ref()
14530            .and_then(|file| Path::new(file.file_name(cx)).extension())
14531            .and_then(|e| e.to_str())
14532            .map(|a| a.to_string()));
14533
14534        let vim_mode = cx
14535            .global::<SettingsStore>()
14536            .raw_user_settings()
14537            .get("vim_mode")
14538            == Some(&serde_json::Value::Bool(true));
14539
14540        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14541        let copilot_enabled = edit_predictions_provider
14542            == language::language_settings::EditPredictionProvider::Copilot;
14543        let copilot_enabled_for_language = self
14544            .buffer
14545            .read(cx)
14546            .settings_at(0, cx)
14547            .show_edit_predictions;
14548
14549        let project = project.read(cx);
14550        telemetry::event!(
14551            event_type,
14552            file_extension,
14553            vim_mode,
14554            copilot_enabled,
14555            copilot_enabled_for_language,
14556            edit_predictions_provider,
14557            is_via_ssh = project.is_via_ssh(),
14558        );
14559    }
14560
14561    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14562    /// with each line being an array of {text, highlight} objects.
14563    fn copy_highlight_json(
14564        &mut self,
14565        _: &CopyHighlightJson,
14566        window: &mut Window,
14567        cx: &mut Context<Self>,
14568    ) {
14569        #[derive(Serialize)]
14570        struct Chunk<'a> {
14571            text: String,
14572            highlight: Option<&'a str>,
14573        }
14574
14575        let snapshot = self.buffer.read(cx).snapshot(cx);
14576        let range = self
14577            .selected_text_range(false, window, cx)
14578            .and_then(|selection| {
14579                if selection.range.is_empty() {
14580                    None
14581                } else {
14582                    Some(selection.range)
14583                }
14584            })
14585            .unwrap_or_else(|| 0..snapshot.len());
14586
14587        let chunks = snapshot.chunks(range, true);
14588        let mut lines = Vec::new();
14589        let mut line: VecDeque<Chunk> = VecDeque::new();
14590
14591        let Some(style) = self.style.as_ref() else {
14592            return;
14593        };
14594
14595        for chunk in chunks {
14596            let highlight = chunk
14597                .syntax_highlight_id
14598                .and_then(|id| id.name(&style.syntax));
14599            let mut chunk_lines = chunk.text.split('\n').peekable();
14600            while let Some(text) = chunk_lines.next() {
14601                let mut merged_with_last_token = false;
14602                if let Some(last_token) = line.back_mut() {
14603                    if last_token.highlight == highlight {
14604                        last_token.text.push_str(text);
14605                        merged_with_last_token = true;
14606                    }
14607                }
14608
14609                if !merged_with_last_token {
14610                    line.push_back(Chunk {
14611                        text: text.into(),
14612                        highlight,
14613                    });
14614                }
14615
14616                if chunk_lines.peek().is_some() {
14617                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14618                        line.pop_front();
14619                    }
14620                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14621                        line.pop_back();
14622                    }
14623
14624                    lines.push(mem::take(&mut line));
14625                }
14626            }
14627        }
14628
14629        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14630            return;
14631        };
14632        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14633    }
14634
14635    pub fn open_context_menu(
14636        &mut self,
14637        _: &OpenContextMenu,
14638        window: &mut Window,
14639        cx: &mut Context<Self>,
14640    ) {
14641        self.request_autoscroll(Autoscroll::newest(), cx);
14642        let position = self.selections.newest_display(cx).start;
14643        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14644    }
14645
14646    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14647        &self.inlay_hint_cache
14648    }
14649
14650    pub fn replay_insert_event(
14651        &mut self,
14652        text: &str,
14653        relative_utf16_range: Option<Range<isize>>,
14654        window: &mut Window,
14655        cx: &mut Context<Self>,
14656    ) {
14657        if !self.input_enabled {
14658            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14659            return;
14660        }
14661        if let Some(relative_utf16_range) = relative_utf16_range {
14662            let selections = self.selections.all::<OffsetUtf16>(cx);
14663            self.change_selections(None, window, cx, |s| {
14664                let new_ranges = selections.into_iter().map(|range| {
14665                    let start = OffsetUtf16(
14666                        range
14667                            .head()
14668                            .0
14669                            .saturating_add_signed(relative_utf16_range.start),
14670                    );
14671                    let end = OffsetUtf16(
14672                        range
14673                            .head()
14674                            .0
14675                            .saturating_add_signed(relative_utf16_range.end),
14676                    );
14677                    start..end
14678                });
14679                s.select_ranges(new_ranges);
14680            });
14681        }
14682
14683        self.handle_input(text, window, cx);
14684    }
14685
14686    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14687        let Some(provider) = self.semantics_provider.as_ref() else {
14688            return false;
14689        };
14690
14691        let mut supports = false;
14692        self.buffer().read(cx).for_each_buffer(|buffer| {
14693            supports |= provider.supports_inlay_hints(buffer, cx);
14694        });
14695        supports
14696    }
14697
14698    pub fn is_focused(&self, window: &Window) -> bool {
14699        self.focus_handle.is_focused(window)
14700    }
14701
14702    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14703        cx.emit(EditorEvent::Focused);
14704
14705        if let Some(descendant) = self
14706            .last_focused_descendant
14707            .take()
14708            .and_then(|descendant| descendant.upgrade())
14709        {
14710            window.focus(&descendant);
14711        } else {
14712            if let Some(blame) = self.blame.as_ref() {
14713                blame.update(cx, GitBlame::focus)
14714            }
14715
14716            self.blink_manager.update(cx, BlinkManager::enable);
14717            self.show_cursor_names(window, cx);
14718            self.buffer.update(cx, |buffer, cx| {
14719                buffer.finalize_last_transaction(cx);
14720                if self.leader_peer_id.is_none() {
14721                    buffer.set_active_selections(
14722                        &self.selections.disjoint_anchors(),
14723                        self.selections.line_mode,
14724                        self.cursor_shape,
14725                        cx,
14726                    );
14727                }
14728            });
14729        }
14730    }
14731
14732    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14733        cx.emit(EditorEvent::FocusedIn)
14734    }
14735
14736    fn handle_focus_out(
14737        &mut self,
14738        event: FocusOutEvent,
14739        _window: &mut Window,
14740        _cx: &mut Context<Self>,
14741    ) {
14742        if event.blurred != self.focus_handle {
14743            self.last_focused_descendant = Some(event.blurred);
14744        }
14745    }
14746
14747    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14748        self.blink_manager.update(cx, BlinkManager::disable);
14749        self.buffer
14750            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14751
14752        if let Some(blame) = self.blame.as_ref() {
14753            blame.update(cx, GitBlame::blur)
14754        }
14755        if !self.hover_state.focused(window, cx) {
14756            hide_hover(self, cx);
14757        }
14758
14759        self.hide_context_menu(window, cx);
14760        self.discard_inline_completion(false, cx);
14761        cx.emit(EditorEvent::Blurred);
14762        cx.notify();
14763    }
14764
14765    pub fn register_action<A: Action>(
14766        &mut self,
14767        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14768    ) -> Subscription {
14769        let id = self.next_editor_action_id.post_inc();
14770        let listener = Arc::new(listener);
14771        self.editor_actions.borrow_mut().insert(
14772            id,
14773            Box::new(move |window, _| {
14774                let listener = listener.clone();
14775                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14776                    let action = action.downcast_ref().unwrap();
14777                    if phase == DispatchPhase::Bubble {
14778                        listener(action, window, cx)
14779                    }
14780                })
14781            }),
14782        );
14783
14784        let editor_actions = self.editor_actions.clone();
14785        Subscription::new(move || {
14786            editor_actions.borrow_mut().remove(&id);
14787        })
14788    }
14789
14790    pub fn file_header_size(&self) -> u32 {
14791        FILE_HEADER_HEIGHT
14792    }
14793
14794    pub fn revert(
14795        &mut self,
14796        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14797        window: &mut Window,
14798        cx: &mut Context<Self>,
14799    ) {
14800        self.buffer().update(cx, |multi_buffer, cx| {
14801            for (buffer_id, changes) in revert_changes {
14802                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14803                    buffer.update(cx, |buffer, cx| {
14804                        buffer.edit(
14805                            changes.into_iter().map(|(range, text)| {
14806                                (range, text.to_string().map(Arc::<str>::from))
14807                            }),
14808                            None,
14809                            cx,
14810                        );
14811                    });
14812                }
14813            }
14814        });
14815        self.change_selections(None, window, cx, |selections| selections.refresh());
14816    }
14817
14818    pub fn to_pixel_point(
14819        &self,
14820        source: multi_buffer::Anchor,
14821        editor_snapshot: &EditorSnapshot,
14822        window: &mut Window,
14823    ) -> Option<gpui::Point<Pixels>> {
14824        let source_point = source.to_display_point(editor_snapshot);
14825        self.display_to_pixel_point(source_point, editor_snapshot, window)
14826    }
14827
14828    pub fn display_to_pixel_point(
14829        &self,
14830        source: DisplayPoint,
14831        editor_snapshot: &EditorSnapshot,
14832        window: &mut Window,
14833    ) -> Option<gpui::Point<Pixels>> {
14834        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14835        let text_layout_details = self.text_layout_details(window);
14836        let scroll_top = text_layout_details
14837            .scroll_anchor
14838            .scroll_position(editor_snapshot)
14839            .y;
14840
14841        if source.row().as_f32() < scroll_top.floor() {
14842            return None;
14843        }
14844        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14845        let source_y = line_height * (source.row().as_f32() - scroll_top);
14846        Some(gpui::Point::new(source_x, source_y))
14847    }
14848
14849    pub fn has_visible_completions_menu(&self) -> bool {
14850        !self.edit_prediction_preview_is_active()
14851            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14852                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14853            })
14854    }
14855
14856    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14857        self.addons
14858            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14859    }
14860
14861    pub fn unregister_addon<T: Addon>(&mut self) {
14862        self.addons.remove(&std::any::TypeId::of::<T>());
14863    }
14864
14865    pub fn addon<T: Addon>(&self) -> Option<&T> {
14866        let type_id = std::any::TypeId::of::<T>();
14867        self.addons
14868            .get(&type_id)
14869            .and_then(|item| item.to_any().downcast_ref::<T>())
14870    }
14871
14872    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14873        let text_layout_details = self.text_layout_details(window);
14874        let style = &text_layout_details.editor_style;
14875        let font_id = window.text_system().resolve_font(&style.text.font());
14876        let font_size = style.text.font_size.to_pixels(window.rem_size());
14877        let line_height = style.text.line_height_in_pixels(window.rem_size());
14878        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14879
14880        gpui::Size::new(em_width, line_height)
14881    }
14882}
14883
14884fn get_uncommitted_diff_for_buffer(
14885    project: &Entity<Project>,
14886    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14887    buffer: Entity<MultiBuffer>,
14888    cx: &mut App,
14889) {
14890    let mut tasks = Vec::new();
14891    project.update(cx, |project, cx| {
14892        for buffer in buffers {
14893            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14894        }
14895    });
14896    cx.spawn(|mut cx| async move {
14897        let diffs = futures::future::join_all(tasks).await;
14898        buffer
14899            .update(&mut cx, |buffer, cx| {
14900                for diff in diffs.into_iter().flatten() {
14901                    buffer.add_diff(diff, cx);
14902                }
14903            })
14904            .ok();
14905    })
14906    .detach();
14907}
14908
14909fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14910    let tab_size = tab_size.get() as usize;
14911    let mut width = offset;
14912
14913    for ch in text.chars() {
14914        width += if ch == '\t' {
14915            tab_size - (width % tab_size)
14916        } else {
14917            1
14918        };
14919    }
14920
14921    width - offset
14922}
14923
14924#[cfg(test)]
14925mod tests {
14926    use super::*;
14927
14928    #[test]
14929    fn test_string_size_with_expanded_tabs() {
14930        let nz = |val| NonZeroU32::new(val).unwrap();
14931        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14932        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14933        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14934        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14935        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14936        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14937        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14938        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14939    }
14940}
14941
14942/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14943struct WordBreakingTokenizer<'a> {
14944    input: &'a str,
14945}
14946
14947impl<'a> WordBreakingTokenizer<'a> {
14948    fn new(input: &'a str) -> Self {
14949        Self { input }
14950    }
14951}
14952
14953fn is_char_ideographic(ch: char) -> bool {
14954    use unicode_script::Script::*;
14955    use unicode_script::UnicodeScript;
14956    matches!(ch.script(), Han | Tangut | Yi)
14957}
14958
14959fn is_grapheme_ideographic(text: &str) -> bool {
14960    text.chars().any(is_char_ideographic)
14961}
14962
14963fn is_grapheme_whitespace(text: &str) -> bool {
14964    text.chars().any(|x| x.is_whitespace())
14965}
14966
14967fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14968    text.chars().next().map_or(false, |ch| {
14969        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14970    })
14971}
14972
14973#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14974struct WordBreakToken<'a> {
14975    token: &'a str,
14976    grapheme_len: usize,
14977    is_whitespace: bool,
14978}
14979
14980impl<'a> Iterator for WordBreakingTokenizer<'a> {
14981    /// Yields a span, the count of graphemes in the token, and whether it was
14982    /// whitespace. Note that it also breaks at word boundaries.
14983    type Item = WordBreakToken<'a>;
14984
14985    fn next(&mut self) -> Option<Self::Item> {
14986        use unicode_segmentation::UnicodeSegmentation;
14987        if self.input.is_empty() {
14988            return None;
14989        }
14990
14991        let mut iter = self.input.graphemes(true).peekable();
14992        let mut offset = 0;
14993        let mut graphemes = 0;
14994        if let Some(first_grapheme) = iter.next() {
14995            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14996            offset += first_grapheme.len();
14997            graphemes += 1;
14998            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14999                if let Some(grapheme) = iter.peek().copied() {
15000                    if should_stay_with_preceding_ideograph(grapheme) {
15001                        offset += grapheme.len();
15002                        graphemes += 1;
15003                    }
15004                }
15005            } else {
15006                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15007                let mut next_word_bound = words.peek().copied();
15008                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15009                    next_word_bound = words.next();
15010                }
15011                while let Some(grapheme) = iter.peek().copied() {
15012                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15013                        break;
15014                    };
15015                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15016                        break;
15017                    };
15018                    offset += grapheme.len();
15019                    graphemes += 1;
15020                    iter.next();
15021                }
15022            }
15023            let token = &self.input[..offset];
15024            self.input = &self.input[offset..];
15025            if is_whitespace {
15026                Some(WordBreakToken {
15027                    token: " ",
15028                    grapheme_len: 1,
15029                    is_whitespace: true,
15030                })
15031            } else {
15032                Some(WordBreakToken {
15033                    token,
15034                    grapheme_len: graphemes,
15035                    is_whitespace: false,
15036                })
15037            }
15038        } else {
15039            None
15040        }
15041    }
15042}
15043
15044#[test]
15045fn test_word_breaking_tokenizer() {
15046    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15047        ("", &[]),
15048        ("  ", &[(" ", 1, true)]),
15049        ("Ʒ", &[("Ʒ", 1, false)]),
15050        ("Ǽ", &[("Ǽ", 1, false)]),
15051        ("", &[("", 1, false)]),
15052        ("⋑⋑", &[("⋑⋑", 2, false)]),
15053        (
15054            "原理,进而",
15055            &[
15056                ("", 1, false),
15057                ("理,", 2, false),
15058                ("", 1, false),
15059                ("", 1, false),
15060            ],
15061        ),
15062        (
15063            "hello world",
15064            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15065        ),
15066        (
15067            "hello, world",
15068            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15069        ),
15070        (
15071            "  hello world",
15072            &[
15073                (" ", 1, true),
15074                ("hello", 5, false),
15075                (" ", 1, true),
15076                ("world", 5, false),
15077            ],
15078        ),
15079        (
15080            "这是什么 \n 钢笔",
15081            &[
15082                ("", 1, false),
15083                ("", 1, false),
15084                ("", 1, false),
15085                ("", 1, false),
15086                (" ", 1, true),
15087                ("", 1, false),
15088                ("", 1, false),
15089            ],
15090        ),
15091        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15092    ];
15093
15094    for (input, result) in tests {
15095        assert_eq!(
15096            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15097            result
15098                .iter()
15099                .copied()
15100                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15101                    token,
15102                    grapheme_len,
15103                    is_whitespace,
15104                })
15105                .collect::<Vec<_>>()
15106        );
15107    }
15108}
15109
15110fn wrap_with_prefix(
15111    line_prefix: String,
15112    unwrapped_text: String,
15113    wrap_column: usize,
15114    tab_size: NonZeroU32,
15115) -> String {
15116    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15117    let mut wrapped_text = String::new();
15118    let mut current_line = line_prefix.clone();
15119
15120    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15121    let mut current_line_len = line_prefix_len;
15122    for WordBreakToken {
15123        token,
15124        grapheme_len,
15125        is_whitespace,
15126    } in tokenizer
15127    {
15128        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15129            wrapped_text.push_str(current_line.trim_end());
15130            wrapped_text.push('\n');
15131            current_line.truncate(line_prefix.len());
15132            current_line_len = line_prefix_len;
15133            if !is_whitespace {
15134                current_line.push_str(token);
15135                current_line_len += grapheme_len;
15136            }
15137        } else if !is_whitespace {
15138            current_line.push_str(token);
15139            current_line_len += grapheme_len;
15140        } else if current_line_len != line_prefix_len {
15141            current_line.push(' ');
15142            current_line_len += 1;
15143        }
15144    }
15145
15146    if !current_line.is_empty() {
15147        wrapped_text.push_str(&current_line);
15148    }
15149    wrapped_text
15150}
15151
15152#[test]
15153fn test_wrap_with_prefix() {
15154    assert_eq!(
15155        wrap_with_prefix(
15156            "# ".to_string(),
15157            "abcdefg".to_string(),
15158            4,
15159            NonZeroU32::new(4).unwrap()
15160        ),
15161        "# abcdefg"
15162    );
15163    assert_eq!(
15164        wrap_with_prefix(
15165            "".to_string(),
15166            "\thello world".to_string(),
15167            8,
15168            NonZeroU32::new(4).unwrap()
15169        ),
15170        "hello\nworld"
15171    );
15172    assert_eq!(
15173        wrap_with_prefix(
15174            "// ".to_string(),
15175            "xx \nyy zz aa bb cc".to_string(),
15176            12,
15177            NonZeroU32::new(4).unwrap()
15178        ),
15179        "// xx yy zz\n// aa bb cc"
15180    );
15181    assert_eq!(
15182        wrap_with_prefix(
15183            String::new(),
15184            "这是什么 \n 钢笔".to_string(),
15185            3,
15186            NonZeroU32::new(4).unwrap()
15187        ),
15188        "这是什\n么 钢\n"
15189    );
15190}
15191
15192pub trait CollaborationHub {
15193    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15194    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15195    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15196}
15197
15198impl CollaborationHub for Entity<Project> {
15199    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15200        self.read(cx).collaborators()
15201    }
15202
15203    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15204        self.read(cx).user_store().read(cx).participant_indices()
15205    }
15206
15207    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15208        let this = self.read(cx);
15209        let user_ids = this.collaborators().values().map(|c| c.user_id);
15210        this.user_store().read_with(cx, |user_store, cx| {
15211            user_store.participant_names(user_ids, cx)
15212        })
15213    }
15214}
15215
15216pub trait SemanticsProvider {
15217    fn hover(
15218        &self,
15219        buffer: &Entity<Buffer>,
15220        position: text::Anchor,
15221        cx: &mut App,
15222    ) -> Option<Task<Vec<project::Hover>>>;
15223
15224    fn inlay_hints(
15225        &self,
15226        buffer_handle: Entity<Buffer>,
15227        range: Range<text::Anchor>,
15228        cx: &mut App,
15229    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15230
15231    fn resolve_inlay_hint(
15232        &self,
15233        hint: InlayHint,
15234        buffer_handle: Entity<Buffer>,
15235        server_id: LanguageServerId,
15236        cx: &mut App,
15237    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15238
15239    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15240
15241    fn document_highlights(
15242        &self,
15243        buffer: &Entity<Buffer>,
15244        position: text::Anchor,
15245        cx: &mut App,
15246    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15247
15248    fn definitions(
15249        &self,
15250        buffer: &Entity<Buffer>,
15251        position: text::Anchor,
15252        kind: GotoDefinitionKind,
15253        cx: &mut App,
15254    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15255
15256    fn range_for_rename(
15257        &self,
15258        buffer: &Entity<Buffer>,
15259        position: text::Anchor,
15260        cx: &mut App,
15261    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15262
15263    fn perform_rename(
15264        &self,
15265        buffer: &Entity<Buffer>,
15266        position: text::Anchor,
15267        new_name: String,
15268        cx: &mut App,
15269    ) -> Option<Task<Result<ProjectTransaction>>>;
15270}
15271
15272pub trait CompletionProvider {
15273    fn completions(
15274        &self,
15275        buffer: &Entity<Buffer>,
15276        buffer_position: text::Anchor,
15277        trigger: CompletionContext,
15278        window: &mut Window,
15279        cx: &mut Context<Editor>,
15280    ) -> Task<Result<Vec<Completion>>>;
15281
15282    fn resolve_completions(
15283        &self,
15284        buffer: Entity<Buffer>,
15285        completion_indices: Vec<usize>,
15286        completions: Rc<RefCell<Box<[Completion]>>>,
15287        cx: &mut Context<Editor>,
15288    ) -> Task<Result<bool>>;
15289
15290    fn apply_additional_edits_for_completion(
15291        &self,
15292        _buffer: Entity<Buffer>,
15293        _completions: Rc<RefCell<Box<[Completion]>>>,
15294        _completion_index: usize,
15295        _push_to_history: bool,
15296        _cx: &mut Context<Editor>,
15297    ) -> Task<Result<Option<language::Transaction>>> {
15298        Task::ready(Ok(None))
15299    }
15300
15301    fn is_completion_trigger(
15302        &self,
15303        buffer: &Entity<Buffer>,
15304        position: language::Anchor,
15305        text: &str,
15306        trigger_in_words: bool,
15307        cx: &mut Context<Editor>,
15308    ) -> bool;
15309
15310    fn sort_completions(&self) -> bool {
15311        true
15312    }
15313}
15314
15315pub trait CodeActionProvider {
15316    fn id(&self) -> Arc<str>;
15317
15318    fn code_actions(
15319        &self,
15320        buffer: &Entity<Buffer>,
15321        range: Range<text::Anchor>,
15322        window: &mut Window,
15323        cx: &mut App,
15324    ) -> Task<Result<Vec<CodeAction>>>;
15325
15326    fn apply_code_action(
15327        &self,
15328        buffer_handle: Entity<Buffer>,
15329        action: CodeAction,
15330        excerpt_id: ExcerptId,
15331        push_to_history: bool,
15332        window: &mut Window,
15333        cx: &mut App,
15334    ) -> Task<Result<ProjectTransaction>>;
15335}
15336
15337impl CodeActionProvider for Entity<Project> {
15338    fn id(&self) -> Arc<str> {
15339        "project".into()
15340    }
15341
15342    fn code_actions(
15343        &self,
15344        buffer: &Entity<Buffer>,
15345        range: Range<text::Anchor>,
15346        _window: &mut Window,
15347        cx: &mut App,
15348    ) -> Task<Result<Vec<CodeAction>>> {
15349        self.update(cx, |project, cx| {
15350            project.code_actions(buffer, range, None, cx)
15351        })
15352    }
15353
15354    fn apply_code_action(
15355        &self,
15356        buffer_handle: Entity<Buffer>,
15357        action: CodeAction,
15358        _excerpt_id: ExcerptId,
15359        push_to_history: bool,
15360        _window: &mut Window,
15361        cx: &mut App,
15362    ) -> Task<Result<ProjectTransaction>> {
15363        self.update(cx, |project, cx| {
15364            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15365        })
15366    }
15367}
15368
15369fn snippet_completions(
15370    project: &Project,
15371    buffer: &Entity<Buffer>,
15372    buffer_position: text::Anchor,
15373    cx: &mut App,
15374) -> Task<Result<Vec<Completion>>> {
15375    let language = buffer.read(cx).language_at(buffer_position);
15376    let language_name = language.as_ref().map(|language| language.lsp_id());
15377    let snippet_store = project.snippets().read(cx);
15378    let snippets = snippet_store.snippets_for(language_name, cx);
15379
15380    if snippets.is_empty() {
15381        return Task::ready(Ok(vec![]));
15382    }
15383    let snapshot = buffer.read(cx).text_snapshot();
15384    let chars: String = snapshot
15385        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15386        .collect();
15387
15388    let scope = language.map(|language| language.default_scope());
15389    let executor = cx.background_executor().clone();
15390
15391    cx.background_executor().spawn(async move {
15392        let classifier = CharClassifier::new(scope).for_completion(true);
15393        let mut last_word = chars
15394            .chars()
15395            .take_while(|c| classifier.is_word(*c))
15396            .collect::<String>();
15397        last_word = last_word.chars().rev().collect();
15398
15399        if last_word.is_empty() {
15400            return Ok(vec![]);
15401        }
15402
15403        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15404        let to_lsp = |point: &text::Anchor| {
15405            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15406            point_to_lsp(end)
15407        };
15408        let lsp_end = to_lsp(&buffer_position);
15409
15410        let candidates = snippets
15411            .iter()
15412            .enumerate()
15413            .flat_map(|(ix, snippet)| {
15414                snippet
15415                    .prefix
15416                    .iter()
15417                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15418            })
15419            .collect::<Vec<StringMatchCandidate>>();
15420
15421        let mut matches = fuzzy::match_strings(
15422            &candidates,
15423            &last_word,
15424            last_word.chars().any(|c| c.is_uppercase()),
15425            100,
15426            &Default::default(),
15427            executor,
15428        )
15429        .await;
15430
15431        // Remove all candidates where the query's start does not match the start of any word in the candidate
15432        if let Some(query_start) = last_word.chars().next() {
15433            matches.retain(|string_match| {
15434                split_words(&string_match.string).any(|word| {
15435                    // Check that the first codepoint of the word as lowercase matches the first
15436                    // codepoint of the query as lowercase
15437                    word.chars()
15438                        .flat_map(|codepoint| codepoint.to_lowercase())
15439                        .zip(query_start.to_lowercase())
15440                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15441                })
15442            });
15443        }
15444
15445        let matched_strings = matches
15446            .into_iter()
15447            .map(|m| m.string)
15448            .collect::<HashSet<_>>();
15449
15450        let result: Vec<Completion> = snippets
15451            .into_iter()
15452            .filter_map(|snippet| {
15453                let matching_prefix = snippet
15454                    .prefix
15455                    .iter()
15456                    .find(|prefix| matched_strings.contains(*prefix))?;
15457                let start = as_offset - last_word.len();
15458                let start = snapshot.anchor_before(start);
15459                let range = start..buffer_position;
15460                let lsp_start = to_lsp(&start);
15461                let lsp_range = lsp::Range {
15462                    start: lsp_start,
15463                    end: lsp_end,
15464                };
15465                Some(Completion {
15466                    old_range: range,
15467                    new_text: snippet.body.clone(),
15468                    resolved: false,
15469                    label: CodeLabel {
15470                        text: matching_prefix.clone(),
15471                        runs: vec![],
15472                        filter_range: 0..matching_prefix.len(),
15473                    },
15474                    server_id: LanguageServerId(usize::MAX),
15475                    documentation: snippet
15476                        .description
15477                        .clone()
15478                        .map(CompletionDocumentation::SingleLine),
15479                    lsp_completion: lsp::CompletionItem {
15480                        label: snippet.prefix.first().unwrap().clone(),
15481                        kind: Some(CompletionItemKind::SNIPPET),
15482                        label_details: snippet.description.as_ref().map(|description| {
15483                            lsp::CompletionItemLabelDetails {
15484                                detail: Some(description.clone()),
15485                                description: None,
15486                            }
15487                        }),
15488                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15489                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15490                            lsp::InsertReplaceEdit {
15491                                new_text: snippet.body.clone(),
15492                                insert: lsp_range,
15493                                replace: lsp_range,
15494                            },
15495                        )),
15496                        filter_text: Some(snippet.body.clone()),
15497                        sort_text: Some(char::MAX.to_string()),
15498                        ..Default::default()
15499                    },
15500                    confirm: None,
15501                })
15502            })
15503            .collect();
15504
15505        Ok(result)
15506    })
15507}
15508
15509impl CompletionProvider for Entity<Project> {
15510    fn completions(
15511        &self,
15512        buffer: &Entity<Buffer>,
15513        buffer_position: text::Anchor,
15514        options: CompletionContext,
15515        _window: &mut Window,
15516        cx: &mut Context<Editor>,
15517    ) -> Task<Result<Vec<Completion>>> {
15518        self.update(cx, |project, cx| {
15519            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15520            let project_completions = project.completions(buffer, buffer_position, options, cx);
15521            cx.background_executor().spawn(async move {
15522                let mut completions = project_completions.await?;
15523                let snippets_completions = snippets.await?;
15524                completions.extend(snippets_completions);
15525                Ok(completions)
15526            })
15527        })
15528    }
15529
15530    fn resolve_completions(
15531        &self,
15532        buffer: Entity<Buffer>,
15533        completion_indices: Vec<usize>,
15534        completions: Rc<RefCell<Box<[Completion]>>>,
15535        cx: &mut Context<Editor>,
15536    ) -> Task<Result<bool>> {
15537        self.update(cx, |project, cx| {
15538            project.lsp_store().update(cx, |lsp_store, cx| {
15539                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15540            })
15541        })
15542    }
15543
15544    fn apply_additional_edits_for_completion(
15545        &self,
15546        buffer: Entity<Buffer>,
15547        completions: Rc<RefCell<Box<[Completion]>>>,
15548        completion_index: usize,
15549        push_to_history: bool,
15550        cx: &mut Context<Editor>,
15551    ) -> Task<Result<Option<language::Transaction>>> {
15552        self.update(cx, |project, cx| {
15553            project.lsp_store().update(cx, |lsp_store, cx| {
15554                lsp_store.apply_additional_edits_for_completion(
15555                    buffer,
15556                    completions,
15557                    completion_index,
15558                    push_to_history,
15559                    cx,
15560                )
15561            })
15562        })
15563    }
15564
15565    fn is_completion_trigger(
15566        &self,
15567        buffer: &Entity<Buffer>,
15568        position: language::Anchor,
15569        text: &str,
15570        trigger_in_words: bool,
15571        cx: &mut Context<Editor>,
15572    ) -> bool {
15573        let mut chars = text.chars();
15574        let char = if let Some(char) = chars.next() {
15575            char
15576        } else {
15577            return false;
15578        };
15579        if chars.next().is_some() {
15580            return false;
15581        }
15582
15583        let buffer = buffer.read(cx);
15584        let snapshot = buffer.snapshot();
15585        if !snapshot.settings_at(position, cx).show_completions_on_input {
15586            return false;
15587        }
15588        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15589        if trigger_in_words && classifier.is_word(char) {
15590            return true;
15591        }
15592
15593        buffer.completion_triggers().contains(text)
15594    }
15595}
15596
15597impl SemanticsProvider for Entity<Project> {
15598    fn hover(
15599        &self,
15600        buffer: &Entity<Buffer>,
15601        position: text::Anchor,
15602        cx: &mut App,
15603    ) -> Option<Task<Vec<project::Hover>>> {
15604        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15605    }
15606
15607    fn document_highlights(
15608        &self,
15609        buffer: &Entity<Buffer>,
15610        position: text::Anchor,
15611        cx: &mut App,
15612    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15613        Some(self.update(cx, |project, cx| {
15614            project.document_highlights(buffer, position, cx)
15615        }))
15616    }
15617
15618    fn definitions(
15619        &self,
15620        buffer: &Entity<Buffer>,
15621        position: text::Anchor,
15622        kind: GotoDefinitionKind,
15623        cx: &mut App,
15624    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15625        Some(self.update(cx, |project, cx| match kind {
15626            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15627            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15628            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15629            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15630        }))
15631    }
15632
15633    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15634        // TODO: make this work for remote projects
15635        self.read(cx)
15636            .language_servers_for_local_buffer(buffer.read(cx), cx)
15637            .any(
15638                |(_, server)| match server.capabilities().inlay_hint_provider {
15639                    Some(lsp::OneOf::Left(enabled)) => enabled,
15640                    Some(lsp::OneOf::Right(_)) => true,
15641                    None => false,
15642                },
15643            )
15644    }
15645
15646    fn inlay_hints(
15647        &self,
15648        buffer_handle: Entity<Buffer>,
15649        range: Range<text::Anchor>,
15650        cx: &mut App,
15651    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15652        Some(self.update(cx, |project, cx| {
15653            project.inlay_hints(buffer_handle, range, cx)
15654        }))
15655    }
15656
15657    fn resolve_inlay_hint(
15658        &self,
15659        hint: InlayHint,
15660        buffer_handle: Entity<Buffer>,
15661        server_id: LanguageServerId,
15662        cx: &mut App,
15663    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15664        Some(self.update(cx, |project, cx| {
15665            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15666        }))
15667    }
15668
15669    fn range_for_rename(
15670        &self,
15671        buffer: &Entity<Buffer>,
15672        position: text::Anchor,
15673        cx: &mut App,
15674    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15675        Some(self.update(cx, |project, cx| {
15676            let buffer = buffer.clone();
15677            let task = project.prepare_rename(buffer.clone(), position, cx);
15678            cx.spawn(|_, mut cx| async move {
15679                Ok(match task.await? {
15680                    PrepareRenameResponse::Success(range) => Some(range),
15681                    PrepareRenameResponse::InvalidPosition => None,
15682                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15683                        // Fallback on using TreeSitter info to determine identifier range
15684                        buffer.update(&mut cx, |buffer, _| {
15685                            let snapshot = buffer.snapshot();
15686                            let (range, kind) = snapshot.surrounding_word(position);
15687                            if kind != Some(CharKind::Word) {
15688                                return None;
15689                            }
15690                            Some(
15691                                snapshot.anchor_before(range.start)
15692                                    ..snapshot.anchor_after(range.end),
15693                            )
15694                        })?
15695                    }
15696                })
15697            })
15698        }))
15699    }
15700
15701    fn perform_rename(
15702        &self,
15703        buffer: &Entity<Buffer>,
15704        position: text::Anchor,
15705        new_name: String,
15706        cx: &mut App,
15707    ) -> Option<Task<Result<ProjectTransaction>>> {
15708        Some(self.update(cx, |project, cx| {
15709            project.perform_rename(buffer.clone(), position, new_name, cx)
15710        }))
15711    }
15712}
15713
15714fn inlay_hint_settings(
15715    location: Anchor,
15716    snapshot: &MultiBufferSnapshot,
15717    cx: &mut Context<Editor>,
15718) -> InlayHintSettings {
15719    let file = snapshot.file_at(location);
15720    let language = snapshot.language_at(location).map(|l| l.name());
15721    language_settings(language, file, cx).inlay_hints
15722}
15723
15724fn consume_contiguous_rows(
15725    contiguous_row_selections: &mut Vec<Selection<Point>>,
15726    selection: &Selection<Point>,
15727    display_map: &DisplaySnapshot,
15728    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15729) -> (MultiBufferRow, MultiBufferRow) {
15730    contiguous_row_selections.push(selection.clone());
15731    let start_row = MultiBufferRow(selection.start.row);
15732    let mut end_row = ending_row(selection, display_map);
15733
15734    while let Some(next_selection) = selections.peek() {
15735        if next_selection.start.row <= end_row.0 {
15736            end_row = ending_row(next_selection, display_map);
15737            contiguous_row_selections.push(selections.next().unwrap().clone());
15738        } else {
15739            break;
15740        }
15741    }
15742    (start_row, end_row)
15743}
15744
15745fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15746    if next_selection.end.column > 0 || next_selection.is_empty() {
15747        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15748    } else {
15749        MultiBufferRow(next_selection.end.row)
15750    }
15751}
15752
15753impl EditorSnapshot {
15754    pub fn remote_selections_in_range<'a>(
15755        &'a self,
15756        range: &'a Range<Anchor>,
15757        collaboration_hub: &dyn CollaborationHub,
15758        cx: &'a App,
15759    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15760        let participant_names = collaboration_hub.user_names(cx);
15761        let participant_indices = collaboration_hub.user_participant_indices(cx);
15762        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15763        let collaborators_by_replica_id = collaborators_by_peer_id
15764            .iter()
15765            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15766            .collect::<HashMap<_, _>>();
15767        self.buffer_snapshot
15768            .selections_in_range(range, false)
15769            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15770                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15771                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15772                let user_name = participant_names.get(&collaborator.user_id).cloned();
15773                Some(RemoteSelection {
15774                    replica_id,
15775                    selection,
15776                    cursor_shape,
15777                    line_mode,
15778                    participant_index,
15779                    peer_id: collaborator.peer_id,
15780                    user_name,
15781                })
15782            })
15783    }
15784
15785    pub fn hunks_for_ranges(
15786        &self,
15787        ranges: impl Iterator<Item = Range<Point>>,
15788    ) -> Vec<MultiBufferDiffHunk> {
15789        let mut hunks = Vec::new();
15790        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15791            HashMap::default();
15792        for query_range in ranges {
15793            let query_rows =
15794                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15795            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15796                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15797            ) {
15798                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15799                // when the caret is just above or just below the deleted hunk.
15800                let allow_adjacent = hunk.status().is_removed();
15801                let related_to_selection = if allow_adjacent {
15802                    hunk.row_range.overlaps(&query_rows)
15803                        || hunk.row_range.start == query_rows.end
15804                        || hunk.row_range.end == query_rows.start
15805                } else {
15806                    hunk.row_range.overlaps(&query_rows)
15807                };
15808                if related_to_selection {
15809                    if !processed_buffer_rows
15810                        .entry(hunk.buffer_id)
15811                        .or_default()
15812                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15813                    {
15814                        continue;
15815                    }
15816                    hunks.push(hunk);
15817                }
15818            }
15819        }
15820
15821        hunks
15822    }
15823
15824    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15825        self.display_snapshot.buffer_snapshot.language_at(position)
15826    }
15827
15828    pub fn is_focused(&self) -> bool {
15829        self.is_focused
15830    }
15831
15832    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15833        self.placeholder_text.as_ref()
15834    }
15835
15836    pub fn scroll_position(&self) -> gpui::Point<f32> {
15837        self.scroll_anchor.scroll_position(&self.display_snapshot)
15838    }
15839
15840    fn gutter_dimensions(
15841        &self,
15842        font_id: FontId,
15843        font_size: Pixels,
15844        max_line_number_width: Pixels,
15845        cx: &App,
15846    ) -> Option<GutterDimensions> {
15847        if !self.show_gutter {
15848            return None;
15849        }
15850
15851        let descent = cx.text_system().descent(font_id, font_size);
15852        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15853        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15854
15855        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15856            matches!(
15857                ProjectSettings::get_global(cx).git.git_gutter,
15858                Some(GitGutterSetting::TrackedFiles)
15859            )
15860        });
15861        let gutter_settings = EditorSettings::get_global(cx).gutter;
15862        let show_line_numbers = self
15863            .show_line_numbers
15864            .unwrap_or(gutter_settings.line_numbers);
15865        let line_gutter_width = if show_line_numbers {
15866            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15867            let min_width_for_number_on_gutter = em_advance * 4.0;
15868            max_line_number_width.max(min_width_for_number_on_gutter)
15869        } else {
15870            0.0.into()
15871        };
15872
15873        let show_code_actions = self
15874            .show_code_actions
15875            .unwrap_or(gutter_settings.code_actions);
15876
15877        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15878
15879        let git_blame_entries_width =
15880            self.git_blame_gutter_max_author_length
15881                .map(|max_author_length| {
15882                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15883
15884                    /// The number of characters to dedicate to gaps and margins.
15885                    const SPACING_WIDTH: usize = 4;
15886
15887                    let max_char_count = max_author_length
15888                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15889                        + ::git::SHORT_SHA_LENGTH
15890                        + MAX_RELATIVE_TIMESTAMP.len()
15891                        + SPACING_WIDTH;
15892
15893                    em_advance * max_char_count
15894                });
15895
15896        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15897        left_padding += if show_code_actions || show_runnables {
15898            em_width * 3.0
15899        } else if show_git_gutter && show_line_numbers {
15900            em_width * 2.0
15901        } else if show_git_gutter || show_line_numbers {
15902            em_width
15903        } else {
15904            px(0.)
15905        };
15906
15907        let right_padding = if gutter_settings.folds && show_line_numbers {
15908            em_width * 4.0
15909        } else if gutter_settings.folds {
15910            em_width * 3.0
15911        } else if show_line_numbers {
15912            em_width
15913        } else {
15914            px(0.)
15915        };
15916
15917        Some(GutterDimensions {
15918            left_padding,
15919            right_padding,
15920            width: line_gutter_width + left_padding + right_padding,
15921            margin: -descent,
15922            git_blame_entries_width,
15923        })
15924    }
15925
15926    pub fn render_crease_toggle(
15927        &self,
15928        buffer_row: MultiBufferRow,
15929        row_contains_cursor: bool,
15930        editor: Entity<Editor>,
15931        window: &mut Window,
15932        cx: &mut App,
15933    ) -> Option<AnyElement> {
15934        let folded = self.is_line_folded(buffer_row);
15935        let mut is_foldable = false;
15936
15937        if let Some(crease) = self
15938            .crease_snapshot
15939            .query_row(buffer_row, &self.buffer_snapshot)
15940        {
15941            is_foldable = true;
15942            match crease {
15943                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15944                    if let Some(render_toggle) = render_toggle {
15945                        let toggle_callback =
15946                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15947                                if folded {
15948                                    editor.update(cx, |editor, cx| {
15949                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15950                                    });
15951                                } else {
15952                                    editor.update(cx, |editor, cx| {
15953                                        editor.unfold_at(
15954                                            &crate::UnfoldAt { buffer_row },
15955                                            window,
15956                                            cx,
15957                                        )
15958                                    });
15959                                }
15960                            });
15961                        return Some((render_toggle)(
15962                            buffer_row,
15963                            folded,
15964                            toggle_callback,
15965                            window,
15966                            cx,
15967                        ));
15968                    }
15969                }
15970            }
15971        }
15972
15973        is_foldable |= self.starts_indent(buffer_row);
15974
15975        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15976            Some(
15977                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15978                    .toggle_state(folded)
15979                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15980                        if folded {
15981                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15982                        } else {
15983                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15984                        }
15985                    }))
15986                    .into_any_element(),
15987            )
15988        } else {
15989            None
15990        }
15991    }
15992
15993    pub fn render_crease_trailer(
15994        &self,
15995        buffer_row: MultiBufferRow,
15996        window: &mut Window,
15997        cx: &mut App,
15998    ) -> Option<AnyElement> {
15999        let folded = self.is_line_folded(buffer_row);
16000        if let Crease::Inline { render_trailer, .. } = self
16001            .crease_snapshot
16002            .query_row(buffer_row, &self.buffer_snapshot)?
16003        {
16004            let render_trailer = render_trailer.as_ref()?;
16005            Some(render_trailer(buffer_row, folded, window, cx))
16006        } else {
16007            None
16008        }
16009    }
16010}
16011
16012impl Deref for EditorSnapshot {
16013    type Target = DisplaySnapshot;
16014
16015    fn deref(&self) -> &Self::Target {
16016        &self.display_snapshot
16017    }
16018}
16019
16020#[derive(Clone, Debug, PartialEq, Eq)]
16021pub enum EditorEvent {
16022    InputIgnored {
16023        text: Arc<str>,
16024    },
16025    InputHandled {
16026        utf16_range_to_replace: Option<Range<isize>>,
16027        text: Arc<str>,
16028    },
16029    ExcerptsAdded {
16030        buffer: Entity<Buffer>,
16031        predecessor: ExcerptId,
16032        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16033    },
16034    ExcerptsRemoved {
16035        ids: Vec<ExcerptId>,
16036    },
16037    BufferFoldToggled {
16038        ids: Vec<ExcerptId>,
16039        folded: bool,
16040    },
16041    ExcerptsEdited {
16042        ids: Vec<ExcerptId>,
16043    },
16044    ExcerptsExpanded {
16045        ids: Vec<ExcerptId>,
16046    },
16047    BufferEdited,
16048    Edited {
16049        transaction_id: clock::Lamport,
16050    },
16051    Reparsed(BufferId),
16052    Focused,
16053    FocusedIn,
16054    Blurred,
16055    DirtyChanged,
16056    Saved,
16057    TitleChanged,
16058    DiffBaseChanged,
16059    SelectionsChanged {
16060        local: bool,
16061    },
16062    ScrollPositionChanged {
16063        local: bool,
16064        autoscroll: bool,
16065    },
16066    Closed,
16067    TransactionUndone {
16068        transaction_id: clock::Lamport,
16069    },
16070    TransactionBegun {
16071        transaction_id: clock::Lamport,
16072    },
16073    Reloaded,
16074    CursorShapeChanged,
16075}
16076
16077impl EventEmitter<EditorEvent> for Editor {}
16078
16079impl Focusable for Editor {
16080    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16081        self.focus_handle.clone()
16082    }
16083}
16084
16085impl Render for Editor {
16086    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16087        let settings = ThemeSettings::get_global(cx);
16088
16089        let mut text_style = match self.mode {
16090            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16091                color: cx.theme().colors().editor_foreground,
16092                font_family: settings.ui_font.family.clone(),
16093                font_features: settings.ui_font.features.clone(),
16094                font_fallbacks: settings.ui_font.fallbacks.clone(),
16095                font_size: rems(0.875).into(),
16096                font_weight: settings.ui_font.weight,
16097                line_height: relative(settings.buffer_line_height.value()),
16098                ..Default::default()
16099            },
16100            EditorMode::Full => TextStyle {
16101                color: cx.theme().colors().editor_foreground,
16102                font_family: settings.buffer_font.family.clone(),
16103                font_features: settings.buffer_font.features.clone(),
16104                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16105                font_size: settings.buffer_font_size().into(),
16106                font_weight: settings.buffer_font.weight,
16107                line_height: relative(settings.buffer_line_height.value()),
16108                ..Default::default()
16109            },
16110        };
16111        if let Some(text_style_refinement) = &self.text_style_refinement {
16112            text_style.refine(text_style_refinement)
16113        }
16114
16115        let background = match self.mode {
16116            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16117            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16118            EditorMode::Full => cx.theme().colors().editor_background,
16119        };
16120
16121        EditorElement::new(
16122            &cx.entity(),
16123            EditorStyle {
16124                background,
16125                local_player: cx.theme().players().local(),
16126                text: text_style,
16127                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16128                syntax: cx.theme().syntax().clone(),
16129                status: cx.theme().status().clone(),
16130                inlay_hints_style: make_inlay_hints_style(cx),
16131                inline_completion_styles: make_suggestion_styles(cx),
16132                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16133            },
16134        )
16135    }
16136}
16137
16138impl EntityInputHandler for Editor {
16139    fn text_for_range(
16140        &mut self,
16141        range_utf16: Range<usize>,
16142        adjusted_range: &mut Option<Range<usize>>,
16143        _: &mut Window,
16144        cx: &mut Context<Self>,
16145    ) -> Option<String> {
16146        let snapshot = self.buffer.read(cx).read(cx);
16147        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16148        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16149        if (start.0..end.0) != range_utf16 {
16150            adjusted_range.replace(start.0..end.0);
16151        }
16152        Some(snapshot.text_for_range(start..end).collect())
16153    }
16154
16155    fn selected_text_range(
16156        &mut self,
16157        ignore_disabled_input: bool,
16158        _: &mut Window,
16159        cx: &mut Context<Self>,
16160    ) -> Option<UTF16Selection> {
16161        // Prevent the IME menu from appearing when holding down an alphabetic key
16162        // while input is disabled.
16163        if !ignore_disabled_input && !self.input_enabled {
16164            return None;
16165        }
16166
16167        let selection = self.selections.newest::<OffsetUtf16>(cx);
16168        let range = selection.range();
16169
16170        Some(UTF16Selection {
16171            range: range.start.0..range.end.0,
16172            reversed: selection.reversed,
16173        })
16174    }
16175
16176    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16177        let snapshot = self.buffer.read(cx).read(cx);
16178        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16179        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16180    }
16181
16182    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16183        self.clear_highlights::<InputComposition>(cx);
16184        self.ime_transaction.take();
16185    }
16186
16187    fn replace_text_in_range(
16188        &mut self,
16189        range_utf16: Option<Range<usize>>,
16190        text: &str,
16191        window: &mut Window,
16192        cx: &mut Context<Self>,
16193    ) {
16194        if !self.input_enabled {
16195            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16196            return;
16197        }
16198
16199        self.transact(window, cx, |this, window, cx| {
16200            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16201                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16202                Some(this.selection_replacement_ranges(range_utf16, cx))
16203            } else {
16204                this.marked_text_ranges(cx)
16205            };
16206
16207            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16208                let newest_selection_id = this.selections.newest_anchor().id;
16209                this.selections
16210                    .all::<OffsetUtf16>(cx)
16211                    .iter()
16212                    .zip(ranges_to_replace.iter())
16213                    .find_map(|(selection, range)| {
16214                        if selection.id == newest_selection_id {
16215                            Some(
16216                                (range.start.0 as isize - selection.head().0 as isize)
16217                                    ..(range.end.0 as isize - selection.head().0 as isize),
16218                            )
16219                        } else {
16220                            None
16221                        }
16222                    })
16223            });
16224
16225            cx.emit(EditorEvent::InputHandled {
16226                utf16_range_to_replace: range_to_replace,
16227                text: text.into(),
16228            });
16229
16230            if let Some(new_selected_ranges) = new_selected_ranges {
16231                this.change_selections(None, window, cx, |selections| {
16232                    selections.select_ranges(new_selected_ranges)
16233                });
16234                this.backspace(&Default::default(), window, cx);
16235            }
16236
16237            this.handle_input(text, window, cx);
16238        });
16239
16240        if let Some(transaction) = self.ime_transaction {
16241            self.buffer.update(cx, |buffer, cx| {
16242                buffer.group_until_transaction(transaction, cx);
16243            });
16244        }
16245
16246        self.unmark_text(window, cx);
16247    }
16248
16249    fn replace_and_mark_text_in_range(
16250        &mut self,
16251        range_utf16: Option<Range<usize>>,
16252        text: &str,
16253        new_selected_range_utf16: Option<Range<usize>>,
16254        window: &mut Window,
16255        cx: &mut Context<Self>,
16256    ) {
16257        if !self.input_enabled {
16258            return;
16259        }
16260
16261        let transaction = self.transact(window, cx, |this, window, cx| {
16262            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16263                let snapshot = this.buffer.read(cx).read(cx);
16264                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16265                    for marked_range in &mut marked_ranges {
16266                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16267                        marked_range.start.0 += relative_range_utf16.start;
16268                        marked_range.start =
16269                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16270                        marked_range.end =
16271                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16272                    }
16273                }
16274                Some(marked_ranges)
16275            } else if let Some(range_utf16) = range_utf16 {
16276                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16277                Some(this.selection_replacement_ranges(range_utf16, cx))
16278            } else {
16279                None
16280            };
16281
16282            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16283                let newest_selection_id = this.selections.newest_anchor().id;
16284                this.selections
16285                    .all::<OffsetUtf16>(cx)
16286                    .iter()
16287                    .zip(ranges_to_replace.iter())
16288                    .find_map(|(selection, range)| {
16289                        if selection.id == newest_selection_id {
16290                            Some(
16291                                (range.start.0 as isize - selection.head().0 as isize)
16292                                    ..(range.end.0 as isize - selection.head().0 as isize),
16293                            )
16294                        } else {
16295                            None
16296                        }
16297                    })
16298            });
16299
16300            cx.emit(EditorEvent::InputHandled {
16301                utf16_range_to_replace: range_to_replace,
16302                text: text.into(),
16303            });
16304
16305            if let Some(ranges) = ranges_to_replace {
16306                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16307            }
16308
16309            let marked_ranges = {
16310                let snapshot = this.buffer.read(cx).read(cx);
16311                this.selections
16312                    .disjoint_anchors()
16313                    .iter()
16314                    .map(|selection| {
16315                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16316                    })
16317                    .collect::<Vec<_>>()
16318            };
16319
16320            if text.is_empty() {
16321                this.unmark_text(window, cx);
16322            } else {
16323                this.highlight_text::<InputComposition>(
16324                    marked_ranges.clone(),
16325                    HighlightStyle {
16326                        underline: Some(UnderlineStyle {
16327                            thickness: px(1.),
16328                            color: None,
16329                            wavy: false,
16330                        }),
16331                        ..Default::default()
16332                    },
16333                    cx,
16334                );
16335            }
16336
16337            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16338            let use_autoclose = this.use_autoclose;
16339            let use_auto_surround = this.use_auto_surround;
16340            this.set_use_autoclose(false);
16341            this.set_use_auto_surround(false);
16342            this.handle_input(text, window, cx);
16343            this.set_use_autoclose(use_autoclose);
16344            this.set_use_auto_surround(use_auto_surround);
16345
16346            if let Some(new_selected_range) = new_selected_range_utf16 {
16347                let snapshot = this.buffer.read(cx).read(cx);
16348                let new_selected_ranges = marked_ranges
16349                    .into_iter()
16350                    .map(|marked_range| {
16351                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16352                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16353                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16354                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16355                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16356                    })
16357                    .collect::<Vec<_>>();
16358
16359                drop(snapshot);
16360                this.change_selections(None, window, cx, |selections| {
16361                    selections.select_ranges(new_selected_ranges)
16362                });
16363            }
16364        });
16365
16366        self.ime_transaction = self.ime_transaction.or(transaction);
16367        if let Some(transaction) = self.ime_transaction {
16368            self.buffer.update(cx, |buffer, cx| {
16369                buffer.group_until_transaction(transaction, cx);
16370            });
16371        }
16372
16373        if self.text_highlights::<InputComposition>(cx).is_none() {
16374            self.ime_transaction.take();
16375        }
16376    }
16377
16378    fn bounds_for_range(
16379        &mut self,
16380        range_utf16: Range<usize>,
16381        element_bounds: gpui::Bounds<Pixels>,
16382        window: &mut Window,
16383        cx: &mut Context<Self>,
16384    ) -> Option<gpui::Bounds<Pixels>> {
16385        let text_layout_details = self.text_layout_details(window);
16386        let gpui::Size {
16387            width: em_width,
16388            height: line_height,
16389        } = self.character_size(window);
16390
16391        let snapshot = self.snapshot(window, cx);
16392        let scroll_position = snapshot.scroll_position();
16393        let scroll_left = scroll_position.x * em_width;
16394
16395        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16396        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16397            + self.gutter_dimensions.width
16398            + self.gutter_dimensions.margin;
16399        let y = line_height * (start.row().as_f32() - scroll_position.y);
16400
16401        Some(Bounds {
16402            origin: element_bounds.origin + point(x, y),
16403            size: size(em_width, line_height),
16404        })
16405    }
16406
16407    fn character_index_for_point(
16408        &mut self,
16409        point: gpui::Point<Pixels>,
16410        _window: &mut Window,
16411        _cx: &mut Context<Self>,
16412    ) -> Option<usize> {
16413        let position_map = self.last_position_map.as_ref()?;
16414        if !position_map.text_hitbox.contains(&point) {
16415            return None;
16416        }
16417        let display_point = position_map.point_for_position(point).previous_valid;
16418        let anchor = position_map
16419            .snapshot
16420            .display_point_to_anchor(display_point, Bias::Left);
16421        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16422        Some(utf16_offset.0)
16423    }
16424}
16425
16426trait SelectionExt {
16427    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16428    fn spanned_rows(
16429        &self,
16430        include_end_if_at_line_start: bool,
16431        map: &DisplaySnapshot,
16432    ) -> Range<MultiBufferRow>;
16433}
16434
16435impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16436    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16437        let start = self
16438            .start
16439            .to_point(&map.buffer_snapshot)
16440            .to_display_point(map);
16441        let end = self
16442            .end
16443            .to_point(&map.buffer_snapshot)
16444            .to_display_point(map);
16445        if self.reversed {
16446            end..start
16447        } else {
16448            start..end
16449        }
16450    }
16451
16452    fn spanned_rows(
16453        &self,
16454        include_end_if_at_line_start: bool,
16455        map: &DisplaySnapshot,
16456    ) -> Range<MultiBufferRow> {
16457        let start = self.start.to_point(&map.buffer_snapshot);
16458        let mut end = self.end.to_point(&map.buffer_snapshot);
16459        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16460            end.row -= 1;
16461        }
16462
16463        let buffer_start = map.prev_line_boundary(start).0;
16464        let buffer_end = map.next_line_boundary(end).0;
16465        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16466    }
16467}
16468
16469impl<T: InvalidationRegion> InvalidationStack<T> {
16470    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16471    where
16472        S: Clone + ToOffset,
16473    {
16474        while let Some(region) = self.last() {
16475            let all_selections_inside_invalidation_ranges =
16476                if selections.len() == region.ranges().len() {
16477                    selections
16478                        .iter()
16479                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16480                        .all(|(selection, invalidation_range)| {
16481                            let head = selection.head().to_offset(buffer);
16482                            invalidation_range.start <= head && invalidation_range.end >= head
16483                        })
16484                } else {
16485                    false
16486                };
16487
16488            if all_selections_inside_invalidation_ranges {
16489                break;
16490            } else {
16491                self.pop();
16492            }
16493        }
16494    }
16495}
16496
16497impl<T> Default for InvalidationStack<T> {
16498    fn default() -> Self {
16499        Self(Default::default())
16500    }
16501}
16502
16503impl<T> Deref for InvalidationStack<T> {
16504    type Target = Vec<T>;
16505
16506    fn deref(&self) -> &Self::Target {
16507        &self.0
16508    }
16509}
16510
16511impl<T> DerefMut for InvalidationStack<T> {
16512    fn deref_mut(&mut self) -> &mut Self::Target {
16513        &mut self.0
16514    }
16515}
16516
16517impl InvalidationRegion for SnippetState {
16518    fn ranges(&self) -> &[Range<Anchor>] {
16519        &self.ranges[self.active_index]
16520    }
16521}
16522
16523pub fn diagnostic_block_renderer(
16524    diagnostic: Diagnostic,
16525    max_message_rows: Option<u8>,
16526    allow_closing: bool,
16527    _is_valid: bool,
16528) -> RenderBlock {
16529    let (text_without_backticks, code_ranges) =
16530        highlight_diagnostic_message(&diagnostic, max_message_rows);
16531
16532    Arc::new(move |cx: &mut BlockContext| {
16533        let group_id: SharedString = cx.block_id.to_string().into();
16534
16535        let mut text_style = cx.window.text_style().clone();
16536        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16537        let theme_settings = ThemeSettings::get_global(cx);
16538        text_style.font_family = theme_settings.buffer_font.family.clone();
16539        text_style.font_style = theme_settings.buffer_font.style;
16540        text_style.font_features = theme_settings.buffer_font.features.clone();
16541        text_style.font_weight = theme_settings.buffer_font.weight;
16542
16543        let multi_line_diagnostic = diagnostic.message.contains('\n');
16544
16545        let buttons = |diagnostic: &Diagnostic| {
16546            if multi_line_diagnostic {
16547                v_flex()
16548            } else {
16549                h_flex()
16550            }
16551            .when(allow_closing, |div| {
16552                div.children(diagnostic.is_primary.then(|| {
16553                    IconButton::new("close-block", IconName::XCircle)
16554                        .icon_color(Color::Muted)
16555                        .size(ButtonSize::Compact)
16556                        .style(ButtonStyle::Transparent)
16557                        .visible_on_hover(group_id.clone())
16558                        .on_click(move |_click, window, cx| {
16559                            window.dispatch_action(Box::new(Cancel), cx)
16560                        })
16561                        .tooltip(|window, cx| {
16562                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16563                        })
16564                }))
16565            })
16566            .child(
16567                IconButton::new("copy-block", IconName::Copy)
16568                    .icon_color(Color::Muted)
16569                    .size(ButtonSize::Compact)
16570                    .style(ButtonStyle::Transparent)
16571                    .visible_on_hover(group_id.clone())
16572                    .on_click({
16573                        let message = diagnostic.message.clone();
16574                        move |_click, _, cx| {
16575                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16576                        }
16577                    })
16578                    .tooltip(Tooltip::text("Copy diagnostic message")),
16579            )
16580        };
16581
16582        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16583            AvailableSpace::min_size(),
16584            cx.window,
16585            cx.app,
16586        );
16587
16588        h_flex()
16589            .id(cx.block_id)
16590            .group(group_id.clone())
16591            .relative()
16592            .size_full()
16593            .block_mouse_down()
16594            .pl(cx.gutter_dimensions.width)
16595            .w(cx.max_width - cx.gutter_dimensions.full_width())
16596            .child(
16597                div()
16598                    .flex()
16599                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16600                    .flex_shrink(),
16601            )
16602            .child(buttons(&diagnostic))
16603            .child(div().flex().flex_shrink_0().child(
16604                StyledText::new(text_without_backticks.clone()).with_highlights(
16605                    &text_style,
16606                    code_ranges.iter().map(|range| {
16607                        (
16608                            range.clone(),
16609                            HighlightStyle {
16610                                font_weight: Some(FontWeight::BOLD),
16611                                ..Default::default()
16612                            },
16613                        )
16614                    }),
16615                ),
16616            ))
16617            .into_any_element()
16618    })
16619}
16620
16621fn inline_completion_edit_text(
16622    current_snapshot: &BufferSnapshot,
16623    edits: &[(Range<Anchor>, String)],
16624    edit_preview: &EditPreview,
16625    include_deletions: bool,
16626    cx: &App,
16627) -> HighlightedText {
16628    let edits = edits
16629        .iter()
16630        .map(|(anchor, text)| {
16631            (
16632                anchor.start.text_anchor..anchor.end.text_anchor,
16633                text.clone(),
16634            )
16635        })
16636        .collect::<Vec<_>>();
16637
16638    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16639}
16640
16641pub fn highlight_diagnostic_message(
16642    diagnostic: &Diagnostic,
16643    mut max_message_rows: Option<u8>,
16644) -> (SharedString, Vec<Range<usize>>) {
16645    let mut text_without_backticks = String::new();
16646    let mut code_ranges = Vec::new();
16647
16648    if let Some(source) = &diagnostic.source {
16649        text_without_backticks.push_str(source);
16650        code_ranges.push(0..source.len());
16651        text_without_backticks.push_str(": ");
16652    }
16653
16654    let mut prev_offset = 0;
16655    let mut in_code_block = false;
16656    let has_row_limit = max_message_rows.is_some();
16657    let mut newline_indices = diagnostic
16658        .message
16659        .match_indices('\n')
16660        .filter(|_| has_row_limit)
16661        .map(|(ix, _)| ix)
16662        .fuse()
16663        .peekable();
16664
16665    for (quote_ix, _) in diagnostic
16666        .message
16667        .match_indices('`')
16668        .chain([(diagnostic.message.len(), "")])
16669    {
16670        let mut first_newline_ix = None;
16671        let mut last_newline_ix = None;
16672        while let Some(newline_ix) = newline_indices.peek() {
16673            if *newline_ix < quote_ix {
16674                if first_newline_ix.is_none() {
16675                    first_newline_ix = Some(*newline_ix);
16676                }
16677                last_newline_ix = Some(*newline_ix);
16678
16679                if let Some(rows_left) = &mut max_message_rows {
16680                    if *rows_left == 0 {
16681                        break;
16682                    } else {
16683                        *rows_left -= 1;
16684                    }
16685                }
16686                let _ = newline_indices.next();
16687            } else {
16688                break;
16689            }
16690        }
16691        let prev_len = text_without_backticks.len();
16692        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16693        text_without_backticks.push_str(new_text);
16694        if in_code_block {
16695            code_ranges.push(prev_len..text_without_backticks.len());
16696        }
16697        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16698        in_code_block = !in_code_block;
16699        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16700            text_without_backticks.push_str("...");
16701            break;
16702        }
16703    }
16704
16705    (text_without_backticks.into(), code_ranges)
16706}
16707
16708fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16709    match severity {
16710        DiagnosticSeverity::ERROR => colors.error,
16711        DiagnosticSeverity::WARNING => colors.warning,
16712        DiagnosticSeverity::INFORMATION => colors.info,
16713        DiagnosticSeverity::HINT => colors.info,
16714        _ => colors.ignored,
16715    }
16716}
16717
16718pub fn styled_runs_for_code_label<'a>(
16719    label: &'a CodeLabel,
16720    syntax_theme: &'a theme::SyntaxTheme,
16721) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16722    let fade_out = HighlightStyle {
16723        fade_out: Some(0.35),
16724        ..Default::default()
16725    };
16726
16727    let mut prev_end = label.filter_range.end;
16728    label
16729        .runs
16730        .iter()
16731        .enumerate()
16732        .flat_map(move |(ix, (range, highlight_id))| {
16733            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16734                style
16735            } else {
16736                return Default::default();
16737            };
16738            let mut muted_style = style;
16739            muted_style.highlight(fade_out);
16740
16741            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16742            if range.start >= label.filter_range.end {
16743                if range.start > prev_end {
16744                    runs.push((prev_end..range.start, fade_out));
16745                }
16746                runs.push((range.clone(), muted_style));
16747            } else if range.end <= label.filter_range.end {
16748                runs.push((range.clone(), style));
16749            } else {
16750                runs.push((range.start..label.filter_range.end, style));
16751                runs.push((label.filter_range.end..range.end, muted_style));
16752            }
16753            prev_end = cmp::max(prev_end, range.end);
16754
16755            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16756                runs.push((prev_end..label.text.len(), fade_out));
16757            }
16758
16759            runs
16760        })
16761}
16762
16763pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16764    let mut prev_index = 0;
16765    let mut prev_codepoint: Option<char> = None;
16766    text.char_indices()
16767        .chain([(text.len(), '\0')])
16768        .filter_map(move |(index, codepoint)| {
16769            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16770            let is_boundary = index == text.len()
16771                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16772                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16773            if is_boundary {
16774                let chunk = &text[prev_index..index];
16775                prev_index = index;
16776                Some(chunk)
16777            } else {
16778                None
16779            }
16780        })
16781}
16782
16783pub trait RangeToAnchorExt: Sized {
16784    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16785
16786    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16787        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16788        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16789    }
16790}
16791
16792impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16793    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16794        let start_offset = self.start.to_offset(snapshot);
16795        let end_offset = self.end.to_offset(snapshot);
16796        if start_offset == end_offset {
16797            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16798        } else {
16799            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16800        }
16801    }
16802}
16803
16804pub trait RowExt {
16805    fn as_f32(&self) -> f32;
16806
16807    fn next_row(&self) -> Self;
16808
16809    fn previous_row(&self) -> Self;
16810
16811    fn minus(&self, other: Self) -> u32;
16812}
16813
16814impl RowExt for DisplayRow {
16815    fn as_f32(&self) -> f32 {
16816        self.0 as f32
16817    }
16818
16819    fn next_row(&self) -> Self {
16820        Self(self.0 + 1)
16821    }
16822
16823    fn previous_row(&self) -> Self {
16824        Self(self.0.saturating_sub(1))
16825    }
16826
16827    fn minus(&self, other: Self) -> u32 {
16828        self.0 - other.0
16829    }
16830}
16831
16832impl RowExt for MultiBufferRow {
16833    fn as_f32(&self) -> f32 {
16834        self.0 as f32
16835    }
16836
16837    fn next_row(&self) -> Self {
16838        Self(self.0 + 1)
16839    }
16840
16841    fn previous_row(&self) -> Self {
16842        Self(self.0.saturating_sub(1))
16843    }
16844
16845    fn minus(&self, other: Self) -> u32 {
16846        self.0 - other.0
16847    }
16848}
16849
16850trait RowRangeExt {
16851    type Row;
16852
16853    fn len(&self) -> usize;
16854
16855    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16856}
16857
16858impl RowRangeExt for Range<MultiBufferRow> {
16859    type Row = MultiBufferRow;
16860
16861    fn len(&self) -> usize {
16862        (self.end.0 - self.start.0) as usize
16863    }
16864
16865    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16866        (self.start.0..self.end.0).map(MultiBufferRow)
16867    }
16868}
16869
16870impl RowRangeExt for Range<DisplayRow> {
16871    type Row = DisplayRow;
16872
16873    fn len(&self) -> usize {
16874        (self.end.0 - self.start.0) as usize
16875    }
16876
16877    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16878        (self.start.0..self.end.0).map(DisplayRow)
16879    }
16880}
16881
16882/// If select range has more than one line, we
16883/// just point the cursor to range.start.
16884fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16885    if range.start.row == range.end.row {
16886        range
16887    } else {
16888        range.start..range.start
16889    }
16890}
16891pub struct KillRing(ClipboardItem);
16892impl Global for KillRing {}
16893
16894const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16895
16896fn all_edits_insertions_or_deletions(
16897    edits: &Vec<(Range<Anchor>, String)>,
16898    snapshot: &MultiBufferSnapshot,
16899) -> bool {
16900    let mut all_insertions = true;
16901    let mut all_deletions = true;
16902
16903    for (range, new_text) in edits.iter() {
16904        let range_is_empty = range.to_offset(&snapshot).is_empty();
16905        let text_is_empty = new_text.is_empty();
16906
16907        if range_is_empty != text_is_empty {
16908            if range_is_empty {
16909                all_deletions = false;
16910            } else {
16911                all_insertions = false;
16912            }
16913        } else {
16914            return false;
16915        }
16916
16917        if !all_insertions && !all_deletions {
16918            return false;
16919        }
16920    }
16921    all_insertions || all_deletions
16922}