editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use display_map::*;
   60pub use display_map::{DisplayPoint, FoldPlaceholder};
   61pub use editor_settings::{
   62    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   63};
   64pub use editor_settings_controls::*;
   65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   66pub use element::{
   67    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   68};
   69use futures::{future, FutureExt};
   70use fuzzy::StringMatchCandidate;
   71
   72use code_context_menus::{
   73    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   74    CompletionsMenu, ContextMenuOrigin,
   75};
   76use git::blame::GitBlame;
   77use gpui::{
   78    div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
   79    px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
   80    AvailableSpace, Background, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase,
   81    ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable,
   82    FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers,
   83    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size,
   84    Styled, StyledText, Subscription, Task, TextRun, TextStyle, TextStyleRefinement,
   85    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   86};
   87use highlight_matching_bracket::refresh_matching_bracket_highlights;
   88use hover_popover::{hide_hover, HoverState};
   89use indent_guides::ActiveIndentGuidesState;
   90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   91pub use inline_completion::Direction;
   92use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   93pub use items::MAX_TAB_TITLE_LEN;
   94use itertools::Itertools;
   95use language::{
   96    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   97    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   98    CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
   99    IndentSize, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
  100    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  101};
  102use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  103use linked_editing_ranges::refresh_linked_ranges;
  104use mouse_context_menu::MouseContextMenu;
  105pub use proposed_changes_editor::{
  106    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  107};
  108use similar::{ChangeTag, TextDiff};
  109use std::iter::Peekable;
  110use task::{ResolvedTask, TaskTemplate, TaskVariables};
  111
  112use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  113pub use lsp::CompletionContext;
  114use lsp::{
  115    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  116    LanguageServerId, LanguageServerName,
  117};
  118
  119use language::BufferSnapshot;
  120use movement::TextLayoutDetails;
  121pub use multi_buffer::{
  122    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  123    ToOffset, ToPoint,
  124};
  125use multi_buffer::{
  126    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  127    ToOffsetUtf16,
  128};
  129use project::{
  130    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  131    project_settings::{GitGutterSetting, ProjectSettings},
  132    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  133    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  134};
  135use rand::prelude::*;
  136use rpc::{proto::*, ErrorExt};
  137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  138use selections_collection::{
  139    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  140};
  141use serde::{Deserialize, Serialize};
  142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  143use smallvec::SmallVec;
  144use snippet::Snippet;
  145use std::{
  146    any::TypeId,
  147    borrow::Cow,
  148    cell::RefCell,
  149    cmp::{self, Ordering, Reverse},
  150    mem,
  151    num::NonZeroU32,
  152    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  153    path::{Path, PathBuf},
  154    rc::Rc,
  155    sync::Arc,
  156    time::{Duration, Instant},
  157};
  158pub use sum_tree::Bias;
  159use sum_tree::TreeMap;
  160use text::{BufferId, OffsetUtf16, Rope};
  161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::{find_url, find_url_from_range};
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188
  189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  191
  192pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  193pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
  194    "edit_prediction_requires_modifier";
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakEntity<Workspace>>,
  201    cx: &mut App,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(
  246        link_ranges,
  247        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace
  253                            .open_abs_path(path.clone(), false, window, cx)
  254                            .detach();
  255                    });
  256                }
  257            }
  258        },
  259    )
  260}
  261
  262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  263pub enum InlayId {
  264    InlineCompletion(usize),
  265    Hint(usize),
  266}
  267
  268impl InlayId {
  269    fn id(&self) -> usize {
  270        match self {
  271            Self::InlineCompletion(id) => *id,
  272            Self::Hint(id) => *id,
  273        }
  274    }
  275}
  276
  277enum DocumentHighlightRead {}
  278enum DocumentHighlightWrite {}
  279enum InputComposition {}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut App) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut App) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new(
  309        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313            workspace.register_action(Editor::cancel_language_server_work);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(
  322                Default::default(),
  323                app_state,
  324                cx,
  325                |workspace, window, cx| {
  326                    Editor::new_file(workspace, &Default::default(), window, cx)
  327                },
  328            )
  329            .detach();
  330        }
  331    });
  332    cx.on_action(move |_: &workspace::NewWindow, cx| {
  333        let app_state = workspace::AppState::global(cx);
  334        if let Some(app_state) = app_state.upgrade() {
  335            workspace::open_new(
  336                Default::default(),
  337                app_state,
  338                cx,
  339                |workspace, window, cx| {
  340                    cx.activate(true);
  341                    Editor::new_file(workspace, &Default::default(), window, cx)
  342                },
  343            )
  344            .detach();
  345        }
  346    });
  347}
  348
  349pub struct SearchWithinRange;
  350
  351trait InvalidationRegion {
  352    fn ranges(&self) -> &[Range<Anchor>];
  353}
  354
  355#[derive(Clone, Debug, PartialEq)]
  356pub enum SelectPhase {
  357    Begin {
  358        position: DisplayPoint,
  359        add: bool,
  360        click_count: usize,
  361    },
  362    BeginColumnar {
  363        position: DisplayPoint,
  364        reset: bool,
  365        goal_column: u32,
  366    },
  367    Extend {
  368        position: DisplayPoint,
  369        click_count: usize,
  370    },
  371    Update {
  372        position: DisplayPoint,
  373        goal_column: u32,
  374        scroll_delta: gpui::Point<f32>,
  375    },
  376    End,
  377}
  378
  379#[derive(Clone, Debug)]
  380pub enum SelectMode {
  381    Character,
  382    Word(Range<Anchor>),
  383    Line(Range<Anchor>),
  384    All,
  385}
  386
  387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  388pub enum EditorMode {
  389    SingleLine { auto_width: bool },
  390    AutoHeight { max_lines: usize },
  391    Full,
  392}
  393
  394#[derive(Copy, Clone, Debug)]
  395pub enum SoftWrap {
  396    /// Prefer not to wrap at all.
  397    ///
  398    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  399    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  400    GitDiff,
  401    /// Prefer a single line generally, unless an overly long line is encountered.
  402    None,
  403    /// Soft wrap lines that exceed the editor width.
  404    EditorWidth,
  405    /// Soft wrap lines at the preferred line length.
  406    Column(u32),
  407    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  408    Bounded(u32),
  409}
  410
  411#[derive(Clone)]
  412pub struct EditorStyle {
  413    pub background: Hsla,
  414    pub local_player: PlayerColor,
  415    pub text: TextStyle,
  416    pub scrollbar_width: Pixels,
  417    pub syntax: Arc<SyntaxTheme>,
  418    pub status: StatusColors,
  419    pub inlay_hints_style: HighlightStyle,
  420    pub inline_completion_styles: InlineCompletionStyles,
  421    pub unnecessary_code_fade: f32,
  422}
  423
  424impl Default for EditorStyle {
  425    fn default() -> Self {
  426        Self {
  427            background: Hsla::default(),
  428            local_player: PlayerColor::default(),
  429            text: TextStyle::default(),
  430            scrollbar_width: Pixels::default(),
  431            syntax: Default::default(),
  432            // HACK: Status colors don't have a real default.
  433            // We should look into removing the status colors from the editor
  434            // style and retrieve them directly from the theme.
  435            status: StatusColors::dark(),
  436            inlay_hints_style: HighlightStyle::default(),
  437            inline_completion_styles: InlineCompletionStyles {
  438                insertion: HighlightStyle::default(),
  439                whitespace: HighlightStyle::default(),
  440            },
  441            unnecessary_code_fade: Default::default(),
  442        }
  443    }
  444}
  445
  446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  447    let show_background = language_settings::language_settings(None, None, cx)
  448        .inlay_hints
  449        .show_background;
  450
  451    HighlightStyle {
  452        color: Some(cx.theme().status().hint),
  453        background_color: show_background.then(|| cx.theme().status().hint_background),
  454        ..HighlightStyle::default()
  455    }
  456}
  457
  458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  459    InlineCompletionStyles {
  460        insertion: HighlightStyle {
  461            color: Some(cx.theme().status().predictive),
  462            ..HighlightStyle::default()
  463        },
  464        whitespace: HighlightStyle {
  465            background_color: Some(cx.theme().status().created_background),
  466            ..HighlightStyle::default()
  467        },
  468    }
  469}
  470
  471type CompletionId = usize;
  472
  473pub(crate) enum EditDisplayMode {
  474    TabAccept,
  475    DiffPopover,
  476    Inline,
  477}
  478
  479enum InlineCompletion {
  480    Edit {
  481        edits: Vec<(Range<Anchor>, String)>,
  482        edit_preview: Option<EditPreview>,
  483        display_mode: EditDisplayMode,
  484        snapshot: BufferSnapshot,
  485    },
  486    Move {
  487        target: Anchor,
  488        range_around_target: Range<text::Anchor>,
  489        snapshot: BufferSnapshot,
  490    },
  491}
  492
  493struct InlineCompletionState {
  494    inlay_ids: Vec<InlayId>,
  495    completion: InlineCompletion,
  496    completion_id: Option<SharedString>,
  497    invalidation_range: Range<Anchor>,
  498}
  499
  500enum 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
  524#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  525struct EditorActionId(usize);
  526
  527impl EditorActionId {
  528    pub fn post_inc(&mut self) -> Self {
  529        let answer = self.0;
  530
  531        *self = Self(answer + 1);
  532
  533        Self(answer)
  534    }
  535}
  536
  537// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  538// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  539
  540type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  541type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  542
  543#[derive(Default)]
  544struct ScrollbarMarkerState {
  545    scrollbar_size: Size<Pixels>,
  546    dirty: bool,
  547    markers: Arc<[PaintQuad]>,
  548    pending_refresh: Option<Task<Result<()>>>,
  549}
  550
  551impl ScrollbarMarkerState {
  552    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  553        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  554    }
  555}
  556
  557#[derive(Clone, Debug)]
  558struct RunnableTasks {
  559    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  560    offset: MultiBufferOffset,
  561    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  562    column: u32,
  563    // Values of all named captures, including those starting with '_'
  564    extra_variables: HashMap<String, String>,
  565    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  566    context_range: Range<BufferOffset>,
  567}
  568
  569impl RunnableTasks {
  570    fn resolve<'a>(
  571        &'a self,
  572        cx: &'a task::TaskContext,
  573    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  574        self.templates.iter().filter_map(|(kind, template)| {
  575            template
  576                .resolve_task(&kind.to_id_base(), cx)
  577                .map(|task| (kind.clone(), task))
  578        })
  579    }
  580}
  581
  582#[derive(Clone)]
  583struct ResolvedTasks {
  584    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  585    position: Anchor,
  586}
  587#[derive(Copy, Clone, Debug)]
  588struct MultiBufferOffset(usize);
  589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  590struct BufferOffset(usize);
  591
  592// Addons allow storing per-editor state in other crates (e.g. Vim)
  593pub trait Addon: 'static {
  594    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  595
  596    fn render_buffer_header_controls(
  597        &self,
  598        _: &ExcerptInfo,
  599        _: &Window,
  600        _: &App,
  601    ) -> Option<AnyElement> {
  602        None
  603    }
  604
  605    fn to_any(&self) -> &dyn std::any::Any;
  606}
  607
  608#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  609pub enum IsVimMode {
  610    Yes,
  611    No,
  612}
  613
  614/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  615///
  616/// See the [module level documentation](self) for more information.
  617pub struct Editor {
  618    focus_handle: FocusHandle,
  619    last_focused_descendant: Option<WeakFocusHandle>,
  620    /// The text buffer being edited
  621    buffer: Entity<MultiBuffer>,
  622    /// Map of how text in the buffer should be displayed.
  623    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  624    pub display_map: Entity<DisplayMap>,
  625    pub selections: SelectionsCollection,
  626    pub scroll_manager: ScrollManager,
  627    /// When inline assist editors are linked, they all render cursors because
  628    /// typing enters text into each of them, even the ones that aren't focused.
  629    pub(crate) show_cursor_when_unfocused: bool,
  630    columnar_selection_tail: Option<Anchor>,
  631    add_selections_state: Option<AddSelectionsState>,
  632    select_next_state: Option<SelectNextState>,
  633    select_prev_state: Option<SelectNextState>,
  634    selection_history: SelectionHistory,
  635    autoclose_regions: Vec<AutocloseRegion>,
  636    snippet_stack: InvalidationStack<SnippetState>,
  637    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  638    ime_transaction: Option<TransactionId>,
  639    active_diagnostics: Option<ActiveDiagnosticGroup>,
  640    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  641
  642    // TODO: make this a access method
  643    pub project: Option<Entity<Project>>,
  644    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  645    completion_provider: Option<Box<dyn CompletionProvider>>,
  646    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  647    blink_manager: Entity<BlinkManager>,
  648    show_cursor_names: bool,
  649    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  650    pub show_local_selections: bool,
  651    mode: EditorMode,
  652    show_breadcrumbs: bool,
  653    show_gutter: bool,
  654    show_scrollbars: bool,
  655    show_line_numbers: Option<bool>,
  656    use_relative_line_numbers: Option<bool>,
  657    show_git_diff_gutter: Option<bool>,
  658    show_code_actions: Option<bool>,
  659    show_runnables: Option<bool>,
  660    show_wrap_guides: Option<bool>,
  661    show_indent_guides: Option<bool>,
  662    placeholder_text: Option<Arc<str>>,
  663    highlight_order: usize,
  664    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  665    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  666    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  667    scrollbar_marker_state: ScrollbarMarkerState,
  668    active_indent_guides_state: ActiveIndentGuidesState,
  669    nav_history: Option<ItemNavHistory>,
  670    context_menu: RefCell<Option<CodeContextMenu>>,
  671    mouse_context_menu: Option<MouseContextMenu>,
  672    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  673    signature_help_state: SignatureHelpState,
  674    auto_signature_help: Option<bool>,
  675    find_all_references_task_sources: Vec<Anchor>,
  676    next_completion_id: CompletionId,
  677    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  678    code_actions_task: Option<Task<Result<()>>>,
  679    document_highlights_task: Option<Task<()>>,
  680    linked_editing_range_task: Option<Task<Option<()>>>,
  681    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  682    pending_rename: Option<RenameState>,
  683    searchable: bool,
  684    cursor_shape: CursorShape,
  685    current_line_highlight: Option<CurrentLineHighlight>,
  686    collapse_matches: bool,
  687    autoindent_mode: Option<AutoindentMode>,
  688    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  689    input_enabled: bool,
  690    use_modal_editing: bool,
  691    read_only: bool,
  692    leader_peer_id: Option<PeerId>,
  693    remote_id: Option<ViewId>,
  694    hover_state: HoverState,
  695    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  696    gutter_hovered: bool,
  697    hovered_link_state: Option<HoveredLinkState>,
  698    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  699    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  700    active_inline_completion: Option<InlineCompletionState>,
  701    /// Used to prevent flickering as the user types while the menu is open
  702    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  703    edit_prediction_settings: EditPredictionSettings,
  704    inline_completions_hidden_for_vim_mode: bool,
  705    show_inline_completions_override: Option<bool>,
  706    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  707    previewing_inline_completion: bool,
  708    inlay_hint_cache: InlayHintCache,
  709    next_inlay_id: usize,
  710    _subscriptions: Vec<Subscription>,
  711    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  712    gutter_dimensions: GutterDimensions,
  713    style: Option<EditorStyle>,
  714    text_style_refinement: Option<TextStyleRefinement>,
  715    next_editor_action_id: EditorActionId,
  716    editor_actions:
  717        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  718    use_autoclose: bool,
  719    use_auto_surround: bool,
  720    auto_replace_emoji_shortcode: bool,
  721    show_git_blame_gutter: bool,
  722    show_git_blame_inline: bool,
  723    show_git_blame_inline_delay_task: Option<Task<()>>,
  724    distinguish_unstaged_diff_hunks: bool,
  725    git_blame_inline_enabled: bool,
  726    serialize_dirty_buffers: bool,
  727    show_selection_menu: Option<bool>,
  728    blame: Option<Entity<GitBlame>>,
  729    blame_subscription: Option<Subscription>,
  730    custom_context_menu: Option<
  731        Box<
  732            dyn 'static
  733                + Fn(
  734                    &mut Self,
  735                    DisplayPoint,
  736                    &mut Window,
  737                    &mut Context<Self>,
  738                ) -> Option<Entity<ui::ContextMenu>>,
  739        >,
  740    >,
  741    last_bounds: Option<Bounds<Pixels>>,
  742    last_position_map: Option<Rc<PositionMap>>,
  743    expect_bounds_change: Option<Bounds<Pixels>>,
  744    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  745    tasks_update_task: Option<Task<()>>,
  746    in_project_search: bool,
  747    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  748    breadcrumb_header: Option<String>,
  749    focused_block: Option<FocusedBlock>,
  750    next_scroll_position: NextScrollCursorCenterTopBottom,
  751    addons: HashMap<TypeId, Box<dyn Addon>>,
  752    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  753    selection_mark_mode: bool,
  754    toggle_fold_multiple_buffers: Task<()>,
  755    _scroll_cursor_center_top_bottom_task: Task<()>,
  756}
  757
  758#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  759enum NextScrollCursorCenterTopBottom {
  760    #[default]
  761    Center,
  762    Top,
  763    Bottom,
  764}
  765
  766impl NextScrollCursorCenterTopBottom {
  767    fn next(&self) -> Self {
  768        match self {
  769            Self::Center => Self::Top,
  770            Self::Top => Self::Bottom,
  771            Self::Bottom => Self::Center,
  772        }
  773    }
  774}
  775
  776#[derive(Clone)]
  777pub struct EditorSnapshot {
  778    pub mode: EditorMode,
  779    show_gutter: bool,
  780    show_line_numbers: Option<bool>,
  781    show_git_diff_gutter: Option<bool>,
  782    show_code_actions: Option<bool>,
  783    show_runnables: Option<bool>,
  784    git_blame_gutter_max_author_length: Option<usize>,
  785    pub display_snapshot: DisplaySnapshot,
  786    pub placeholder_text: Option<Arc<str>>,
  787    is_focused: bool,
  788    scroll_anchor: ScrollAnchor,
  789    ongoing_scroll: OngoingScroll,
  790    current_line_highlight: CurrentLineHighlight,
  791    gutter_hovered: bool,
  792}
  793
  794const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  795
  796#[derive(Default, Debug, Clone, Copy)]
  797pub struct GutterDimensions {
  798    pub left_padding: Pixels,
  799    pub right_padding: Pixels,
  800    pub width: Pixels,
  801    pub margin: Pixels,
  802    pub git_blame_entries_width: Option<Pixels>,
  803}
  804
  805impl GutterDimensions {
  806    /// The full width of the space taken up by the gutter.
  807    pub fn full_width(&self) -> Pixels {
  808        self.margin + self.width
  809    }
  810
  811    /// The width of the space reserved for the fold indicators,
  812    /// use alongside 'justify_end' and `gutter_width` to
  813    /// right align content with the line numbers
  814    pub fn fold_area_width(&self) -> Pixels {
  815        self.margin + self.right_padding
  816    }
  817}
  818
  819#[derive(Debug)]
  820pub struct RemoteSelection {
  821    pub replica_id: ReplicaId,
  822    pub selection: Selection<Anchor>,
  823    pub cursor_shape: CursorShape,
  824    pub peer_id: PeerId,
  825    pub line_mode: bool,
  826    pub participant_index: Option<ParticipantIndex>,
  827    pub user_name: Option<SharedString>,
  828}
  829
  830#[derive(Clone, Debug)]
  831struct SelectionHistoryEntry {
  832    selections: Arc<[Selection<Anchor>]>,
  833    select_next_state: Option<SelectNextState>,
  834    select_prev_state: Option<SelectNextState>,
  835    add_selections_state: Option<AddSelectionsState>,
  836}
  837
  838enum SelectionHistoryMode {
  839    Normal,
  840    Undoing,
  841    Redoing,
  842}
  843
  844#[derive(Clone, PartialEq, Eq, Hash)]
  845struct HoveredCursor {
  846    replica_id: u16,
  847    selection_id: usize,
  848}
  849
  850impl Default for SelectionHistoryMode {
  851    fn default() -> Self {
  852        Self::Normal
  853    }
  854}
  855
  856#[derive(Default)]
  857struct SelectionHistory {
  858    #[allow(clippy::type_complexity)]
  859    selections_by_transaction:
  860        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  861    mode: SelectionHistoryMode,
  862    undo_stack: VecDeque<SelectionHistoryEntry>,
  863    redo_stack: VecDeque<SelectionHistoryEntry>,
  864}
  865
  866impl SelectionHistory {
  867    fn insert_transaction(
  868        &mut self,
  869        transaction_id: TransactionId,
  870        selections: Arc<[Selection<Anchor>]>,
  871    ) {
  872        self.selections_by_transaction
  873            .insert(transaction_id, (selections, None));
  874    }
  875
  876    #[allow(clippy::type_complexity)]
  877    fn transaction(
  878        &self,
  879        transaction_id: TransactionId,
  880    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  881        self.selections_by_transaction.get(&transaction_id)
  882    }
  883
  884    #[allow(clippy::type_complexity)]
  885    fn transaction_mut(
  886        &mut self,
  887        transaction_id: TransactionId,
  888    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  889        self.selections_by_transaction.get_mut(&transaction_id)
  890    }
  891
  892    fn push(&mut self, entry: SelectionHistoryEntry) {
  893        if !entry.selections.is_empty() {
  894            match self.mode {
  895                SelectionHistoryMode::Normal => {
  896                    self.push_undo(entry);
  897                    self.redo_stack.clear();
  898                }
  899                SelectionHistoryMode::Undoing => self.push_redo(entry),
  900                SelectionHistoryMode::Redoing => self.push_undo(entry),
  901            }
  902        }
  903    }
  904
  905    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  906        if self
  907            .undo_stack
  908            .back()
  909            .map_or(true, |e| e.selections != entry.selections)
  910        {
  911            self.undo_stack.push_back(entry);
  912            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  913                self.undo_stack.pop_front();
  914            }
  915        }
  916    }
  917
  918    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  919        if self
  920            .redo_stack
  921            .back()
  922            .map_or(true, |e| e.selections != entry.selections)
  923        {
  924            self.redo_stack.push_back(entry);
  925            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  926                self.redo_stack.pop_front();
  927            }
  928        }
  929    }
  930}
  931
  932struct RowHighlight {
  933    index: usize,
  934    range: Range<Anchor>,
  935    color: Hsla,
  936    should_autoscroll: bool,
  937}
  938
  939#[derive(Clone, Debug)]
  940struct AddSelectionsState {
  941    above: bool,
  942    stack: Vec<usize>,
  943}
  944
  945#[derive(Clone)]
  946struct SelectNextState {
  947    query: AhoCorasick,
  948    wordwise: bool,
  949    done: bool,
  950}
  951
  952impl std::fmt::Debug for SelectNextState {
  953    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  954        f.debug_struct(std::any::type_name::<Self>())
  955            .field("wordwise", &self.wordwise)
  956            .field("done", &self.done)
  957            .finish()
  958    }
  959}
  960
  961#[derive(Debug)]
  962struct AutocloseRegion {
  963    selection_id: usize,
  964    range: Range<Anchor>,
  965    pair: BracketPair,
  966}
  967
  968#[derive(Debug)]
  969struct SnippetState {
  970    ranges: Vec<Vec<Range<Anchor>>>,
  971    active_index: usize,
  972    choices: Vec<Option<Vec<String>>>,
  973}
  974
  975#[doc(hidden)]
  976pub struct RenameState {
  977    pub range: Range<Anchor>,
  978    pub old_name: Arc<str>,
  979    pub editor: Entity<Editor>,
  980    block_id: CustomBlockId,
  981}
  982
  983struct InvalidationStack<T>(Vec<T>);
  984
  985struct RegisteredInlineCompletionProvider {
  986    provider: Arc<dyn InlineCompletionProviderHandle>,
  987    _subscription: Subscription,
  988}
  989
  990#[derive(Debug)]
  991struct ActiveDiagnosticGroup {
  992    primary_range: Range<Anchor>,
  993    primary_message: String,
  994    group_id: usize,
  995    blocks: HashMap<CustomBlockId, Diagnostic>,
  996    is_valid: bool,
  997}
  998
  999#[derive(Serialize, Deserialize, Clone, Debug)]
 1000pub struct ClipboardSelection {
 1001    pub len: usize,
 1002    pub is_entire_line: bool,
 1003    pub first_line_indent: u32,
 1004}
 1005
 1006#[derive(Debug)]
 1007pub(crate) struct NavigationData {
 1008    cursor_anchor: Anchor,
 1009    cursor_position: Point,
 1010    scroll_anchor: ScrollAnchor,
 1011    scroll_top_row: u32,
 1012}
 1013
 1014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1015pub enum GotoDefinitionKind {
 1016    Symbol,
 1017    Declaration,
 1018    Type,
 1019    Implementation,
 1020}
 1021
 1022#[derive(Debug, Clone)]
 1023enum InlayHintRefreshReason {
 1024    Toggle(bool),
 1025    SettingsChange(InlayHintSettings),
 1026    NewLinesShown,
 1027    BufferEdited(HashSet<Arc<Language>>),
 1028    RefreshRequested,
 1029    ExcerptsRemoved(Vec<ExcerptId>),
 1030}
 1031
 1032impl InlayHintRefreshReason {
 1033    fn description(&self) -> &'static str {
 1034        match self {
 1035            Self::Toggle(_) => "toggle",
 1036            Self::SettingsChange(_) => "settings change",
 1037            Self::NewLinesShown => "new lines shown",
 1038            Self::BufferEdited(_) => "buffer edited",
 1039            Self::RefreshRequested => "refresh requested",
 1040            Self::ExcerptsRemoved(_) => "excerpts removed",
 1041        }
 1042    }
 1043}
 1044
 1045pub enum FormatTarget {
 1046    Buffers,
 1047    Ranges(Vec<Range<MultiBufferPoint>>),
 1048}
 1049
 1050pub(crate) struct FocusedBlock {
 1051    id: BlockId,
 1052    focus_handle: WeakFocusHandle,
 1053}
 1054
 1055#[derive(Clone)]
 1056enum JumpData {
 1057    MultiBufferRow {
 1058        row: MultiBufferRow,
 1059        line_offset_from_top: u32,
 1060    },
 1061    MultiBufferPoint {
 1062        excerpt_id: ExcerptId,
 1063        position: Point,
 1064        anchor: text::Anchor,
 1065        line_offset_from_top: u32,
 1066    },
 1067}
 1068
 1069pub enum MultibufferSelectionMode {
 1070    First,
 1071    All,
 1072}
 1073
 1074impl Editor {
 1075    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1076        let buffer = cx.new(|cx| Buffer::local("", cx));
 1077        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1078        Self::new(
 1079            EditorMode::SingleLine { auto_width: false },
 1080            buffer,
 1081            None,
 1082            false,
 1083            window,
 1084            cx,
 1085        )
 1086    }
 1087
 1088    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1089        let buffer = cx.new(|cx| Buffer::local("", cx));
 1090        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1091        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1092    }
 1093
 1094    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1095        let buffer = cx.new(|cx| Buffer::local("", cx));
 1096        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1097        Self::new(
 1098            EditorMode::SingleLine { auto_width: true },
 1099            buffer,
 1100            None,
 1101            false,
 1102            window,
 1103            cx,
 1104        )
 1105    }
 1106
 1107    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1108        let buffer = cx.new(|cx| Buffer::local("", cx));
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(
 1111            EditorMode::AutoHeight { max_lines },
 1112            buffer,
 1113            None,
 1114            false,
 1115            window,
 1116            cx,
 1117        )
 1118    }
 1119
 1120    pub fn for_buffer(
 1121        buffer: Entity<Buffer>,
 1122        project: Option<Entity<Project>>,
 1123        window: &mut Window,
 1124        cx: &mut Context<Self>,
 1125    ) -> Self {
 1126        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1127        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1128    }
 1129
 1130    pub fn for_multibuffer(
 1131        buffer: Entity<MultiBuffer>,
 1132        project: Option<Entity<Project>>,
 1133        show_excerpt_controls: bool,
 1134        window: &mut Window,
 1135        cx: &mut Context<Self>,
 1136    ) -> Self {
 1137        Self::new(
 1138            EditorMode::Full,
 1139            buffer,
 1140            project,
 1141            show_excerpt_controls,
 1142            window,
 1143            cx,
 1144        )
 1145    }
 1146
 1147    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1148        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1149        let mut clone = Self::new(
 1150            self.mode,
 1151            self.buffer.clone(),
 1152            self.project.clone(),
 1153            show_excerpt_controls,
 1154            window,
 1155            cx,
 1156        );
 1157        self.display_map.update(cx, |display_map, cx| {
 1158            let snapshot = display_map.snapshot(cx);
 1159            clone.display_map.update(cx, |display_map, cx| {
 1160                display_map.set_state(&snapshot, cx);
 1161            });
 1162        });
 1163        clone.selections.clone_state(&self.selections);
 1164        clone.scroll_manager.clone_state(&self.scroll_manager);
 1165        clone.searchable = self.searchable;
 1166        clone
 1167    }
 1168
 1169    pub fn new(
 1170        mode: EditorMode,
 1171        buffer: Entity<MultiBuffer>,
 1172        project: Option<Entity<Project>>,
 1173        show_excerpt_controls: bool,
 1174        window: &mut Window,
 1175        cx: &mut Context<Self>,
 1176    ) -> Self {
 1177        let style = window.text_style();
 1178        let font_size = style.font_size.to_pixels(window.rem_size());
 1179        let editor = cx.entity().downgrade();
 1180        let fold_placeholder = FoldPlaceholder {
 1181            constrain_width: true,
 1182            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1183                let editor = editor.clone();
 1184                div()
 1185                    .id(fold_id)
 1186                    .bg(cx.theme().colors().ghost_element_background)
 1187                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1188                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1189                    .rounded_sm()
 1190                    .size_full()
 1191                    .cursor_pointer()
 1192                    .child("")
 1193                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1194                    .on_click(move |_, _window, cx| {
 1195                        editor
 1196                            .update(cx, |editor, cx| {
 1197                                editor.unfold_ranges(
 1198                                    &[fold_range.start..fold_range.end],
 1199                                    true,
 1200                                    false,
 1201                                    cx,
 1202                                );
 1203                                cx.stop_propagation();
 1204                            })
 1205                            .ok();
 1206                    })
 1207                    .into_any()
 1208            }),
 1209            merge_adjacent: true,
 1210            ..Default::default()
 1211        };
 1212        let display_map = cx.new(|cx| {
 1213            DisplayMap::new(
 1214                buffer.clone(),
 1215                style.font(),
 1216                font_size,
 1217                None,
 1218                show_excerpt_controls,
 1219                FILE_HEADER_HEIGHT,
 1220                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1221                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1222                fold_placeholder,
 1223                cx,
 1224            )
 1225        });
 1226
 1227        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1228
 1229        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1230
 1231        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1232            .then(|| language_settings::SoftWrap::None);
 1233
 1234        let mut project_subscriptions = Vec::new();
 1235        if mode == EditorMode::Full {
 1236            if let Some(project) = project.as_ref() {
 1237                if buffer.read(cx).is_singleton() {
 1238                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1239                        cx.emit(EditorEvent::TitleChanged);
 1240                    }));
 1241                }
 1242                project_subscriptions.push(cx.subscribe_in(
 1243                    project,
 1244                    window,
 1245                    |editor, _, event, window, cx| {
 1246                        if let project::Event::RefreshInlayHints = event {
 1247                            editor
 1248                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1249                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1250                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1251                                let focus_handle = editor.focus_handle(cx);
 1252                                if focus_handle.is_focused(window) {
 1253                                    let snapshot = buffer.read(cx).snapshot();
 1254                                    for (range, snippet) in snippet_edits {
 1255                                        let editor_range =
 1256                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1257                                        editor
 1258                                            .insert_snippet(
 1259                                                &[editor_range],
 1260                                                snippet.clone(),
 1261                                                window,
 1262                                                cx,
 1263                                            )
 1264                                            .ok();
 1265                                    }
 1266                                }
 1267                            }
 1268                        }
 1269                    },
 1270                ));
 1271                if let Some(task_inventory) = project
 1272                    .read(cx)
 1273                    .task_store()
 1274                    .read(cx)
 1275                    .task_inventory()
 1276                    .cloned()
 1277                {
 1278                    project_subscriptions.push(cx.observe_in(
 1279                        &task_inventory,
 1280                        window,
 1281                        |editor, _, window, cx| {
 1282                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1283                        },
 1284                    ));
 1285                }
 1286            }
 1287        }
 1288
 1289        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1290
 1291        let inlay_hint_settings =
 1292            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1293        let focus_handle = cx.focus_handle();
 1294        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1295            .detach();
 1296        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1297            .detach();
 1298        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1299            .detach();
 1300        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1301            .detach();
 1302
 1303        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1304            Some(false)
 1305        } else {
 1306            None
 1307        };
 1308
 1309        let mut code_action_providers = Vec::new();
 1310        if let Some(project) = project.clone() {
 1311            get_uncommitted_diff_for_buffer(
 1312                &project,
 1313                buffer.read(cx).all_buffers(),
 1314                buffer.clone(),
 1315                cx,
 1316            );
 1317            code_action_providers.push(Rc::new(project) as Rc<_>);
 1318        }
 1319
 1320        let mut this = Self {
 1321            focus_handle,
 1322            show_cursor_when_unfocused: false,
 1323            last_focused_descendant: None,
 1324            buffer: buffer.clone(),
 1325            display_map: display_map.clone(),
 1326            selections,
 1327            scroll_manager: ScrollManager::new(cx),
 1328            columnar_selection_tail: None,
 1329            add_selections_state: None,
 1330            select_next_state: None,
 1331            select_prev_state: None,
 1332            selection_history: Default::default(),
 1333            autoclose_regions: Default::default(),
 1334            snippet_stack: Default::default(),
 1335            select_larger_syntax_node_stack: Vec::new(),
 1336            ime_transaction: Default::default(),
 1337            active_diagnostics: None,
 1338            soft_wrap_mode_override,
 1339            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1340            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1341            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1342            project,
 1343            blink_manager: blink_manager.clone(),
 1344            show_local_selections: true,
 1345            show_scrollbars: true,
 1346            mode,
 1347            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1348            show_gutter: mode == EditorMode::Full,
 1349            show_line_numbers: None,
 1350            use_relative_line_numbers: None,
 1351            show_git_diff_gutter: None,
 1352            show_code_actions: None,
 1353            show_runnables: None,
 1354            show_wrap_guides: None,
 1355            show_indent_guides,
 1356            placeholder_text: None,
 1357            highlight_order: 0,
 1358            highlighted_rows: HashMap::default(),
 1359            background_highlights: Default::default(),
 1360            gutter_highlights: TreeMap::default(),
 1361            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1362            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1363            nav_history: None,
 1364            context_menu: RefCell::new(None),
 1365            mouse_context_menu: None,
 1366            completion_tasks: Default::default(),
 1367            signature_help_state: SignatureHelpState::default(),
 1368            auto_signature_help: None,
 1369            find_all_references_task_sources: Vec::new(),
 1370            next_completion_id: 0,
 1371            next_inlay_id: 0,
 1372            code_action_providers,
 1373            available_code_actions: Default::default(),
 1374            code_actions_task: Default::default(),
 1375            document_highlights_task: Default::default(),
 1376            linked_editing_range_task: Default::default(),
 1377            pending_rename: Default::default(),
 1378            searchable: true,
 1379            cursor_shape: EditorSettings::get_global(cx)
 1380                .cursor_shape
 1381                .unwrap_or_default(),
 1382            current_line_highlight: None,
 1383            autoindent_mode: Some(AutoindentMode::EachLine),
 1384            collapse_matches: false,
 1385            workspace: None,
 1386            input_enabled: true,
 1387            use_modal_editing: mode == EditorMode::Full,
 1388            read_only: false,
 1389            use_autoclose: true,
 1390            use_auto_surround: true,
 1391            auto_replace_emoji_shortcode: false,
 1392            leader_peer_id: None,
 1393            remote_id: None,
 1394            hover_state: Default::default(),
 1395            pending_mouse_down: None,
 1396            hovered_link_state: Default::default(),
 1397            edit_prediction_provider: None,
 1398            active_inline_completion: None,
 1399            stale_inline_completion_in_menu: None,
 1400            previewing_inline_completion: false,
 1401            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1402
 1403            gutter_hovered: false,
 1404            pixel_position_of_newest_cursor: None,
 1405            last_bounds: None,
 1406            last_position_map: None,
 1407            expect_bounds_change: None,
 1408            gutter_dimensions: GutterDimensions::default(),
 1409            style: None,
 1410            show_cursor_names: false,
 1411            hovered_cursors: Default::default(),
 1412            next_editor_action_id: EditorActionId::default(),
 1413            editor_actions: Rc::default(),
 1414            inline_completions_hidden_for_vim_mode: false,
 1415            show_inline_completions_override: None,
 1416            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1417            edit_prediction_settings: EditPredictionSettings::Disabled,
 1418            custom_context_menu: None,
 1419            show_git_blame_gutter: false,
 1420            show_git_blame_inline: false,
 1421            distinguish_unstaged_diff_hunks: false,
 1422            show_selection_menu: None,
 1423            show_git_blame_inline_delay_task: None,
 1424            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1425            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1426                .session
 1427                .restore_unsaved_buffers,
 1428            blame: None,
 1429            blame_subscription: None,
 1430            tasks: Default::default(),
 1431            _subscriptions: vec![
 1432                cx.observe(&buffer, Self::on_buffer_changed),
 1433                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1434                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1435                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1436                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1437                cx.observe_window_activation(window, |editor, window, cx| {
 1438                    let active = window.is_window_active();
 1439                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1440                        if active {
 1441                            blink_manager.enable(cx);
 1442                        } else {
 1443                            blink_manager.disable(cx);
 1444                        }
 1445                    });
 1446                }),
 1447            ],
 1448            tasks_update_task: None,
 1449            linked_edit_ranges: Default::default(),
 1450            in_project_search: false,
 1451            previous_search_ranges: None,
 1452            breadcrumb_header: None,
 1453            focused_block: None,
 1454            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1455            addons: HashMap::default(),
 1456            registered_buffers: HashMap::default(),
 1457            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1458            selection_mark_mode: false,
 1459            toggle_fold_multiple_buffers: Task::ready(()),
 1460            text_style_refinement: None,
 1461        };
 1462        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1463        this._subscriptions.extend(project_subscriptions);
 1464
 1465        this.end_selection(window, cx);
 1466        this.scroll_manager.show_scrollbar(window, cx);
 1467
 1468        if mode == EditorMode::Full {
 1469            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1470            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1471
 1472            if this.git_blame_inline_enabled {
 1473                this.git_blame_inline_enabled = true;
 1474                this.start_git_blame_inline(false, window, cx);
 1475            }
 1476
 1477            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1478                if let Some(project) = this.project.as_ref() {
 1479                    let lsp_store = project.read(cx).lsp_store();
 1480                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1481                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1482                    });
 1483                    this.registered_buffers
 1484                        .insert(buffer.read(cx).remote_id(), handle);
 1485                }
 1486            }
 1487        }
 1488
 1489        this.report_editor_event("Editor Opened", None, cx);
 1490        this
 1491    }
 1492
 1493    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1494        self.mouse_context_menu
 1495            .as_ref()
 1496            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1497    }
 1498
 1499    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1500        let mut key_context = KeyContext::new_with_defaults();
 1501        key_context.add("Editor");
 1502        let mode = match self.mode {
 1503            EditorMode::SingleLine { .. } => "single_line",
 1504            EditorMode::AutoHeight { .. } => "auto_height",
 1505            EditorMode::Full => "full",
 1506        };
 1507
 1508        if EditorSettings::jupyter_enabled(cx) {
 1509            key_context.add("jupyter");
 1510        }
 1511
 1512        key_context.set("mode", mode);
 1513        if self.pending_rename.is_some() {
 1514            key_context.add("renaming");
 1515        }
 1516
 1517        let mut showing_completions = false;
 1518
 1519        match self.context_menu.borrow().as_ref() {
 1520            Some(CodeContextMenu::Completions(_)) => {
 1521                key_context.add("menu");
 1522                key_context.add("showing_completions");
 1523                showing_completions = true;
 1524            }
 1525            Some(CodeContextMenu::CodeActions(_)) => {
 1526                key_context.add("menu");
 1527                key_context.add("showing_code_actions")
 1528            }
 1529            None => {}
 1530        }
 1531
 1532        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1533        if !self.focus_handle(cx).contains_focused(window, cx)
 1534            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1535        {
 1536            for addon in self.addons.values() {
 1537                addon.extend_key_context(&mut key_context, cx)
 1538            }
 1539        }
 1540
 1541        if let Some(extension) = self
 1542            .buffer
 1543            .read(cx)
 1544            .as_singleton()
 1545            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1546        {
 1547            key_context.set("extension", extension.to_string());
 1548        }
 1549
 1550        if self.has_active_inline_completion() {
 1551            key_context.add("copilot_suggestion");
 1552            key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1553
 1554            if showing_completions || self.edit_prediction_requires_modifier() {
 1555                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1556            }
 1557        }
 1558
 1559        if self.selection_mark_mode {
 1560            key_context.add("selection_mode");
 1561        }
 1562
 1563        key_context
 1564    }
 1565
 1566    pub fn accept_edit_prediction_keybind(
 1567        &self,
 1568        window: &Window,
 1569        cx: &App,
 1570    ) -> AcceptEditPredictionBinding {
 1571        let mut context = self.key_context(window, cx);
 1572        context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1573
 1574        AcceptEditPredictionBinding(
 1575            window
 1576                .bindings_for_action_in_context(&AcceptEditPrediction, context)
 1577                .into_iter()
 1578                .rev()
 1579                .next(),
 1580        )
 1581    }
 1582
 1583    pub fn new_file(
 1584        workspace: &mut Workspace,
 1585        _: &workspace::NewFile,
 1586        window: &mut Window,
 1587        cx: &mut Context<Workspace>,
 1588    ) {
 1589        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1590            "Failed to create buffer",
 1591            window,
 1592            cx,
 1593            |e, _, _| match e.error_code() {
 1594                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1595                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1596                e.error_tag("required").unwrap_or("the latest version")
 1597            )),
 1598                _ => None,
 1599            },
 1600        );
 1601    }
 1602
 1603    pub fn new_in_workspace(
 1604        workspace: &mut Workspace,
 1605        window: &mut Window,
 1606        cx: &mut Context<Workspace>,
 1607    ) -> Task<Result<Entity<Editor>>> {
 1608        let project = workspace.project().clone();
 1609        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1610
 1611        cx.spawn_in(window, |workspace, mut cx| async move {
 1612            let buffer = create.await?;
 1613            workspace.update_in(&mut cx, |workspace, window, cx| {
 1614                let editor =
 1615                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1616                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1617                editor
 1618            })
 1619        })
 1620    }
 1621
 1622    fn new_file_vertical(
 1623        workspace: &mut Workspace,
 1624        _: &workspace::NewFileSplitVertical,
 1625        window: &mut Window,
 1626        cx: &mut Context<Workspace>,
 1627    ) {
 1628        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1629    }
 1630
 1631    fn new_file_horizontal(
 1632        workspace: &mut Workspace,
 1633        _: &workspace::NewFileSplitHorizontal,
 1634        window: &mut Window,
 1635        cx: &mut Context<Workspace>,
 1636    ) {
 1637        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1638    }
 1639
 1640    fn new_file_in_direction(
 1641        workspace: &mut Workspace,
 1642        direction: SplitDirection,
 1643        window: &mut Window,
 1644        cx: &mut Context<Workspace>,
 1645    ) {
 1646        let project = workspace.project().clone();
 1647        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1648
 1649        cx.spawn_in(window, |workspace, mut cx| async move {
 1650            let buffer = create.await?;
 1651            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1652                workspace.split_item(
 1653                    direction,
 1654                    Box::new(
 1655                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1656                    ),
 1657                    window,
 1658                    cx,
 1659                )
 1660            })?;
 1661            anyhow::Ok(())
 1662        })
 1663        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1664            match e.error_code() {
 1665                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1666                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1667                e.error_tag("required").unwrap_or("the latest version")
 1668            )),
 1669                _ => None,
 1670            }
 1671        });
 1672    }
 1673
 1674    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1675        self.leader_peer_id
 1676    }
 1677
 1678    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1679        &self.buffer
 1680    }
 1681
 1682    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1683        self.workspace.as_ref()?.0.upgrade()
 1684    }
 1685
 1686    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1687        self.buffer().read(cx).title(cx)
 1688    }
 1689
 1690    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1691        let git_blame_gutter_max_author_length = self
 1692            .render_git_blame_gutter(cx)
 1693            .then(|| {
 1694                if let Some(blame) = self.blame.as_ref() {
 1695                    let max_author_length =
 1696                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1697                    Some(max_author_length)
 1698                } else {
 1699                    None
 1700                }
 1701            })
 1702            .flatten();
 1703
 1704        EditorSnapshot {
 1705            mode: self.mode,
 1706            show_gutter: self.show_gutter,
 1707            show_line_numbers: self.show_line_numbers,
 1708            show_git_diff_gutter: self.show_git_diff_gutter,
 1709            show_code_actions: self.show_code_actions,
 1710            show_runnables: self.show_runnables,
 1711            git_blame_gutter_max_author_length,
 1712            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1713            scroll_anchor: self.scroll_manager.anchor(),
 1714            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1715            placeholder_text: self.placeholder_text.clone(),
 1716            is_focused: self.focus_handle.is_focused(window),
 1717            current_line_highlight: self
 1718                .current_line_highlight
 1719                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1720            gutter_hovered: self.gutter_hovered,
 1721        }
 1722    }
 1723
 1724    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1725        self.buffer.read(cx).language_at(point, cx)
 1726    }
 1727
 1728    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1729        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1730    }
 1731
 1732    pub fn active_excerpt(
 1733        &self,
 1734        cx: &App,
 1735    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1736        self.buffer
 1737            .read(cx)
 1738            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1739    }
 1740
 1741    pub fn mode(&self) -> EditorMode {
 1742        self.mode
 1743    }
 1744
 1745    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1746        self.collaboration_hub.as_deref()
 1747    }
 1748
 1749    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1750        self.collaboration_hub = Some(hub);
 1751    }
 1752
 1753    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1754        self.in_project_search = in_project_search;
 1755    }
 1756
 1757    pub fn set_custom_context_menu(
 1758        &mut self,
 1759        f: impl 'static
 1760            + Fn(
 1761                &mut Self,
 1762                DisplayPoint,
 1763                &mut Window,
 1764                &mut Context<Self>,
 1765            ) -> Option<Entity<ui::ContextMenu>>,
 1766    ) {
 1767        self.custom_context_menu = Some(Box::new(f))
 1768    }
 1769
 1770    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1771        self.completion_provider = provider;
 1772    }
 1773
 1774    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1775        self.semantics_provider.clone()
 1776    }
 1777
 1778    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1779        self.semantics_provider = provider;
 1780    }
 1781
 1782    pub fn set_edit_prediction_provider<T>(
 1783        &mut self,
 1784        provider: Option<Entity<T>>,
 1785        window: &mut Window,
 1786        cx: &mut Context<Self>,
 1787    ) where
 1788        T: EditPredictionProvider,
 1789    {
 1790        self.edit_prediction_provider =
 1791            provider.map(|provider| RegisteredInlineCompletionProvider {
 1792                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1793                    if this.focus_handle.is_focused(window) {
 1794                        this.update_visible_inline_completion(window, cx);
 1795                    }
 1796                }),
 1797                provider: Arc::new(provider),
 1798            });
 1799        self.refresh_inline_completion(false, false, window, cx);
 1800    }
 1801
 1802    pub fn placeholder_text(&self) -> Option<&str> {
 1803        self.placeholder_text.as_deref()
 1804    }
 1805
 1806    pub fn set_placeholder_text(
 1807        &mut self,
 1808        placeholder_text: impl Into<Arc<str>>,
 1809        cx: &mut Context<Self>,
 1810    ) {
 1811        let placeholder_text = Some(placeholder_text.into());
 1812        if self.placeholder_text != placeholder_text {
 1813            self.placeholder_text = placeholder_text;
 1814            cx.notify();
 1815        }
 1816    }
 1817
 1818    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1819        self.cursor_shape = cursor_shape;
 1820
 1821        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1822        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1823
 1824        cx.notify();
 1825    }
 1826
 1827    pub fn set_current_line_highlight(
 1828        &mut self,
 1829        current_line_highlight: Option<CurrentLineHighlight>,
 1830    ) {
 1831        self.current_line_highlight = current_line_highlight;
 1832    }
 1833
 1834    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1835        self.collapse_matches = collapse_matches;
 1836    }
 1837
 1838    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1839        let buffers = self.buffer.read(cx).all_buffers();
 1840        let Some(lsp_store) = self.lsp_store(cx) else {
 1841            return;
 1842        };
 1843        lsp_store.update(cx, |lsp_store, cx| {
 1844            for buffer in buffers {
 1845                self.registered_buffers
 1846                    .entry(buffer.read(cx).remote_id())
 1847                    .or_insert_with(|| {
 1848                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1849                    });
 1850            }
 1851        })
 1852    }
 1853
 1854    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1855        if self.collapse_matches {
 1856            return range.start..range.start;
 1857        }
 1858        range.clone()
 1859    }
 1860
 1861    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1862        if self.display_map.read(cx).clip_at_line_ends != clip {
 1863            self.display_map
 1864                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1865        }
 1866    }
 1867
 1868    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1869        self.input_enabled = input_enabled;
 1870    }
 1871
 1872    pub fn set_inline_completions_hidden_for_vim_mode(
 1873        &mut self,
 1874        hidden: bool,
 1875        window: &mut Window,
 1876        cx: &mut Context<Self>,
 1877    ) {
 1878        if hidden != self.inline_completions_hidden_for_vim_mode {
 1879            self.inline_completions_hidden_for_vim_mode = hidden;
 1880            if hidden {
 1881                self.update_visible_inline_completion(window, cx);
 1882            } else {
 1883                self.refresh_inline_completion(true, false, window, cx);
 1884            }
 1885        }
 1886    }
 1887
 1888    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1889        self.menu_inline_completions_policy = value;
 1890    }
 1891
 1892    pub fn set_autoindent(&mut self, autoindent: bool) {
 1893        if autoindent {
 1894            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1895        } else {
 1896            self.autoindent_mode = None;
 1897        }
 1898    }
 1899
 1900    pub fn read_only(&self, cx: &App) -> bool {
 1901        self.read_only || self.buffer.read(cx).read_only()
 1902    }
 1903
 1904    pub fn set_read_only(&mut self, read_only: bool) {
 1905        self.read_only = read_only;
 1906    }
 1907
 1908    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1909        self.use_autoclose = autoclose;
 1910    }
 1911
 1912    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1913        self.use_auto_surround = auto_surround;
 1914    }
 1915
 1916    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1917        self.auto_replace_emoji_shortcode = auto_replace;
 1918    }
 1919
 1920    pub fn toggle_inline_completions(
 1921        &mut self,
 1922        _: &ToggleEditPrediction,
 1923        window: &mut Window,
 1924        cx: &mut Context<Self>,
 1925    ) {
 1926        if self.show_inline_completions_override.is_some() {
 1927            self.set_show_edit_predictions(None, window, cx);
 1928        } else {
 1929            let show_edit_predictions = !self.edit_predictions_enabled();
 1930            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1931        }
 1932    }
 1933
 1934    pub fn set_show_edit_predictions(
 1935        &mut self,
 1936        show_edit_predictions: Option<bool>,
 1937        window: &mut Window,
 1938        cx: &mut Context<Self>,
 1939    ) {
 1940        self.show_inline_completions_override = show_edit_predictions;
 1941        self.refresh_inline_completion(false, true, window, cx);
 1942    }
 1943
 1944    fn inline_completions_disabled_in_scope(
 1945        &self,
 1946        buffer: &Entity<Buffer>,
 1947        buffer_position: language::Anchor,
 1948        cx: &App,
 1949    ) -> bool {
 1950        let snapshot = buffer.read(cx).snapshot();
 1951        let settings = snapshot.settings_at(buffer_position, cx);
 1952
 1953        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1954            return false;
 1955        };
 1956
 1957        scope.override_name().map_or(false, |scope_name| {
 1958            settings
 1959                .edit_predictions_disabled_in
 1960                .iter()
 1961                .any(|s| s == scope_name)
 1962        })
 1963    }
 1964
 1965    pub fn set_use_modal_editing(&mut self, to: bool) {
 1966        self.use_modal_editing = to;
 1967    }
 1968
 1969    pub fn use_modal_editing(&self) -> bool {
 1970        self.use_modal_editing
 1971    }
 1972
 1973    fn selections_did_change(
 1974        &mut self,
 1975        local: bool,
 1976        old_cursor_position: &Anchor,
 1977        show_completions: bool,
 1978        window: &mut Window,
 1979        cx: &mut Context<Self>,
 1980    ) {
 1981        window.invalidate_character_coordinates();
 1982
 1983        // Copy selections to primary selection buffer
 1984        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1985        if local {
 1986            let selections = self.selections.all::<usize>(cx);
 1987            let buffer_handle = self.buffer.read(cx).read(cx);
 1988
 1989            let mut text = String::new();
 1990            for (index, selection) in selections.iter().enumerate() {
 1991                let text_for_selection = buffer_handle
 1992                    .text_for_range(selection.start..selection.end)
 1993                    .collect::<String>();
 1994
 1995                text.push_str(&text_for_selection);
 1996                if index != selections.len() - 1 {
 1997                    text.push('\n');
 1998                }
 1999            }
 2000
 2001            if !text.is_empty() {
 2002                cx.write_to_primary(ClipboardItem::new_string(text));
 2003            }
 2004        }
 2005
 2006        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2007            self.buffer.update(cx, |buffer, cx| {
 2008                buffer.set_active_selections(
 2009                    &self.selections.disjoint_anchors(),
 2010                    self.selections.line_mode,
 2011                    self.cursor_shape,
 2012                    cx,
 2013                )
 2014            });
 2015        }
 2016        let display_map = self
 2017            .display_map
 2018            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2019        let buffer = &display_map.buffer_snapshot;
 2020        self.add_selections_state = None;
 2021        self.select_next_state = None;
 2022        self.select_prev_state = None;
 2023        self.select_larger_syntax_node_stack.clear();
 2024        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2025        self.snippet_stack
 2026            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2027        self.take_rename(false, window, cx);
 2028
 2029        let new_cursor_position = self.selections.newest_anchor().head();
 2030
 2031        self.push_to_nav_history(
 2032            *old_cursor_position,
 2033            Some(new_cursor_position.to_point(buffer)),
 2034            cx,
 2035        );
 2036
 2037        if local {
 2038            let new_cursor_position = self.selections.newest_anchor().head();
 2039            let mut context_menu = self.context_menu.borrow_mut();
 2040            let completion_menu = match context_menu.as_ref() {
 2041                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2042                _ => {
 2043                    *context_menu = None;
 2044                    None
 2045                }
 2046            };
 2047            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2048                if !self.registered_buffers.contains_key(&buffer_id) {
 2049                    if let Some(lsp_store) = self.lsp_store(cx) {
 2050                        lsp_store.update(cx, |lsp_store, cx| {
 2051                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2052                                return;
 2053                            };
 2054                            self.registered_buffers.insert(
 2055                                buffer_id,
 2056                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2057                            );
 2058                        })
 2059                    }
 2060                }
 2061            }
 2062
 2063            if let Some(completion_menu) = completion_menu {
 2064                let cursor_position = new_cursor_position.to_offset(buffer);
 2065                let (word_range, kind) =
 2066                    buffer.surrounding_word(completion_menu.initial_position, true);
 2067                if kind == Some(CharKind::Word)
 2068                    && word_range.to_inclusive().contains(&cursor_position)
 2069                {
 2070                    let mut completion_menu = completion_menu.clone();
 2071                    drop(context_menu);
 2072
 2073                    let query = Self::completion_query(buffer, cursor_position);
 2074                    cx.spawn(move |this, mut cx| async move {
 2075                        completion_menu
 2076                            .filter(query.as_deref(), cx.background_executor().clone())
 2077                            .await;
 2078
 2079                        this.update(&mut cx, |this, cx| {
 2080                            let mut context_menu = this.context_menu.borrow_mut();
 2081                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2082                            else {
 2083                                return;
 2084                            };
 2085
 2086                            if menu.id > completion_menu.id {
 2087                                return;
 2088                            }
 2089
 2090                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2091                            drop(context_menu);
 2092                            cx.notify();
 2093                        })
 2094                    })
 2095                    .detach();
 2096
 2097                    if show_completions {
 2098                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2099                    }
 2100                } else {
 2101                    drop(context_menu);
 2102                    self.hide_context_menu(window, cx);
 2103                }
 2104            } else {
 2105                drop(context_menu);
 2106            }
 2107
 2108            hide_hover(self, cx);
 2109
 2110            if old_cursor_position.to_display_point(&display_map).row()
 2111                != new_cursor_position.to_display_point(&display_map).row()
 2112            {
 2113                self.available_code_actions.take();
 2114            }
 2115            self.refresh_code_actions(window, cx);
 2116            self.refresh_document_highlights(cx);
 2117            refresh_matching_bracket_highlights(self, window, cx);
 2118            self.update_visible_inline_completion(window, cx);
 2119            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2120            if self.git_blame_inline_enabled {
 2121                self.start_inline_blame_timer(window, cx);
 2122            }
 2123        }
 2124
 2125        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2126        cx.emit(EditorEvent::SelectionsChanged { local });
 2127
 2128        if self.selections.disjoint_anchors().len() == 1 {
 2129            cx.emit(SearchEvent::ActiveMatchChanged)
 2130        }
 2131        cx.notify();
 2132    }
 2133
 2134    pub fn change_selections<R>(
 2135        &mut self,
 2136        autoscroll: Option<Autoscroll>,
 2137        window: &mut Window,
 2138        cx: &mut Context<Self>,
 2139        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2140    ) -> R {
 2141        self.change_selections_inner(autoscroll, true, window, cx, change)
 2142    }
 2143
 2144    pub fn change_selections_inner<R>(
 2145        &mut self,
 2146        autoscroll: Option<Autoscroll>,
 2147        request_completions: bool,
 2148        window: &mut Window,
 2149        cx: &mut Context<Self>,
 2150        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2151    ) -> R {
 2152        let old_cursor_position = self.selections.newest_anchor().head();
 2153        self.push_to_selection_history();
 2154
 2155        let (changed, result) = self.selections.change_with(cx, change);
 2156
 2157        if changed {
 2158            if let Some(autoscroll) = autoscroll {
 2159                self.request_autoscroll(autoscroll, cx);
 2160            }
 2161            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2162
 2163            if self.should_open_signature_help_automatically(
 2164                &old_cursor_position,
 2165                self.signature_help_state.backspace_pressed(),
 2166                cx,
 2167            ) {
 2168                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2169            }
 2170            self.signature_help_state.set_backspace_pressed(false);
 2171        }
 2172
 2173        result
 2174    }
 2175
 2176    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2177    where
 2178        I: IntoIterator<Item = (Range<S>, T)>,
 2179        S: ToOffset,
 2180        T: Into<Arc<str>>,
 2181    {
 2182        if self.read_only(cx) {
 2183            return;
 2184        }
 2185
 2186        self.buffer
 2187            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2188    }
 2189
 2190    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2191    where
 2192        I: IntoIterator<Item = (Range<S>, T)>,
 2193        S: ToOffset,
 2194        T: Into<Arc<str>>,
 2195    {
 2196        if self.read_only(cx) {
 2197            return;
 2198        }
 2199
 2200        self.buffer.update(cx, |buffer, cx| {
 2201            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2202        });
 2203    }
 2204
 2205    pub fn edit_with_block_indent<I, S, T>(
 2206        &mut self,
 2207        edits: I,
 2208        original_indent_columns: Vec<u32>,
 2209        cx: &mut Context<Self>,
 2210    ) where
 2211        I: IntoIterator<Item = (Range<S>, T)>,
 2212        S: ToOffset,
 2213        T: Into<Arc<str>>,
 2214    {
 2215        if self.read_only(cx) {
 2216            return;
 2217        }
 2218
 2219        self.buffer.update(cx, |buffer, cx| {
 2220            buffer.edit(
 2221                edits,
 2222                Some(AutoindentMode::Block {
 2223                    original_indent_columns,
 2224                }),
 2225                cx,
 2226            )
 2227        });
 2228    }
 2229
 2230    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2231        self.hide_context_menu(window, cx);
 2232
 2233        match phase {
 2234            SelectPhase::Begin {
 2235                position,
 2236                add,
 2237                click_count,
 2238            } => self.begin_selection(position, add, click_count, window, cx),
 2239            SelectPhase::BeginColumnar {
 2240                position,
 2241                goal_column,
 2242                reset,
 2243            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2244            SelectPhase::Extend {
 2245                position,
 2246                click_count,
 2247            } => self.extend_selection(position, click_count, window, cx),
 2248            SelectPhase::Update {
 2249                position,
 2250                goal_column,
 2251                scroll_delta,
 2252            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2253            SelectPhase::End => self.end_selection(window, cx),
 2254        }
 2255    }
 2256
 2257    fn extend_selection(
 2258        &mut self,
 2259        position: DisplayPoint,
 2260        click_count: usize,
 2261        window: &mut Window,
 2262        cx: &mut Context<Self>,
 2263    ) {
 2264        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2265        let tail = self.selections.newest::<usize>(cx).tail();
 2266        self.begin_selection(position, false, click_count, window, cx);
 2267
 2268        let position = position.to_offset(&display_map, Bias::Left);
 2269        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2270
 2271        let mut pending_selection = self
 2272            .selections
 2273            .pending_anchor()
 2274            .expect("extend_selection not called with pending selection");
 2275        if position >= tail {
 2276            pending_selection.start = tail_anchor;
 2277        } else {
 2278            pending_selection.end = tail_anchor;
 2279            pending_selection.reversed = true;
 2280        }
 2281
 2282        let mut pending_mode = self.selections.pending_mode().unwrap();
 2283        match &mut pending_mode {
 2284            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2285            _ => {}
 2286        }
 2287
 2288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2289            s.set_pending(pending_selection, pending_mode)
 2290        });
 2291    }
 2292
 2293    fn begin_selection(
 2294        &mut self,
 2295        position: DisplayPoint,
 2296        add: bool,
 2297        click_count: usize,
 2298        window: &mut Window,
 2299        cx: &mut Context<Self>,
 2300    ) {
 2301        if !self.focus_handle.is_focused(window) {
 2302            self.last_focused_descendant = None;
 2303            window.focus(&self.focus_handle);
 2304        }
 2305
 2306        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2307        let buffer = &display_map.buffer_snapshot;
 2308        let newest_selection = self.selections.newest_anchor().clone();
 2309        let position = display_map.clip_point(position, Bias::Left);
 2310
 2311        let start;
 2312        let end;
 2313        let mode;
 2314        let mut auto_scroll;
 2315        match click_count {
 2316            1 => {
 2317                start = buffer.anchor_before(position.to_point(&display_map));
 2318                end = start;
 2319                mode = SelectMode::Character;
 2320                auto_scroll = true;
 2321            }
 2322            2 => {
 2323                let range = movement::surrounding_word(&display_map, position);
 2324                start = buffer.anchor_before(range.start.to_point(&display_map));
 2325                end = buffer.anchor_before(range.end.to_point(&display_map));
 2326                mode = SelectMode::Word(start..end);
 2327                auto_scroll = true;
 2328            }
 2329            3 => {
 2330                let position = display_map
 2331                    .clip_point(position, Bias::Left)
 2332                    .to_point(&display_map);
 2333                let line_start = display_map.prev_line_boundary(position).0;
 2334                let next_line_start = buffer.clip_point(
 2335                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2336                    Bias::Left,
 2337                );
 2338                start = buffer.anchor_before(line_start);
 2339                end = buffer.anchor_before(next_line_start);
 2340                mode = SelectMode::Line(start..end);
 2341                auto_scroll = true;
 2342            }
 2343            _ => {
 2344                start = buffer.anchor_before(0);
 2345                end = buffer.anchor_before(buffer.len());
 2346                mode = SelectMode::All;
 2347                auto_scroll = false;
 2348            }
 2349        }
 2350        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2351
 2352        let point_to_delete: Option<usize> = {
 2353            let selected_points: Vec<Selection<Point>> =
 2354                self.selections.disjoint_in_range(start..end, cx);
 2355
 2356            if !add || click_count > 1 {
 2357                None
 2358            } else if !selected_points.is_empty() {
 2359                Some(selected_points[0].id)
 2360            } else {
 2361                let clicked_point_already_selected =
 2362                    self.selections.disjoint.iter().find(|selection| {
 2363                        selection.start.to_point(buffer) == start.to_point(buffer)
 2364                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2365                    });
 2366
 2367                clicked_point_already_selected.map(|selection| selection.id)
 2368            }
 2369        };
 2370
 2371        let selections_count = self.selections.count();
 2372
 2373        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2374            if let Some(point_to_delete) = point_to_delete {
 2375                s.delete(point_to_delete);
 2376
 2377                if selections_count == 1 {
 2378                    s.set_pending_anchor_range(start..end, mode);
 2379                }
 2380            } else {
 2381                if !add {
 2382                    s.clear_disjoint();
 2383                } else if click_count > 1 {
 2384                    s.delete(newest_selection.id)
 2385                }
 2386
 2387                s.set_pending_anchor_range(start..end, mode);
 2388            }
 2389        });
 2390    }
 2391
 2392    fn begin_columnar_selection(
 2393        &mut self,
 2394        position: DisplayPoint,
 2395        goal_column: u32,
 2396        reset: bool,
 2397        window: &mut Window,
 2398        cx: &mut Context<Self>,
 2399    ) {
 2400        if !self.focus_handle.is_focused(window) {
 2401            self.last_focused_descendant = None;
 2402            window.focus(&self.focus_handle);
 2403        }
 2404
 2405        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2406
 2407        if reset {
 2408            let pointer_position = display_map
 2409                .buffer_snapshot
 2410                .anchor_before(position.to_point(&display_map));
 2411
 2412            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2413                s.clear_disjoint();
 2414                s.set_pending_anchor_range(
 2415                    pointer_position..pointer_position,
 2416                    SelectMode::Character,
 2417                );
 2418            });
 2419        }
 2420
 2421        let tail = self.selections.newest::<Point>(cx).tail();
 2422        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2423
 2424        if !reset {
 2425            self.select_columns(
 2426                tail.to_display_point(&display_map),
 2427                position,
 2428                goal_column,
 2429                &display_map,
 2430                window,
 2431                cx,
 2432            );
 2433        }
 2434    }
 2435
 2436    fn update_selection(
 2437        &mut self,
 2438        position: DisplayPoint,
 2439        goal_column: u32,
 2440        scroll_delta: gpui::Point<f32>,
 2441        window: &mut Window,
 2442        cx: &mut Context<Self>,
 2443    ) {
 2444        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2445
 2446        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2447            let tail = tail.to_display_point(&display_map);
 2448            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2449        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2450            let buffer = self.buffer.read(cx).snapshot(cx);
 2451            let head;
 2452            let tail;
 2453            let mode = self.selections.pending_mode().unwrap();
 2454            match &mode {
 2455                SelectMode::Character => {
 2456                    head = position.to_point(&display_map);
 2457                    tail = pending.tail().to_point(&buffer);
 2458                }
 2459                SelectMode::Word(original_range) => {
 2460                    let original_display_range = original_range.start.to_display_point(&display_map)
 2461                        ..original_range.end.to_display_point(&display_map);
 2462                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2463                        ..original_display_range.end.to_point(&display_map);
 2464                    if movement::is_inside_word(&display_map, position)
 2465                        || original_display_range.contains(&position)
 2466                    {
 2467                        let word_range = movement::surrounding_word(&display_map, position);
 2468                        if word_range.start < original_display_range.start {
 2469                            head = word_range.start.to_point(&display_map);
 2470                        } else {
 2471                            head = word_range.end.to_point(&display_map);
 2472                        }
 2473                    } else {
 2474                        head = position.to_point(&display_map);
 2475                    }
 2476
 2477                    if head <= original_buffer_range.start {
 2478                        tail = original_buffer_range.end;
 2479                    } else {
 2480                        tail = original_buffer_range.start;
 2481                    }
 2482                }
 2483                SelectMode::Line(original_range) => {
 2484                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2485
 2486                    let position = display_map
 2487                        .clip_point(position, Bias::Left)
 2488                        .to_point(&display_map);
 2489                    let line_start = display_map.prev_line_boundary(position).0;
 2490                    let next_line_start = buffer.clip_point(
 2491                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2492                        Bias::Left,
 2493                    );
 2494
 2495                    if line_start < original_range.start {
 2496                        head = line_start
 2497                    } else {
 2498                        head = next_line_start
 2499                    }
 2500
 2501                    if head <= original_range.start {
 2502                        tail = original_range.end;
 2503                    } else {
 2504                        tail = original_range.start;
 2505                    }
 2506                }
 2507                SelectMode::All => {
 2508                    return;
 2509                }
 2510            };
 2511
 2512            if head < tail {
 2513                pending.start = buffer.anchor_before(head);
 2514                pending.end = buffer.anchor_before(tail);
 2515                pending.reversed = true;
 2516            } else {
 2517                pending.start = buffer.anchor_before(tail);
 2518                pending.end = buffer.anchor_before(head);
 2519                pending.reversed = false;
 2520            }
 2521
 2522            self.change_selections(None, window, cx, |s| {
 2523                s.set_pending(pending, mode);
 2524            });
 2525        } else {
 2526            log::error!("update_selection dispatched with no pending selection");
 2527            return;
 2528        }
 2529
 2530        self.apply_scroll_delta(scroll_delta, window, cx);
 2531        cx.notify();
 2532    }
 2533
 2534    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2535        self.columnar_selection_tail.take();
 2536        if self.selections.pending_anchor().is_some() {
 2537            let selections = self.selections.all::<usize>(cx);
 2538            self.change_selections(None, window, cx, |s| {
 2539                s.select(selections);
 2540                s.clear_pending();
 2541            });
 2542        }
 2543    }
 2544
 2545    fn select_columns(
 2546        &mut self,
 2547        tail: DisplayPoint,
 2548        head: DisplayPoint,
 2549        goal_column: u32,
 2550        display_map: &DisplaySnapshot,
 2551        window: &mut Window,
 2552        cx: &mut Context<Self>,
 2553    ) {
 2554        let start_row = cmp::min(tail.row(), head.row());
 2555        let end_row = cmp::max(tail.row(), head.row());
 2556        let start_column = cmp::min(tail.column(), goal_column);
 2557        let end_column = cmp::max(tail.column(), goal_column);
 2558        let reversed = start_column < tail.column();
 2559
 2560        let selection_ranges = (start_row.0..=end_row.0)
 2561            .map(DisplayRow)
 2562            .filter_map(|row| {
 2563                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2564                    let start = display_map
 2565                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2566                        .to_point(display_map);
 2567                    let end = display_map
 2568                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2569                        .to_point(display_map);
 2570                    if reversed {
 2571                        Some(end..start)
 2572                    } else {
 2573                        Some(start..end)
 2574                    }
 2575                } else {
 2576                    None
 2577                }
 2578            })
 2579            .collect::<Vec<_>>();
 2580
 2581        self.change_selections(None, window, cx, |s| {
 2582            s.select_ranges(selection_ranges);
 2583        });
 2584        cx.notify();
 2585    }
 2586
 2587    pub fn has_pending_nonempty_selection(&self) -> bool {
 2588        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2589            Some(Selection { start, end, .. }) => start != end,
 2590            None => false,
 2591        };
 2592
 2593        pending_nonempty_selection
 2594            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2595    }
 2596
 2597    pub fn has_pending_selection(&self) -> bool {
 2598        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2599    }
 2600
 2601    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2602        self.selection_mark_mode = false;
 2603
 2604        if self.clear_expanded_diff_hunks(cx) {
 2605            cx.notify();
 2606            return;
 2607        }
 2608        if self.dismiss_menus_and_popups(true, window, cx) {
 2609            return;
 2610        }
 2611
 2612        if self.mode == EditorMode::Full
 2613            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2614        {
 2615            return;
 2616        }
 2617
 2618        cx.propagate();
 2619    }
 2620
 2621    pub fn dismiss_menus_and_popups(
 2622        &mut self,
 2623        is_user_requested: bool,
 2624        window: &mut Window,
 2625        cx: &mut Context<Self>,
 2626    ) -> bool {
 2627        if self.take_rename(false, window, cx).is_some() {
 2628            return true;
 2629        }
 2630
 2631        if hide_hover(self, cx) {
 2632            return true;
 2633        }
 2634
 2635        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2636            return true;
 2637        }
 2638
 2639        if self.hide_context_menu(window, cx).is_some() {
 2640            return true;
 2641        }
 2642
 2643        if self.mouse_context_menu.take().is_some() {
 2644            return true;
 2645        }
 2646
 2647        if is_user_requested && self.discard_inline_completion(true, cx) {
 2648            return true;
 2649        }
 2650
 2651        if self.snippet_stack.pop().is_some() {
 2652            return true;
 2653        }
 2654
 2655        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2656            self.dismiss_diagnostics(cx);
 2657            return true;
 2658        }
 2659
 2660        false
 2661    }
 2662
 2663    fn linked_editing_ranges_for(
 2664        &self,
 2665        selection: Range<text::Anchor>,
 2666        cx: &App,
 2667    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2668        if self.linked_edit_ranges.is_empty() {
 2669            return None;
 2670        }
 2671        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2672            selection.end.buffer_id.and_then(|end_buffer_id| {
 2673                if selection.start.buffer_id != Some(end_buffer_id) {
 2674                    return None;
 2675                }
 2676                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2677                let snapshot = buffer.read(cx).snapshot();
 2678                self.linked_edit_ranges
 2679                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2680                    .map(|ranges| (ranges, snapshot, buffer))
 2681            })?;
 2682        use text::ToOffset as TO;
 2683        // find offset from the start of current range to current cursor position
 2684        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2685
 2686        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2687        let start_difference = start_offset - start_byte_offset;
 2688        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2689        let end_difference = end_offset - start_byte_offset;
 2690        // Current range has associated linked ranges.
 2691        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2692        for range in linked_ranges.iter() {
 2693            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2694            let end_offset = start_offset + end_difference;
 2695            let start_offset = start_offset + start_difference;
 2696            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2697                continue;
 2698            }
 2699            if self.selections.disjoint_anchor_ranges().any(|s| {
 2700                if s.start.buffer_id != selection.start.buffer_id
 2701                    || s.end.buffer_id != selection.end.buffer_id
 2702                {
 2703                    return false;
 2704                }
 2705                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2706                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2707            }) {
 2708                continue;
 2709            }
 2710            let start = buffer_snapshot.anchor_after(start_offset);
 2711            let end = buffer_snapshot.anchor_after(end_offset);
 2712            linked_edits
 2713                .entry(buffer.clone())
 2714                .or_default()
 2715                .push(start..end);
 2716        }
 2717        Some(linked_edits)
 2718    }
 2719
 2720    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2721        let text: Arc<str> = text.into();
 2722
 2723        if self.read_only(cx) {
 2724            return;
 2725        }
 2726
 2727        let selections = self.selections.all_adjusted(cx);
 2728        let mut bracket_inserted = false;
 2729        let mut edits = Vec::new();
 2730        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2731        let mut new_selections = Vec::with_capacity(selections.len());
 2732        let mut new_autoclose_regions = Vec::new();
 2733        let snapshot = self.buffer.read(cx).read(cx);
 2734
 2735        for (selection, autoclose_region) in
 2736            self.selections_with_autoclose_regions(selections, &snapshot)
 2737        {
 2738            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2739                // Determine if the inserted text matches the opening or closing
 2740                // bracket of any of this language's bracket pairs.
 2741                let mut bracket_pair = None;
 2742                let mut is_bracket_pair_start = false;
 2743                let mut is_bracket_pair_end = false;
 2744                if !text.is_empty() {
 2745                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2746                    //  and they are removing the character that triggered IME popup.
 2747                    for (pair, enabled) in scope.brackets() {
 2748                        if !pair.close && !pair.surround {
 2749                            continue;
 2750                        }
 2751
 2752                        if enabled && pair.start.ends_with(text.as_ref()) {
 2753                            let prefix_len = pair.start.len() - text.len();
 2754                            let preceding_text_matches_prefix = prefix_len == 0
 2755                                || (selection.start.column >= (prefix_len as u32)
 2756                                    && snapshot.contains_str_at(
 2757                                        Point::new(
 2758                                            selection.start.row,
 2759                                            selection.start.column - (prefix_len as u32),
 2760                                        ),
 2761                                        &pair.start[..prefix_len],
 2762                                    ));
 2763                            if preceding_text_matches_prefix {
 2764                                bracket_pair = Some(pair.clone());
 2765                                is_bracket_pair_start = true;
 2766                                break;
 2767                            }
 2768                        }
 2769                        if pair.end.as_str() == text.as_ref() {
 2770                            bracket_pair = Some(pair.clone());
 2771                            is_bracket_pair_end = true;
 2772                            break;
 2773                        }
 2774                    }
 2775                }
 2776
 2777                if let Some(bracket_pair) = bracket_pair {
 2778                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2779                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2780                    let auto_surround =
 2781                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2782                    if selection.is_empty() {
 2783                        if is_bracket_pair_start {
 2784                            // If the inserted text is a suffix of an opening bracket and the
 2785                            // selection is preceded by the rest of the opening bracket, then
 2786                            // insert the closing bracket.
 2787                            let following_text_allows_autoclose = snapshot
 2788                                .chars_at(selection.start)
 2789                                .next()
 2790                                .map_or(true, |c| scope.should_autoclose_before(c));
 2791
 2792                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2793                                && bracket_pair.start.len() == 1
 2794                            {
 2795                                let target = bracket_pair.start.chars().next().unwrap();
 2796                                let current_line_count = snapshot
 2797                                    .reversed_chars_at(selection.start)
 2798                                    .take_while(|&c| c != '\n')
 2799                                    .filter(|&c| c == target)
 2800                                    .count();
 2801                                current_line_count % 2 == 1
 2802                            } else {
 2803                                false
 2804                            };
 2805
 2806                            if autoclose
 2807                                && bracket_pair.close
 2808                                && following_text_allows_autoclose
 2809                                && !is_closing_quote
 2810                            {
 2811                                let anchor = snapshot.anchor_before(selection.end);
 2812                                new_selections.push((selection.map(|_| anchor), text.len()));
 2813                                new_autoclose_regions.push((
 2814                                    anchor,
 2815                                    text.len(),
 2816                                    selection.id,
 2817                                    bracket_pair.clone(),
 2818                                ));
 2819                                edits.push((
 2820                                    selection.range(),
 2821                                    format!("{}{}", text, bracket_pair.end).into(),
 2822                                ));
 2823                                bracket_inserted = true;
 2824                                continue;
 2825                            }
 2826                        }
 2827
 2828                        if let Some(region) = autoclose_region {
 2829                            // If the selection is followed by an auto-inserted closing bracket,
 2830                            // then don't insert that closing bracket again; just move the selection
 2831                            // past the closing bracket.
 2832                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2833                                && text.as_ref() == region.pair.end.as_str();
 2834                            if should_skip {
 2835                                let anchor = snapshot.anchor_after(selection.end);
 2836                                new_selections
 2837                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2838                                continue;
 2839                            }
 2840                        }
 2841
 2842                        let always_treat_brackets_as_autoclosed = snapshot
 2843                            .settings_at(selection.start, cx)
 2844                            .always_treat_brackets_as_autoclosed;
 2845                        if always_treat_brackets_as_autoclosed
 2846                            && is_bracket_pair_end
 2847                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2848                        {
 2849                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2850                            // and the inserted text is a closing bracket and the selection is followed
 2851                            // by the closing bracket then move the selection past the closing bracket.
 2852                            let anchor = snapshot.anchor_after(selection.end);
 2853                            new_selections.push((selection.map(|_| anchor), text.len()));
 2854                            continue;
 2855                        }
 2856                    }
 2857                    // If an opening bracket is 1 character long and is typed while
 2858                    // text is selected, then surround that text with the bracket pair.
 2859                    else if auto_surround
 2860                        && bracket_pair.surround
 2861                        && is_bracket_pair_start
 2862                        && bracket_pair.start.chars().count() == 1
 2863                    {
 2864                        edits.push((selection.start..selection.start, text.clone()));
 2865                        edits.push((
 2866                            selection.end..selection.end,
 2867                            bracket_pair.end.as_str().into(),
 2868                        ));
 2869                        bracket_inserted = true;
 2870                        new_selections.push((
 2871                            Selection {
 2872                                id: selection.id,
 2873                                start: snapshot.anchor_after(selection.start),
 2874                                end: snapshot.anchor_before(selection.end),
 2875                                reversed: selection.reversed,
 2876                                goal: selection.goal,
 2877                            },
 2878                            0,
 2879                        ));
 2880                        continue;
 2881                    }
 2882                }
 2883            }
 2884
 2885            if self.auto_replace_emoji_shortcode
 2886                && selection.is_empty()
 2887                && text.as_ref().ends_with(':')
 2888            {
 2889                if let Some(possible_emoji_short_code) =
 2890                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2891                {
 2892                    if !possible_emoji_short_code.is_empty() {
 2893                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2894                            let emoji_shortcode_start = Point::new(
 2895                                selection.start.row,
 2896                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2897                            );
 2898
 2899                            // Remove shortcode from buffer
 2900                            edits.push((
 2901                                emoji_shortcode_start..selection.start,
 2902                                "".to_string().into(),
 2903                            ));
 2904                            new_selections.push((
 2905                                Selection {
 2906                                    id: selection.id,
 2907                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2908                                    end: snapshot.anchor_before(selection.start),
 2909                                    reversed: selection.reversed,
 2910                                    goal: selection.goal,
 2911                                },
 2912                                0,
 2913                            ));
 2914
 2915                            // Insert emoji
 2916                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2917                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2918                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2919
 2920                            continue;
 2921                        }
 2922                    }
 2923                }
 2924            }
 2925
 2926            // If not handling any auto-close operation, then just replace the selected
 2927            // text with the given input and move the selection to the end of the
 2928            // newly inserted text.
 2929            let anchor = snapshot.anchor_after(selection.end);
 2930            if !self.linked_edit_ranges.is_empty() {
 2931                let start_anchor = snapshot.anchor_before(selection.start);
 2932
 2933                let is_word_char = text.chars().next().map_or(true, |char| {
 2934                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2935                    classifier.is_word(char)
 2936                });
 2937
 2938                if is_word_char {
 2939                    if let Some(ranges) = self
 2940                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2941                    {
 2942                        for (buffer, edits) in ranges {
 2943                            linked_edits
 2944                                .entry(buffer.clone())
 2945                                .or_default()
 2946                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2947                        }
 2948                    }
 2949                }
 2950            }
 2951
 2952            new_selections.push((selection.map(|_| anchor), 0));
 2953            edits.push((selection.start..selection.end, text.clone()));
 2954        }
 2955
 2956        drop(snapshot);
 2957
 2958        self.transact(window, cx, |this, window, cx| {
 2959            this.buffer.update(cx, |buffer, cx| {
 2960                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2961            });
 2962            for (buffer, edits) in linked_edits {
 2963                buffer.update(cx, |buffer, cx| {
 2964                    let snapshot = buffer.snapshot();
 2965                    let edits = edits
 2966                        .into_iter()
 2967                        .map(|(range, text)| {
 2968                            use text::ToPoint as TP;
 2969                            let end_point = TP::to_point(&range.end, &snapshot);
 2970                            let start_point = TP::to_point(&range.start, &snapshot);
 2971                            (start_point..end_point, text)
 2972                        })
 2973                        .sorted_by_key(|(range, _)| range.start)
 2974                        .collect::<Vec<_>>();
 2975                    buffer.edit(edits, None, cx);
 2976                })
 2977            }
 2978            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2979            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2980            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2981            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2982                .zip(new_selection_deltas)
 2983                .map(|(selection, delta)| Selection {
 2984                    id: selection.id,
 2985                    start: selection.start + delta,
 2986                    end: selection.end + delta,
 2987                    reversed: selection.reversed,
 2988                    goal: SelectionGoal::None,
 2989                })
 2990                .collect::<Vec<_>>();
 2991
 2992            let mut i = 0;
 2993            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2994                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2995                let start = map.buffer_snapshot.anchor_before(position);
 2996                let end = map.buffer_snapshot.anchor_after(position);
 2997                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2998                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2999                        Ordering::Less => i += 1,
 3000                        Ordering::Greater => break,
 3001                        Ordering::Equal => {
 3002                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3003                                Ordering::Less => i += 1,
 3004                                Ordering::Equal => break,
 3005                                Ordering::Greater => break,
 3006                            }
 3007                        }
 3008                    }
 3009                }
 3010                this.autoclose_regions.insert(
 3011                    i,
 3012                    AutocloseRegion {
 3013                        selection_id,
 3014                        range: start..end,
 3015                        pair,
 3016                    },
 3017                );
 3018            }
 3019
 3020            let had_active_inline_completion = this.has_active_inline_completion();
 3021            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3022                s.select(new_selections)
 3023            });
 3024
 3025            if !bracket_inserted {
 3026                if let Some(on_type_format_task) =
 3027                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3028                {
 3029                    on_type_format_task.detach_and_log_err(cx);
 3030                }
 3031            }
 3032
 3033            let editor_settings = EditorSettings::get_global(cx);
 3034            if bracket_inserted
 3035                && (editor_settings.auto_signature_help
 3036                    || editor_settings.show_signature_help_after_edits)
 3037            {
 3038                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3039            }
 3040
 3041            let trigger_in_words =
 3042                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3043            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3044            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3045            this.refresh_inline_completion(true, false, window, cx);
 3046        });
 3047    }
 3048
 3049    fn find_possible_emoji_shortcode_at_position(
 3050        snapshot: &MultiBufferSnapshot,
 3051        position: Point,
 3052    ) -> Option<String> {
 3053        let mut chars = Vec::new();
 3054        let mut found_colon = false;
 3055        for char in snapshot.reversed_chars_at(position).take(100) {
 3056            // Found a possible emoji shortcode in the middle of the buffer
 3057            if found_colon {
 3058                if char.is_whitespace() {
 3059                    chars.reverse();
 3060                    return Some(chars.iter().collect());
 3061                }
 3062                // If the previous character is not a whitespace, we are in the middle of a word
 3063                // and we only want to complete the shortcode if the word is made up of other emojis
 3064                let mut containing_word = String::new();
 3065                for ch in snapshot
 3066                    .reversed_chars_at(position)
 3067                    .skip(chars.len() + 1)
 3068                    .take(100)
 3069                {
 3070                    if ch.is_whitespace() {
 3071                        break;
 3072                    }
 3073                    containing_word.push(ch);
 3074                }
 3075                let containing_word = containing_word.chars().rev().collect::<String>();
 3076                if util::word_consists_of_emojis(containing_word.as_str()) {
 3077                    chars.reverse();
 3078                    return Some(chars.iter().collect());
 3079                }
 3080            }
 3081
 3082            if char.is_whitespace() || !char.is_ascii() {
 3083                return None;
 3084            }
 3085            if char == ':' {
 3086                found_colon = true;
 3087            } else {
 3088                chars.push(char);
 3089            }
 3090        }
 3091        // Found a possible emoji shortcode at the beginning of the buffer
 3092        chars.reverse();
 3093        Some(chars.iter().collect())
 3094    }
 3095
 3096    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3097        self.transact(window, cx, |this, window, cx| {
 3098            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3099                let selections = this.selections.all::<usize>(cx);
 3100                let multi_buffer = this.buffer.read(cx);
 3101                let buffer = multi_buffer.snapshot(cx);
 3102                selections
 3103                    .iter()
 3104                    .map(|selection| {
 3105                        let start_point = selection.start.to_point(&buffer);
 3106                        let mut indent =
 3107                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3108                        indent.len = cmp::min(indent.len, start_point.column);
 3109                        let start = selection.start;
 3110                        let end = selection.end;
 3111                        let selection_is_empty = start == end;
 3112                        let language_scope = buffer.language_scope_at(start);
 3113                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3114                            &language_scope
 3115                        {
 3116                            let leading_whitespace_len = buffer
 3117                                .reversed_chars_at(start)
 3118                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3119                                .map(|c| c.len_utf8())
 3120                                .sum::<usize>();
 3121
 3122                            let trailing_whitespace_len = buffer
 3123                                .chars_at(end)
 3124                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3125                                .map(|c| c.len_utf8())
 3126                                .sum::<usize>();
 3127
 3128                            let insert_extra_newline =
 3129                                language.brackets().any(|(pair, enabled)| {
 3130                                    let pair_start = pair.start.trim_end();
 3131                                    let pair_end = pair.end.trim_start();
 3132
 3133                                    enabled
 3134                                        && pair.newline
 3135                                        && buffer.contains_str_at(
 3136                                            end + trailing_whitespace_len,
 3137                                            pair_end,
 3138                                        )
 3139                                        && buffer.contains_str_at(
 3140                                            (start - leading_whitespace_len)
 3141                                                .saturating_sub(pair_start.len()),
 3142                                            pair_start,
 3143                                        )
 3144                                });
 3145
 3146                            // Comment extension on newline is allowed only for cursor selections
 3147                            let comment_delimiter = maybe!({
 3148                                if !selection_is_empty {
 3149                                    return None;
 3150                                }
 3151
 3152                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3153                                    return None;
 3154                                }
 3155
 3156                                let delimiters = language.line_comment_prefixes();
 3157                                let max_len_of_delimiter =
 3158                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3159                                let (snapshot, range) =
 3160                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3161
 3162                                let mut index_of_first_non_whitespace = 0;
 3163                                let comment_candidate = snapshot
 3164                                    .chars_for_range(range)
 3165                                    .skip_while(|c| {
 3166                                        let should_skip = c.is_whitespace();
 3167                                        if should_skip {
 3168                                            index_of_first_non_whitespace += 1;
 3169                                        }
 3170                                        should_skip
 3171                                    })
 3172                                    .take(max_len_of_delimiter)
 3173                                    .collect::<String>();
 3174                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3175                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3176                                })?;
 3177                                let cursor_is_placed_after_comment_marker =
 3178                                    index_of_first_non_whitespace + comment_prefix.len()
 3179                                        <= start_point.column as usize;
 3180                                if cursor_is_placed_after_comment_marker {
 3181                                    Some(comment_prefix.clone())
 3182                                } else {
 3183                                    None
 3184                                }
 3185                            });
 3186                            (comment_delimiter, insert_extra_newline)
 3187                        } else {
 3188                            (None, false)
 3189                        };
 3190
 3191                        let capacity_for_delimiter = comment_delimiter
 3192                            .as_deref()
 3193                            .map(str::len)
 3194                            .unwrap_or_default();
 3195                        let mut new_text =
 3196                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3197                        new_text.push('\n');
 3198                        new_text.extend(indent.chars());
 3199                        if let Some(delimiter) = &comment_delimiter {
 3200                            new_text.push_str(delimiter);
 3201                        }
 3202                        if insert_extra_newline {
 3203                            new_text = new_text.repeat(2);
 3204                        }
 3205
 3206                        let anchor = buffer.anchor_after(end);
 3207                        let new_selection = selection.map(|_| anchor);
 3208                        (
 3209                            (start..end, new_text),
 3210                            (insert_extra_newline, new_selection),
 3211                        )
 3212                    })
 3213                    .unzip()
 3214            };
 3215
 3216            this.edit_with_autoindent(edits, cx);
 3217            let buffer = this.buffer.read(cx).snapshot(cx);
 3218            let new_selections = selection_fixup_info
 3219                .into_iter()
 3220                .map(|(extra_newline_inserted, new_selection)| {
 3221                    let mut cursor = new_selection.end.to_point(&buffer);
 3222                    if extra_newline_inserted {
 3223                        cursor.row -= 1;
 3224                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3225                    }
 3226                    new_selection.map(|_| cursor)
 3227                })
 3228                .collect();
 3229
 3230            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3231                s.select(new_selections)
 3232            });
 3233            this.refresh_inline_completion(true, false, window, cx);
 3234        });
 3235    }
 3236
 3237    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3238        let buffer = self.buffer.read(cx);
 3239        let snapshot = buffer.snapshot(cx);
 3240
 3241        let mut edits = Vec::new();
 3242        let mut rows = Vec::new();
 3243
 3244        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3245            let cursor = selection.head();
 3246            let row = cursor.row;
 3247
 3248            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3249
 3250            let newline = "\n".to_string();
 3251            edits.push((start_of_line..start_of_line, newline));
 3252
 3253            rows.push(row + rows_inserted as u32);
 3254        }
 3255
 3256        self.transact(window, cx, |editor, window, cx| {
 3257            editor.edit(edits, cx);
 3258
 3259            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3260                let mut index = 0;
 3261                s.move_cursors_with(|map, _, _| {
 3262                    let row = rows[index];
 3263                    index += 1;
 3264
 3265                    let point = Point::new(row, 0);
 3266                    let boundary = map.next_line_boundary(point).1;
 3267                    let clipped = map.clip_point(boundary, Bias::Left);
 3268
 3269                    (clipped, SelectionGoal::None)
 3270                });
 3271            });
 3272
 3273            let mut indent_edits = Vec::new();
 3274            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3275            for row in rows {
 3276                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3277                for (row, indent) in indents {
 3278                    if indent.len == 0 {
 3279                        continue;
 3280                    }
 3281
 3282                    let text = match indent.kind {
 3283                        IndentKind::Space => " ".repeat(indent.len as usize),
 3284                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3285                    };
 3286                    let point = Point::new(row.0, 0);
 3287                    indent_edits.push((point..point, text));
 3288                }
 3289            }
 3290            editor.edit(indent_edits, cx);
 3291        });
 3292    }
 3293
 3294    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3295        let buffer = self.buffer.read(cx);
 3296        let snapshot = buffer.snapshot(cx);
 3297
 3298        let mut edits = Vec::new();
 3299        let mut rows = Vec::new();
 3300        let mut rows_inserted = 0;
 3301
 3302        for selection in self.selections.all_adjusted(cx) {
 3303            let cursor = selection.head();
 3304            let row = cursor.row;
 3305
 3306            let point = Point::new(row + 1, 0);
 3307            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3308
 3309            let newline = "\n".to_string();
 3310            edits.push((start_of_line..start_of_line, newline));
 3311
 3312            rows_inserted += 1;
 3313            rows.push(row + rows_inserted);
 3314        }
 3315
 3316        self.transact(window, cx, |editor, window, cx| {
 3317            editor.edit(edits, cx);
 3318
 3319            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3320                let mut index = 0;
 3321                s.move_cursors_with(|map, _, _| {
 3322                    let row = rows[index];
 3323                    index += 1;
 3324
 3325                    let point = Point::new(row, 0);
 3326                    let boundary = map.next_line_boundary(point).1;
 3327                    let clipped = map.clip_point(boundary, Bias::Left);
 3328
 3329                    (clipped, SelectionGoal::None)
 3330                });
 3331            });
 3332
 3333            let mut indent_edits = Vec::new();
 3334            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3335            for row in rows {
 3336                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3337                for (row, indent) in indents {
 3338                    if indent.len == 0 {
 3339                        continue;
 3340                    }
 3341
 3342                    let text = match indent.kind {
 3343                        IndentKind::Space => " ".repeat(indent.len as usize),
 3344                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3345                    };
 3346                    let point = Point::new(row.0, 0);
 3347                    indent_edits.push((point..point, text));
 3348                }
 3349            }
 3350            editor.edit(indent_edits, cx);
 3351        });
 3352    }
 3353
 3354    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3355        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3356            original_indent_columns: Vec::new(),
 3357        });
 3358        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3359    }
 3360
 3361    fn insert_with_autoindent_mode(
 3362        &mut self,
 3363        text: &str,
 3364        autoindent_mode: Option<AutoindentMode>,
 3365        window: &mut Window,
 3366        cx: &mut Context<Self>,
 3367    ) {
 3368        if self.read_only(cx) {
 3369            return;
 3370        }
 3371
 3372        let text: Arc<str> = text.into();
 3373        self.transact(window, cx, |this, window, cx| {
 3374            let old_selections = this.selections.all_adjusted(cx);
 3375            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3376                let anchors = {
 3377                    let snapshot = buffer.read(cx);
 3378                    old_selections
 3379                        .iter()
 3380                        .map(|s| {
 3381                            let anchor = snapshot.anchor_after(s.head());
 3382                            s.map(|_| anchor)
 3383                        })
 3384                        .collect::<Vec<_>>()
 3385                };
 3386                buffer.edit(
 3387                    old_selections
 3388                        .iter()
 3389                        .map(|s| (s.start..s.end, text.clone())),
 3390                    autoindent_mode,
 3391                    cx,
 3392                );
 3393                anchors
 3394            });
 3395
 3396            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3397                s.select_anchors(selection_anchors);
 3398            });
 3399
 3400            cx.notify();
 3401        });
 3402    }
 3403
 3404    fn trigger_completion_on_input(
 3405        &mut self,
 3406        text: &str,
 3407        trigger_in_words: bool,
 3408        window: &mut Window,
 3409        cx: &mut Context<Self>,
 3410    ) {
 3411        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3412            self.show_completions(
 3413                &ShowCompletions {
 3414                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3415                },
 3416                window,
 3417                cx,
 3418            );
 3419        } else {
 3420            self.hide_context_menu(window, cx);
 3421        }
 3422    }
 3423
 3424    fn is_completion_trigger(
 3425        &self,
 3426        text: &str,
 3427        trigger_in_words: bool,
 3428        cx: &mut Context<Self>,
 3429    ) -> bool {
 3430        let position = self.selections.newest_anchor().head();
 3431        let multibuffer = self.buffer.read(cx);
 3432        let Some(buffer) = position
 3433            .buffer_id
 3434            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3435        else {
 3436            return false;
 3437        };
 3438
 3439        if let Some(completion_provider) = &self.completion_provider {
 3440            completion_provider.is_completion_trigger(
 3441                &buffer,
 3442                position.text_anchor,
 3443                text,
 3444                trigger_in_words,
 3445                cx,
 3446            )
 3447        } else {
 3448            false
 3449        }
 3450    }
 3451
 3452    /// If any empty selections is touching the start of its innermost containing autoclose
 3453    /// region, expand it to select the brackets.
 3454    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3455        let selections = self.selections.all::<usize>(cx);
 3456        let buffer = self.buffer.read(cx).read(cx);
 3457        let new_selections = self
 3458            .selections_with_autoclose_regions(selections, &buffer)
 3459            .map(|(mut selection, region)| {
 3460                if !selection.is_empty() {
 3461                    return selection;
 3462                }
 3463
 3464                if let Some(region) = region {
 3465                    let mut range = region.range.to_offset(&buffer);
 3466                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3467                        range.start -= region.pair.start.len();
 3468                        if buffer.contains_str_at(range.start, &region.pair.start)
 3469                            && buffer.contains_str_at(range.end, &region.pair.end)
 3470                        {
 3471                            range.end += region.pair.end.len();
 3472                            selection.start = range.start;
 3473                            selection.end = range.end;
 3474
 3475                            return selection;
 3476                        }
 3477                    }
 3478                }
 3479
 3480                let always_treat_brackets_as_autoclosed = buffer
 3481                    .settings_at(selection.start, cx)
 3482                    .always_treat_brackets_as_autoclosed;
 3483
 3484                if !always_treat_brackets_as_autoclosed {
 3485                    return selection;
 3486                }
 3487
 3488                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3489                    for (pair, enabled) in scope.brackets() {
 3490                        if !enabled || !pair.close {
 3491                            continue;
 3492                        }
 3493
 3494                        if buffer.contains_str_at(selection.start, &pair.end) {
 3495                            let pair_start_len = pair.start.len();
 3496                            if buffer.contains_str_at(
 3497                                selection.start.saturating_sub(pair_start_len),
 3498                                &pair.start,
 3499                            ) {
 3500                                selection.start -= pair_start_len;
 3501                                selection.end += pair.end.len();
 3502
 3503                                return selection;
 3504                            }
 3505                        }
 3506                    }
 3507                }
 3508
 3509                selection
 3510            })
 3511            .collect();
 3512
 3513        drop(buffer);
 3514        self.change_selections(None, window, cx, |selections| {
 3515            selections.select(new_selections)
 3516        });
 3517    }
 3518
 3519    /// Iterate the given selections, and for each one, find the smallest surrounding
 3520    /// autoclose region. This uses the ordering of the selections and the autoclose
 3521    /// regions to avoid repeated comparisons.
 3522    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3523        &'a self,
 3524        selections: impl IntoIterator<Item = Selection<D>>,
 3525        buffer: &'a MultiBufferSnapshot,
 3526    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3527        let mut i = 0;
 3528        let mut regions = self.autoclose_regions.as_slice();
 3529        selections.into_iter().map(move |selection| {
 3530            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3531
 3532            let mut enclosing = None;
 3533            while let Some(pair_state) = regions.get(i) {
 3534                if pair_state.range.end.to_offset(buffer) < range.start {
 3535                    regions = &regions[i + 1..];
 3536                    i = 0;
 3537                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3538                    break;
 3539                } else {
 3540                    if pair_state.selection_id == selection.id {
 3541                        enclosing = Some(pair_state);
 3542                    }
 3543                    i += 1;
 3544                }
 3545            }
 3546
 3547            (selection, enclosing)
 3548        })
 3549    }
 3550
 3551    /// Remove any autoclose regions that no longer contain their selection.
 3552    fn invalidate_autoclose_regions(
 3553        &mut self,
 3554        mut selections: &[Selection<Anchor>],
 3555        buffer: &MultiBufferSnapshot,
 3556    ) {
 3557        self.autoclose_regions.retain(|state| {
 3558            let mut i = 0;
 3559            while let Some(selection) = selections.get(i) {
 3560                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3561                    selections = &selections[1..];
 3562                    continue;
 3563                }
 3564                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3565                    break;
 3566                }
 3567                if selection.id == state.selection_id {
 3568                    return true;
 3569                } else {
 3570                    i += 1;
 3571                }
 3572            }
 3573            false
 3574        });
 3575    }
 3576
 3577    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3578        let offset = position.to_offset(buffer);
 3579        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3580        if offset > word_range.start && kind == Some(CharKind::Word) {
 3581            Some(
 3582                buffer
 3583                    .text_for_range(word_range.start..offset)
 3584                    .collect::<String>(),
 3585            )
 3586        } else {
 3587            None
 3588        }
 3589    }
 3590
 3591    pub fn toggle_inlay_hints(
 3592        &mut self,
 3593        _: &ToggleInlayHints,
 3594        _: &mut Window,
 3595        cx: &mut Context<Self>,
 3596    ) {
 3597        self.refresh_inlay_hints(
 3598            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3599            cx,
 3600        );
 3601    }
 3602
 3603    pub fn inlay_hints_enabled(&self) -> bool {
 3604        self.inlay_hint_cache.enabled
 3605    }
 3606
 3607    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3608        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3609            return;
 3610        }
 3611
 3612        let reason_description = reason.description();
 3613        let ignore_debounce = matches!(
 3614            reason,
 3615            InlayHintRefreshReason::SettingsChange(_)
 3616                | InlayHintRefreshReason::Toggle(_)
 3617                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3618        );
 3619        let (invalidate_cache, required_languages) = match reason {
 3620            InlayHintRefreshReason::Toggle(enabled) => {
 3621                self.inlay_hint_cache.enabled = enabled;
 3622                if enabled {
 3623                    (InvalidationStrategy::RefreshRequested, None)
 3624                } else {
 3625                    self.inlay_hint_cache.clear();
 3626                    self.splice_inlays(
 3627                        &self
 3628                            .visible_inlay_hints(cx)
 3629                            .iter()
 3630                            .map(|inlay| inlay.id)
 3631                            .collect::<Vec<InlayId>>(),
 3632                        Vec::new(),
 3633                        cx,
 3634                    );
 3635                    return;
 3636                }
 3637            }
 3638            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3639                match self.inlay_hint_cache.update_settings(
 3640                    &self.buffer,
 3641                    new_settings,
 3642                    self.visible_inlay_hints(cx),
 3643                    cx,
 3644                ) {
 3645                    ControlFlow::Break(Some(InlaySplice {
 3646                        to_remove,
 3647                        to_insert,
 3648                    })) => {
 3649                        self.splice_inlays(&to_remove, to_insert, cx);
 3650                        return;
 3651                    }
 3652                    ControlFlow::Break(None) => return,
 3653                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3654                }
 3655            }
 3656            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3657                if let Some(InlaySplice {
 3658                    to_remove,
 3659                    to_insert,
 3660                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3661                {
 3662                    self.splice_inlays(&to_remove, to_insert, cx);
 3663                }
 3664                return;
 3665            }
 3666            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3667            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3668                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3669            }
 3670            InlayHintRefreshReason::RefreshRequested => {
 3671                (InvalidationStrategy::RefreshRequested, None)
 3672            }
 3673        };
 3674
 3675        if let Some(InlaySplice {
 3676            to_remove,
 3677            to_insert,
 3678        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3679            reason_description,
 3680            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3681            invalidate_cache,
 3682            ignore_debounce,
 3683            cx,
 3684        ) {
 3685            self.splice_inlays(&to_remove, to_insert, cx);
 3686        }
 3687    }
 3688
 3689    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3690        self.display_map
 3691            .read(cx)
 3692            .current_inlays()
 3693            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3694            .cloned()
 3695            .collect()
 3696    }
 3697
 3698    pub fn excerpts_for_inlay_hints_query(
 3699        &self,
 3700        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3701        cx: &mut Context<Editor>,
 3702    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3703        let Some(project) = self.project.as_ref() else {
 3704            return HashMap::default();
 3705        };
 3706        let project = project.read(cx);
 3707        let multi_buffer = self.buffer().read(cx);
 3708        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3709        let multi_buffer_visible_start = self
 3710            .scroll_manager
 3711            .anchor()
 3712            .anchor
 3713            .to_point(&multi_buffer_snapshot);
 3714        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3715            multi_buffer_visible_start
 3716                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3717            Bias::Left,
 3718        );
 3719        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3720        multi_buffer_snapshot
 3721            .range_to_buffer_ranges(multi_buffer_visible_range)
 3722            .into_iter()
 3723            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3724            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3725                let buffer_file = project::File::from_dyn(buffer.file())?;
 3726                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3727                let worktree_entry = buffer_worktree
 3728                    .read(cx)
 3729                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3730                if worktree_entry.is_ignored {
 3731                    return None;
 3732                }
 3733
 3734                let language = buffer.language()?;
 3735                if let Some(restrict_to_languages) = restrict_to_languages {
 3736                    if !restrict_to_languages.contains(language) {
 3737                        return None;
 3738                    }
 3739                }
 3740                Some((
 3741                    excerpt_id,
 3742                    (
 3743                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3744                        buffer.version().clone(),
 3745                        excerpt_visible_range,
 3746                    ),
 3747                ))
 3748            })
 3749            .collect()
 3750    }
 3751
 3752    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3753        TextLayoutDetails {
 3754            text_system: window.text_system().clone(),
 3755            editor_style: self.style.clone().unwrap(),
 3756            rem_size: window.rem_size(),
 3757            scroll_anchor: self.scroll_manager.anchor(),
 3758            visible_rows: self.visible_line_count(),
 3759            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3760        }
 3761    }
 3762
 3763    pub fn splice_inlays(
 3764        &self,
 3765        to_remove: &[InlayId],
 3766        to_insert: Vec<Inlay>,
 3767        cx: &mut Context<Self>,
 3768    ) {
 3769        self.display_map.update(cx, |display_map, cx| {
 3770            display_map.splice_inlays(to_remove, to_insert, cx)
 3771        });
 3772        cx.notify();
 3773    }
 3774
 3775    fn trigger_on_type_formatting(
 3776        &self,
 3777        input: String,
 3778        window: &mut Window,
 3779        cx: &mut Context<Self>,
 3780    ) -> Option<Task<Result<()>>> {
 3781        if input.len() != 1 {
 3782            return None;
 3783        }
 3784
 3785        let project = self.project.as_ref()?;
 3786        let position = self.selections.newest_anchor().head();
 3787        let (buffer, buffer_position) = self
 3788            .buffer
 3789            .read(cx)
 3790            .text_anchor_for_position(position, cx)?;
 3791
 3792        let settings = language_settings::language_settings(
 3793            buffer
 3794                .read(cx)
 3795                .language_at(buffer_position)
 3796                .map(|l| l.name()),
 3797            buffer.read(cx).file(),
 3798            cx,
 3799        );
 3800        if !settings.use_on_type_format {
 3801            return None;
 3802        }
 3803
 3804        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3805        // hence we do LSP request & edit on host side only — add formats to host's history.
 3806        let push_to_lsp_host_history = true;
 3807        // If this is not the host, append its history with new edits.
 3808        let push_to_client_history = project.read(cx).is_via_collab();
 3809
 3810        let on_type_formatting = project.update(cx, |project, cx| {
 3811            project.on_type_format(
 3812                buffer.clone(),
 3813                buffer_position,
 3814                input,
 3815                push_to_lsp_host_history,
 3816                cx,
 3817            )
 3818        });
 3819        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3820            if let Some(transaction) = on_type_formatting.await? {
 3821                if push_to_client_history {
 3822                    buffer
 3823                        .update(&mut cx, |buffer, _| {
 3824                            buffer.push_transaction(transaction, Instant::now());
 3825                        })
 3826                        .ok();
 3827                }
 3828                editor.update(&mut cx, |editor, cx| {
 3829                    editor.refresh_document_highlights(cx);
 3830                })?;
 3831            }
 3832            Ok(())
 3833        }))
 3834    }
 3835
 3836    pub fn show_completions(
 3837        &mut self,
 3838        options: &ShowCompletions,
 3839        window: &mut Window,
 3840        cx: &mut Context<Self>,
 3841    ) {
 3842        if self.pending_rename.is_some() {
 3843            return;
 3844        }
 3845
 3846        let Some(provider) = self.completion_provider.as_ref() else {
 3847            return;
 3848        };
 3849
 3850        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3851            return;
 3852        }
 3853
 3854        let position = self.selections.newest_anchor().head();
 3855        if position.diff_base_anchor.is_some() {
 3856            return;
 3857        }
 3858        let (buffer, buffer_position) =
 3859            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3860                output
 3861            } else {
 3862                return;
 3863            };
 3864        let show_completion_documentation = buffer
 3865            .read(cx)
 3866            .snapshot()
 3867            .settings_at(buffer_position, cx)
 3868            .show_completion_documentation;
 3869
 3870        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3871
 3872        let trigger_kind = match &options.trigger {
 3873            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3874                CompletionTriggerKind::TRIGGER_CHARACTER
 3875            }
 3876            _ => CompletionTriggerKind::INVOKED,
 3877        };
 3878        let completion_context = CompletionContext {
 3879            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3880                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3881                    Some(String::from(trigger))
 3882                } else {
 3883                    None
 3884                }
 3885            }),
 3886            trigger_kind,
 3887        };
 3888        let completions =
 3889            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3890        let sort_completions = provider.sort_completions();
 3891
 3892        let id = post_inc(&mut self.next_completion_id);
 3893        let task = cx.spawn_in(window, |editor, mut cx| {
 3894            async move {
 3895                editor.update(&mut cx, |this, _| {
 3896                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3897                })?;
 3898                let completions = completions.await.log_err();
 3899                let menu = if let Some(completions) = completions {
 3900                    let mut menu = CompletionsMenu::new(
 3901                        id,
 3902                        sort_completions,
 3903                        show_completion_documentation,
 3904                        position,
 3905                        buffer.clone(),
 3906                        completions.into(),
 3907                    );
 3908
 3909                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3910                        .await;
 3911
 3912                    menu.visible().then_some(menu)
 3913                } else {
 3914                    None
 3915                };
 3916
 3917                editor.update_in(&mut cx, |editor, window, cx| {
 3918                    match editor.context_menu.borrow().as_ref() {
 3919                        None => {}
 3920                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3921                            if prev_menu.id > id {
 3922                                return;
 3923                            }
 3924                        }
 3925                        _ => return,
 3926                    }
 3927
 3928                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3929                        let mut menu = menu.unwrap();
 3930                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3931
 3932                        *editor.context_menu.borrow_mut() =
 3933                            Some(CodeContextMenu::Completions(menu));
 3934
 3935                        if editor.show_edit_predictions_in_menu() {
 3936                            editor.update_visible_inline_completion(window, cx);
 3937                        } else {
 3938                            editor.discard_inline_completion(false, cx);
 3939                        }
 3940
 3941                        cx.notify();
 3942                    } else if editor.completion_tasks.len() <= 1 {
 3943                        // If there are no more completion tasks and the last menu was
 3944                        // empty, we should hide it.
 3945                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3946                        // If it was already hidden and we don't show inline
 3947                        // completions in the menu, we should also show the
 3948                        // inline-completion when available.
 3949                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3950                            editor.update_visible_inline_completion(window, cx);
 3951                        }
 3952                    }
 3953                })?;
 3954
 3955                Ok::<_, anyhow::Error>(())
 3956            }
 3957            .log_err()
 3958        });
 3959
 3960        self.completion_tasks.push((id, task));
 3961    }
 3962
 3963    pub fn confirm_completion(
 3964        &mut self,
 3965        action: &ConfirmCompletion,
 3966        window: &mut Window,
 3967        cx: &mut Context<Self>,
 3968    ) -> Option<Task<Result<()>>> {
 3969        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3970    }
 3971
 3972    pub fn compose_completion(
 3973        &mut self,
 3974        action: &ComposeCompletion,
 3975        window: &mut Window,
 3976        cx: &mut Context<Self>,
 3977    ) -> Option<Task<Result<()>>> {
 3978        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3979    }
 3980
 3981    fn do_completion(
 3982        &mut self,
 3983        item_ix: Option<usize>,
 3984        intent: CompletionIntent,
 3985        window: &mut Window,
 3986        cx: &mut Context<Editor>,
 3987    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3988        use language::ToOffset as _;
 3989
 3990        let completions_menu =
 3991            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3992                menu
 3993            } else {
 3994                return None;
 3995            };
 3996
 3997        let entries = completions_menu.entries.borrow();
 3998        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3999        if self.show_edit_predictions_in_menu() {
 4000            self.discard_inline_completion(true, cx);
 4001        }
 4002        let candidate_id = mat.candidate_id;
 4003        drop(entries);
 4004
 4005        let buffer_handle = completions_menu.buffer;
 4006        let completion = completions_menu
 4007            .completions
 4008            .borrow()
 4009            .get(candidate_id)?
 4010            .clone();
 4011        cx.stop_propagation();
 4012
 4013        let snippet;
 4014        let text;
 4015
 4016        if completion.is_snippet() {
 4017            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4018            text = snippet.as_ref().unwrap().text.clone();
 4019        } else {
 4020            snippet = None;
 4021            text = completion.new_text.clone();
 4022        };
 4023        let selections = self.selections.all::<usize>(cx);
 4024        let buffer = buffer_handle.read(cx);
 4025        let old_range = completion.old_range.to_offset(buffer);
 4026        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4027
 4028        let newest_selection = self.selections.newest_anchor();
 4029        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4030            return None;
 4031        }
 4032
 4033        let lookbehind = newest_selection
 4034            .start
 4035            .text_anchor
 4036            .to_offset(buffer)
 4037            .saturating_sub(old_range.start);
 4038        let lookahead = old_range
 4039            .end
 4040            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4041        let mut common_prefix_len = old_text
 4042            .bytes()
 4043            .zip(text.bytes())
 4044            .take_while(|(a, b)| a == b)
 4045            .count();
 4046
 4047        let snapshot = self.buffer.read(cx).snapshot(cx);
 4048        let mut range_to_replace: Option<Range<isize>> = None;
 4049        let mut ranges = Vec::new();
 4050        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4051        for selection in &selections {
 4052            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4053                let start = selection.start.saturating_sub(lookbehind);
 4054                let end = selection.end + lookahead;
 4055                if selection.id == newest_selection.id {
 4056                    range_to_replace = Some(
 4057                        ((start + common_prefix_len) as isize - selection.start as isize)
 4058                            ..(end as isize - selection.start as isize),
 4059                    );
 4060                }
 4061                ranges.push(start + common_prefix_len..end);
 4062            } else {
 4063                common_prefix_len = 0;
 4064                ranges.clear();
 4065                ranges.extend(selections.iter().map(|s| {
 4066                    if s.id == newest_selection.id {
 4067                        range_to_replace = Some(
 4068                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4069                                - selection.start as isize
 4070                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4071                                    - selection.start as isize,
 4072                        );
 4073                        old_range.clone()
 4074                    } else {
 4075                        s.start..s.end
 4076                    }
 4077                }));
 4078                break;
 4079            }
 4080            if !self.linked_edit_ranges.is_empty() {
 4081                let start_anchor = snapshot.anchor_before(selection.head());
 4082                let end_anchor = snapshot.anchor_after(selection.tail());
 4083                if let Some(ranges) = self
 4084                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4085                {
 4086                    for (buffer, edits) in ranges {
 4087                        linked_edits.entry(buffer.clone()).or_default().extend(
 4088                            edits
 4089                                .into_iter()
 4090                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4091                        );
 4092                    }
 4093                }
 4094            }
 4095        }
 4096        let text = &text[common_prefix_len..];
 4097
 4098        cx.emit(EditorEvent::InputHandled {
 4099            utf16_range_to_replace: range_to_replace,
 4100            text: text.into(),
 4101        });
 4102
 4103        self.transact(window, cx, |this, window, cx| {
 4104            if let Some(mut snippet) = snippet {
 4105                snippet.text = text.to_string();
 4106                for tabstop in snippet
 4107                    .tabstops
 4108                    .iter_mut()
 4109                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4110                {
 4111                    tabstop.start -= common_prefix_len as isize;
 4112                    tabstop.end -= common_prefix_len as isize;
 4113                }
 4114
 4115                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4116            } else {
 4117                this.buffer.update(cx, |buffer, cx| {
 4118                    buffer.edit(
 4119                        ranges.iter().map(|range| (range.clone(), text)),
 4120                        this.autoindent_mode.clone(),
 4121                        cx,
 4122                    );
 4123                });
 4124            }
 4125            for (buffer, edits) in linked_edits {
 4126                buffer.update(cx, |buffer, cx| {
 4127                    let snapshot = buffer.snapshot();
 4128                    let edits = edits
 4129                        .into_iter()
 4130                        .map(|(range, text)| {
 4131                            use text::ToPoint as TP;
 4132                            let end_point = TP::to_point(&range.end, &snapshot);
 4133                            let start_point = TP::to_point(&range.start, &snapshot);
 4134                            (start_point..end_point, text)
 4135                        })
 4136                        .sorted_by_key(|(range, _)| range.start)
 4137                        .collect::<Vec<_>>();
 4138                    buffer.edit(edits, None, cx);
 4139                })
 4140            }
 4141
 4142            this.refresh_inline_completion(true, false, window, cx);
 4143        });
 4144
 4145        let show_new_completions_on_confirm = completion
 4146            .confirm
 4147            .as_ref()
 4148            .map_or(false, |confirm| confirm(intent, window, cx));
 4149        if show_new_completions_on_confirm {
 4150            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4151        }
 4152
 4153        let provider = self.completion_provider.as_ref()?;
 4154        drop(completion);
 4155        let apply_edits = provider.apply_additional_edits_for_completion(
 4156            buffer_handle,
 4157            completions_menu.completions.clone(),
 4158            candidate_id,
 4159            true,
 4160            cx,
 4161        );
 4162
 4163        let editor_settings = EditorSettings::get_global(cx);
 4164        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4165            // After the code completion is finished, users often want to know what signatures are needed.
 4166            // so we should automatically call signature_help
 4167            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4168        }
 4169
 4170        Some(cx.foreground_executor().spawn(async move {
 4171            apply_edits.await?;
 4172            Ok(())
 4173        }))
 4174    }
 4175
 4176    pub fn toggle_code_actions(
 4177        &mut self,
 4178        action: &ToggleCodeActions,
 4179        window: &mut Window,
 4180        cx: &mut Context<Self>,
 4181    ) {
 4182        let mut context_menu = self.context_menu.borrow_mut();
 4183        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4184            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4185                // Toggle if we're selecting the same one
 4186                *context_menu = None;
 4187                cx.notify();
 4188                return;
 4189            } else {
 4190                // Otherwise, clear it and start a new one
 4191                *context_menu = None;
 4192                cx.notify();
 4193            }
 4194        }
 4195        drop(context_menu);
 4196        let snapshot = self.snapshot(window, cx);
 4197        let deployed_from_indicator = action.deployed_from_indicator;
 4198        let mut task = self.code_actions_task.take();
 4199        let action = action.clone();
 4200        cx.spawn_in(window, |editor, mut cx| async move {
 4201            while let Some(prev_task) = task {
 4202                prev_task.await.log_err();
 4203                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4204            }
 4205
 4206            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4207                if editor.focus_handle.is_focused(window) {
 4208                    let multibuffer_point = action
 4209                        .deployed_from_indicator
 4210                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4211                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4212                    let (buffer, buffer_row) = snapshot
 4213                        .buffer_snapshot
 4214                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4215                        .and_then(|(buffer_snapshot, range)| {
 4216                            editor
 4217                                .buffer
 4218                                .read(cx)
 4219                                .buffer(buffer_snapshot.remote_id())
 4220                                .map(|buffer| (buffer, range.start.row))
 4221                        })?;
 4222                    let (_, code_actions) = editor
 4223                        .available_code_actions
 4224                        .clone()
 4225                        .and_then(|(location, code_actions)| {
 4226                            let snapshot = location.buffer.read(cx).snapshot();
 4227                            let point_range = location.range.to_point(&snapshot);
 4228                            let point_range = point_range.start.row..=point_range.end.row;
 4229                            if point_range.contains(&buffer_row) {
 4230                                Some((location, code_actions))
 4231                            } else {
 4232                                None
 4233                            }
 4234                        })
 4235                        .unzip();
 4236                    let buffer_id = buffer.read(cx).remote_id();
 4237                    let tasks = editor
 4238                        .tasks
 4239                        .get(&(buffer_id, buffer_row))
 4240                        .map(|t| Arc::new(t.to_owned()));
 4241                    if tasks.is_none() && code_actions.is_none() {
 4242                        return None;
 4243                    }
 4244
 4245                    editor.completion_tasks.clear();
 4246                    editor.discard_inline_completion(false, cx);
 4247                    let task_context =
 4248                        tasks
 4249                            .as_ref()
 4250                            .zip(editor.project.clone())
 4251                            .map(|(tasks, project)| {
 4252                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4253                            });
 4254
 4255                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4256                        let task_context = match task_context {
 4257                            Some(task_context) => task_context.await,
 4258                            None => None,
 4259                        };
 4260                        let resolved_tasks =
 4261                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4262                                Rc::new(ResolvedTasks {
 4263                                    templates: tasks.resolve(&task_context).collect(),
 4264                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4265                                        multibuffer_point.row,
 4266                                        tasks.column,
 4267                                    )),
 4268                                })
 4269                            });
 4270                        let spawn_straight_away = resolved_tasks
 4271                            .as_ref()
 4272                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4273                            && code_actions
 4274                                .as_ref()
 4275                                .map_or(true, |actions| actions.is_empty());
 4276                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4277                            *editor.context_menu.borrow_mut() =
 4278                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4279                                    buffer,
 4280                                    actions: CodeActionContents {
 4281                                        tasks: resolved_tasks,
 4282                                        actions: code_actions,
 4283                                    },
 4284                                    selected_item: Default::default(),
 4285                                    scroll_handle: UniformListScrollHandle::default(),
 4286                                    deployed_from_indicator,
 4287                                }));
 4288                            if spawn_straight_away {
 4289                                if let Some(task) = editor.confirm_code_action(
 4290                                    &ConfirmCodeAction { item_ix: Some(0) },
 4291                                    window,
 4292                                    cx,
 4293                                ) {
 4294                                    cx.notify();
 4295                                    return task;
 4296                                }
 4297                            }
 4298                            cx.notify();
 4299                            Task::ready(Ok(()))
 4300                        }) {
 4301                            task.await
 4302                        } else {
 4303                            Ok(())
 4304                        }
 4305                    }))
 4306                } else {
 4307                    Some(Task::ready(Ok(())))
 4308                }
 4309            })?;
 4310            if let Some(task) = spawned_test_task {
 4311                task.await?;
 4312            }
 4313
 4314            Ok::<_, anyhow::Error>(())
 4315        })
 4316        .detach_and_log_err(cx);
 4317    }
 4318
 4319    pub fn confirm_code_action(
 4320        &mut self,
 4321        action: &ConfirmCodeAction,
 4322        window: &mut Window,
 4323        cx: &mut Context<Self>,
 4324    ) -> Option<Task<Result<()>>> {
 4325        let actions_menu =
 4326            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4327                menu
 4328            } else {
 4329                return None;
 4330            };
 4331        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4332        let action = actions_menu.actions.get(action_ix)?;
 4333        let title = action.label();
 4334        let buffer = actions_menu.buffer;
 4335        let workspace = self.workspace()?;
 4336
 4337        match action {
 4338            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4339                workspace.update(cx, |workspace, cx| {
 4340                    workspace::tasks::schedule_resolved_task(
 4341                        workspace,
 4342                        task_source_kind,
 4343                        resolved_task,
 4344                        false,
 4345                        cx,
 4346                    );
 4347
 4348                    Some(Task::ready(Ok(())))
 4349                })
 4350            }
 4351            CodeActionsItem::CodeAction {
 4352                excerpt_id,
 4353                action,
 4354                provider,
 4355            } => {
 4356                let apply_code_action =
 4357                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4358                let workspace = workspace.downgrade();
 4359                Some(cx.spawn_in(window, |editor, cx| async move {
 4360                    let project_transaction = apply_code_action.await?;
 4361                    Self::open_project_transaction(
 4362                        &editor,
 4363                        workspace,
 4364                        project_transaction,
 4365                        title,
 4366                        cx,
 4367                    )
 4368                    .await
 4369                }))
 4370            }
 4371        }
 4372    }
 4373
 4374    pub async fn open_project_transaction(
 4375        this: &WeakEntity<Editor>,
 4376        workspace: WeakEntity<Workspace>,
 4377        transaction: ProjectTransaction,
 4378        title: String,
 4379        mut cx: AsyncWindowContext,
 4380    ) -> Result<()> {
 4381        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4382        cx.update(|_, cx| {
 4383            entries.sort_unstable_by_key(|(buffer, _)| {
 4384                buffer.read(cx).file().map(|f| f.path().clone())
 4385            });
 4386        })?;
 4387
 4388        // If the project transaction's edits are all contained within this editor, then
 4389        // avoid opening a new editor to display them.
 4390
 4391        if let Some((buffer, transaction)) = entries.first() {
 4392            if entries.len() == 1 {
 4393                let excerpt = this.update(&mut cx, |editor, cx| {
 4394                    editor
 4395                        .buffer()
 4396                        .read(cx)
 4397                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4398                })?;
 4399                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4400                    if excerpted_buffer == *buffer {
 4401                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4402                            let excerpt_range = excerpt_range.to_offset(buffer);
 4403                            buffer
 4404                                .edited_ranges_for_transaction::<usize>(transaction)
 4405                                .all(|range| {
 4406                                    excerpt_range.start <= range.start
 4407                                        && excerpt_range.end >= range.end
 4408                                })
 4409                        })?;
 4410
 4411                        if all_edits_within_excerpt {
 4412                            return Ok(());
 4413                        }
 4414                    }
 4415                }
 4416            }
 4417        } else {
 4418            return Ok(());
 4419        }
 4420
 4421        let mut ranges_to_highlight = Vec::new();
 4422        let excerpt_buffer = cx.new(|cx| {
 4423            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4424            for (buffer_handle, transaction) in &entries {
 4425                let buffer = buffer_handle.read(cx);
 4426                ranges_to_highlight.extend(
 4427                    multibuffer.push_excerpts_with_context_lines(
 4428                        buffer_handle.clone(),
 4429                        buffer
 4430                            .edited_ranges_for_transaction::<usize>(transaction)
 4431                            .collect(),
 4432                        DEFAULT_MULTIBUFFER_CONTEXT,
 4433                        cx,
 4434                    ),
 4435                );
 4436            }
 4437            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4438            multibuffer
 4439        })?;
 4440
 4441        workspace.update_in(&mut cx, |workspace, window, cx| {
 4442            let project = workspace.project().clone();
 4443            let editor = cx
 4444                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4445            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4446            editor.update(cx, |editor, cx| {
 4447                editor.highlight_background::<Self>(
 4448                    &ranges_to_highlight,
 4449                    |theme| theme.editor_highlighted_line_background,
 4450                    cx,
 4451                );
 4452            });
 4453        })?;
 4454
 4455        Ok(())
 4456    }
 4457
 4458    pub fn clear_code_action_providers(&mut self) {
 4459        self.code_action_providers.clear();
 4460        self.available_code_actions.take();
 4461    }
 4462
 4463    pub fn add_code_action_provider(
 4464        &mut self,
 4465        provider: Rc<dyn CodeActionProvider>,
 4466        window: &mut Window,
 4467        cx: &mut Context<Self>,
 4468    ) {
 4469        if self
 4470            .code_action_providers
 4471            .iter()
 4472            .any(|existing_provider| existing_provider.id() == provider.id())
 4473        {
 4474            return;
 4475        }
 4476
 4477        self.code_action_providers.push(provider);
 4478        self.refresh_code_actions(window, cx);
 4479    }
 4480
 4481    pub fn remove_code_action_provider(
 4482        &mut self,
 4483        id: Arc<str>,
 4484        window: &mut Window,
 4485        cx: &mut Context<Self>,
 4486    ) {
 4487        self.code_action_providers
 4488            .retain(|provider| provider.id() != id);
 4489        self.refresh_code_actions(window, cx);
 4490    }
 4491
 4492    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4493        let buffer = self.buffer.read(cx);
 4494        let newest_selection = self.selections.newest_anchor().clone();
 4495        if newest_selection.head().diff_base_anchor.is_some() {
 4496            return None;
 4497        }
 4498        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4499        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4500        if start_buffer != end_buffer {
 4501            return None;
 4502        }
 4503
 4504        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4505            cx.background_executor()
 4506                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4507                .await;
 4508
 4509            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4510                let providers = this.code_action_providers.clone();
 4511                let tasks = this
 4512                    .code_action_providers
 4513                    .iter()
 4514                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4515                    .collect::<Vec<_>>();
 4516                (providers, tasks)
 4517            })?;
 4518
 4519            let mut actions = Vec::new();
 4520            for (provider, provider_actions) in
 4521                providers.into_iter().zip(future::join_all(tasks).await)
 4522            {
 4523                if let Some(provider_actions) = provider_actions.log_err() {
 4524                    actions.extend(provider_actions.into_iter().map(|action| {
 4525                        AvailableCodeAction {
 4526                            excerpt_id: newest_selection.start.excerpt_id,
 4527                            action,
 4528                            provider: provider.clone(),
 4529                        }
 4530                    }));
 4531                }
 4532            }
 4533
 4534            this.update(&mut cx, |this, cx| {
 4535                this.available_code_actions = if actions.is_empty() {
 4536                    None
 4537                } else {
 4538                    Some((
 4539                        Location {
 4540                            buffer: start_buffer,
 4541                            range: start..end,
 4542                        },
 4543                        actions.into(),
 4544                    ))
 4545                };
 4546                cx.notify();
 4547            })
 4548        }));
 4549        None
 4550    }
 4551
 4552    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4553        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4554            self.show_git_blame_inline = false;
 4555
 4556            self.show_git_blame_inline_delay_task =
 4557                Some(cx.spawn_in(window, |this, mut cx| async move {
 4558                    cx.background_executor().timer(delay).await;
 4559
 4560                    this.update(&mut cx, |this, cx| {
 4561                        this.show_git_blame_inline = true;
 4562                        cx.notify();
 4563                    })
 4564                    .log_err();
 4565                }));
 4566        }
 4567    }
 4568
 4569    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4570        if self.pending_rename.is_some() {
 4571            return None;
 4572        }
 4573
 4574        let provider = self.semantics_provider.clone()?;
 4575        let buffer = self.buffer.read(cx);
 4576        let newest_selection = self.selections.newest_anchor().clone();
 4577        let cursor_position = newest_selection.head();
 4578        let (cursor_buffer, cursor_buffer_position) =
 4579            buffer.text_anchor_for_position(cursor_position, cx)?;
 4580        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4581        if cursor_buffer != tail_buffer {
 4582            return None;
 4583        }
 4584        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4585        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4586            cx.background_executor()
 4587                .timer(Duration::from_millis(debounce))
 4588                .await;
 4589
 4590            let highlights = if let Some(highlights) = cx
 4591                .update(|cx| {
 4592                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4593                })
 4594                .ok()
 4595                .flatten()
 4596            {
 4597                highlights.await.log_err()
 4598            } else {
 4599                None
 4600            };
 4601
 4602            if let Some(highlights) = highlights {
 4603                this.update(&mut cx, |this, cx| {
 4604                    if this.pending_rename.is_some() {
 4605                        return;
 4606                    }
 4607
 4608                    let buffer_id = cursor_position.buffer_id;
 4609                    let buffer = this.buffer.read(cx);
 4610                    if !buffer
 4611                        .text_anchor_for_position(cursor_position, cx)
 4612                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4613                    {
 4614                        return;
 4615                    }
 4616
 4617                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4618                    let mut write_ranges = Vec::new();
 4619                    let mut read_ranges = Vec::new();
 4620                    for highlight in highlights {
 4621                        for (excerpt_id, excerpt_range) in
 4622                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4623                        {
 4624                            let start = highlight
 4625                                .range
 4626                                .start
 4627                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4628                            let end = highlight
 4629                                .range
 4630                                .end
 4631                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4632                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4633                                continue;
 4634                            }
 4635
 4636                            let range = Anchor {
 4637                                buffer_id,
 4638                                excerpt_id,
 4639                                text_anchor: start,
 4640                                diff_base_anchor: None,
 4641                            }..Anchor {
 4642                                buffer_id,
 4643                                excerpt_id,
 4644                                text_anchor: end,
 4645                                diff_base_anchor: None,
 4646                            };
 4647                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4648                                write_ranges.push(range);
 4649                            } else {
 4650                                read_ranges.push(range);
 4651                            }
 4652                        }
 4653                    }
 4654
 4655                    this.highlight_background::<DocumentHighlightRead>(
 4656                        &read_ranges,
 4657                        |theme| theme.editor_document_highlight_read_background,
 4658                        cx,
 4659                    );
 4660                    this.highlight_background::<DocumentHighlightWrite>(
 4661                        &write_ranges,
 4662                        |theme| theme.editor_document_highlight_write_background,
 4663                        cx,
 4664                    );
 4665                    cx.notify();
 4666                })
 4667                .log_err();
 4668            }
 4669        }));
 4670        None
 4671    }
 4672
 4673    pub fn refresh_inline_completion(
 4674        &mut self,
 4675        debounce: bool,
 4676        user_requested: bool,
 4677        window: &mut Window,
 4678        cx: &mut Context<Self>,
 4679    ) -> Option<()> {
 4680        let provider = self.edit_prediction_provider()?;
 4681        let cursor = self.selections.newest_anchor().head();
 4682        let (buffer, cursor_buffer_position) =
 4683            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4684
 4685        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4686            self.discard_inline_completion(false, cx);
 4687            return None;
 4688        }
 4689
 4690        if !user_requested
 4691            && (!self.should_show_edit_predictions()
 4692                || !self.is_focused(window)
 4693                || buffer.read(cx).is_empty())
 4694        {
 4695            self.discard_inline_completion(false, cx);
 4696            return None;
 4697        }
 4698
 4699        self.update_visible_inline_completion(window, cx);
 4700        provider.refresh(
 4701            self.project.clone(),
 4702            buffer,
 4703            cursor_buffer_position,
 4704            debounce,
 4705            cx,
 4706        );
 4707        Some(())
 4708    }
 4709
 4710    fn show_edit_predictions_in_menu(&self) -> bool {
 4711        match self.edit_prediction_settings {
 4712            EditPredictionSettings::Disabled => false,
 4713            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4714        }
 4715    }
 4716
 4717    pub fn edit_predictions_enabled(&self) -> bool {
 4718        match self.edit_prediction_settings {
 4719            EditPredictionSettings::Disabled => false,
 4720            EditPredictionSettings::Enabled { .. } => true,
 4721        }
 4722    }
 4723
 4724    fn edit_prediction_requires_modifier(&self) -> bool {
 4725        match self.edit_prediction_settings {
 4726            EditPredictionSettings::Disabled => false,
 4727            EditPredictionSettings::Enabled {
 4728                preview_requires_modifier,
 4729                ..
 4730            } => preview_requires_modifier,
 4731        }
 4732    }
 4733
 4734    fn edit_prediction_settings_at_position(
 4735        &self,
 4736        buffer: &Entity<Buffer>,
 4737        buffer_position: language::Anchor,
 4738        cx: &App,
 4739    ) -> EditPredictionSettings {
 4740        if self.mode != EditorMode::Full
 4741            || !self.show_inline_completions_override.unwrap_or(true)
 4742            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4743        {
 4744            return EditPredictionSettings::Disabled;
 4745        }
 4746
 4747        let buffer = buffer.read(cx);
 4748
 4749        let file = buffer.file();
 4750
 4751        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4752            return EditPredictionSettings::Disabled;
 4753        };
 4754
 4755        let by_provider = matches!(
 4756            self.menu_inline_completions_policy,
 4757            MenuInlineCompletionsPolicy::ByProvider
 4758        );
 4759
 4760        let show_in_menu = by_provider
 4761            && EditorSettings::get_global(cx).show_edit_predictions_in_menu
 4762            && self
 4763                .edit_prediction_provider
 4764                .as_ref()
 4765                .map_or(false, |provider| {
 4766                    provider.provider.show_completions_in_menu()
 4767                });
 4768
 4769        let preview_requires_modifier = all_language_settings(file, cx)
 4770            .inline_completions_preview_mode()
 4771            == InlineCompletionPreviewMode::WhenHoldingModifier;
 4772
 4773        EditPredictionSettings::Enabled {
 4774            show_in_menu,
 4775            preview_requires_modifier,
 4776        }
 4777    }
 4778
 4779    fn should_show_edit_predictions(&self) -> bool {
 4780        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4781    }
 4782
 4783    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4784        let cursor = self.selections.newest_anchor().head();
 4785        if let Some((buffer, cursor_position)) =
 4786            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4787        {
 4788            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4789        } else {
 4790            false
 4791        }
 4792    }
 4793
 4794    fn inline_completions_enabled_in_buffer(
 4795        &self,
 4796        buffer: &Entity<Buffer>,
 4797        buffer_position: language::Anchor,
 4798        cx: &App,
 4799    ) -> bool {
 4800        maybe!({
 4801            let provider = self.edit_prediction_provider()?;
 4802            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4803                return Some(false);
 4804            }
 4805            let buffer = buffer.read(cx);
 4806            let Some(file) = buffer.file() else {
 4807                return Some(true);
 4808            };
 4809            let settings = all_language_settings(Some(file), cx);
 4810            Some(settings.inline_completions_enabled_for_path(file.path()))
 4811        })
 4812        .unwrap_or(false)
 4813    }
 4814
 4815    fn cycle_inline_completion(
 4816        &mut self,
 4817        direction: Direction,
 4818        window: &mut Window,
 4819        cx: &mut Context<Self>,
 4820    ) -> Option<()> {
 4821        let provider = self.edit_prediction_provider()?;
 4822        let cursor = self.selections.newest_anchor().head();
 4823        let (buffer, cursor_buffer_position) =
 4824            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4825        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4826            return None;
 4827        }
 4828
 4829        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4830        self.update_visible_inline_completion(window, cx);
 4831
 4832        Some(())
 4833    }
 4834
 4835    pub fn show_inline_completion(
 4836        &mut self,
 4837        _: &ShowEditPrediction,
 4838        window: &mut Window,
 4839        cx: &mut Context<Self>,
 4840    ) {
 4841        if !self.has_active_inline_completion() {
 4842            self.refresh_inline_completion(false, true, window, cx);
 4843            return;
 4844        }
 4845
 4846        self.update_visible_inline_completion(window, cx);
 4847    }
 4848
 4849    pub fn display_cursor_names(
 4850        &mut self,
 4851        _: &DisplayCursorNames,
 4852        window: &mut Window,
 4853        cx: &mut Context<Self>,
 4854    ) {
 4855        self.show_cursor_names(window, cx);
 4856    }
 4857
 4858    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4859        self.show_cursor_names = true;
 4860        cx.notify();
 4861        cx.spawn_in(window, |this, mut cx| async move {
 4862            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4863            this.update(&mut cx, |this, cx| {
 4864                this.show_cursor_names = false;
 4865                cx.notify()
 4866            })
 4867            .ok()
 4868        })
 4869        .detach();
 4870    }
 4871
 4872    pub fn next_edit_prediction(
 4873        &mut self,
 4874        _: &NextEditPrediction,
 4875        window: &mut Window,
 4876        cx: &mut Context<Self>,
 4877    ) {
 4878        if self.has_active_inline_completion() {
 4879            self.cycle_inline_completion(Direction::Next, window, cx);
 4880        } else {
 4881            let is_copilot_disabled = self
 4882                .refresh_inline_completion(false, true, window, cx)
 4883                .is_none();
 4884            if is_copilot_disabled {
 4885                cx.propagate();
 4886            }
 4887        }
 4888    }
 4889
 4890    pub fn previous_edit_prediction(
 4891        &mut self,
 4892        _: &PreviousEditPrediction,
 4893        window: &mut Window,
 4894        cx: &mut Context<Self>,
 4895    ) {
 4896        if self.has_active_inline_completion() {
 4897            self.cycle_inline_completion(Direction::Prev, window, cx);
 4898        } else {
 4899            let is_copilot_disabled = self
 4900                .refresh_inline_completion(false, true, window, cx)
 4901                .is_none();
 4902            if is_copilot_disabled {
 4903                cx.propagate();
 4904            }
 4905        }
 4906    }
 4907
 4908    pub fn accept_edit_prediction(
 4909        &mut self,
 4910        _: &AcceptEditPrediction,
 4911        window: &mut Window,
 4912        cx: &mut Context<Self>,
 4913    ) {
 4914        let buffer = self.buffer.read(cx);
 4915        let snapshot = buffer.snapshot(cx);
 4916        let selection = self.selections.newest_adjusted(cx);
 4917        let cursor = selection.head();
 4918        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4919        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4920        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4921        {
 4922            if cursor.column < suggested_indent.len
 4923                && cursor.column <= current_indent.len
 4924                && current_indent.len <= suggested_indent.len
 4925            {
 4926                self.tab(&Default::default(), window, cx);
 4927                return;
 4928            }
 4929        }
 4930
 4931        if self.show_edit_predictions_in_menu() {
 4932            self.hide_context_menu(window, cx);
 4933        }
 4934
 4935        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4936            return;
 4937        };
 4938
 4939        self.report_inline_completion_event(
 4940            active_inline_completion.completion_id.clone(),
 4941            true,
 4942            cx,
 4943        );
 4944
 4945        match &active_inline_completion.completion {
 4946            InlineCompletion::Move { target, .. } => {
 4947                let target = *target;
 4948                // Note that this is also done in vim's handler of the Tab action.
 4949                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4950                    selections.select_anchor_ranges([target..target]);
 4951                });
 4952            }
 4953            InlineCompletion::Edit { edits, .. } => {
 4954                if let Some(provider) = self.edit_prediction_provider() {
 4955                    provider.accept(cx);
 4956                }
 4957
 4958                let snapshot = self.buffer.read(cx).snapshot(cx);
 4959                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4960
 4961                self.buffer.update(cx, |buffer, cx| {
 4962                    buffer.edit(edits.iter().cloned(), None, cx)
 4963                });
 4964
 4965                self.change_selections(None, window, cx, |s| {
 4966                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4967                });
 4968
 4969                self.update_visible_inline_completion(window, cx);
 4970                if self.active_inline_completion.is_none() {
 4971                    self.refresh_inline_completion(true, true, window, cx);
 4972                }
 4973
 4974                cx.notify();
 4975            }
 4976        }
 4977    }
 4978
 4979    pub fn accept_partial_inline_completion(
 4980        &mut self,
 4981        _: &AcceptPartialEditPrediction,
 4982        window: &mut Window,
 4983        cx: &mut Context<Self>,
 4984    ) {
 4985        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4986            return;
 4987        };
 4988        if self.selections.count() != 1 {
 4989            return;
 4990        }
 4991
 4992        self.report_inline_completion_event(
 4993            active_inline_completion.completion_id.clone(),
 4994            true,
 4995            cx,
 4996        );
 4997
 4998        match &active_inline_completion.completion {
 4999            InlineCompletion::Move { target, .. } => {
 5000                let target = *target;
 5001                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5002                    selections.select_anchor_ranges([target..target]);
 5003                });
 5004            }
 5005            InlineCompletion::Edit { edits, .. } => {
 5006                // Find an insertion that starts at the cursor position.
 5007                let snapshot = self.buffer.read(cx).snapshot(cx);
 5008                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5009                let insertion = edits.iter().find_map(|(range, text)| {
 5010                    let range = range.to_offset(&snapshot);
 5011                    if range.is_empty() && range.start == cursor_offset {
 5012                        Some(text)
 5013                    } else {
 5014                        None
 5015                    }
 5016                });
 5017
 5018                if let Some(text) = insertion {
 5019                    let mut partial_completion = text
 5020                        .chars()
 5021                        .by_ref()
 5022                        .take_while(|c| c.is_alphabetic())
 5023                        .collect::<String>();
 5024                    if partial_completion.is_empty() {
 5025                        partial_completion = text
 5026                            .chars()
 5027                            .by_ref()
 5028                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5029                            .collect::<String>();
 5030                    }
 5031
 5032                    cx.emit(EditorEvent::InputHandled {
 5033                        utf16_range_to_replace: None,
 5034                        text: partial_completion.clone().into(),
 5035                    });
 5036
 5037                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5038
 5039                    self.refresh_inline_completion(true, true, window, cx);
 5040                    cx.notify();
 5041                } else {
 5042                    self.accept_edit_prediction(&Default::default(), window, cx);
 5043                }
 5044            }
 5045        }
 5046    }
 5047
 5048    fn discard_inline_completion(
 5049        &mut self,
 5050        should_report_inline_completion_event: bool,
 5051        cx: &mut Context<Self>,
 5052    ) -> bool {
 5053        if should_report_inline_completion_event {
 5054            let completion_id = self
 5055                .active_inline_completion
 5056                .as_ref()
 5057                .and_then(|active_completion| active_completion.completion_id.clone());
 5058
 5059            self.report_inline_completion_event(completion_id, false, cx);
 5060        }
 5061
 5062        if let Some(provider) = self.edit_prediction_provider() {
 5063            provider.discard(cx);
 5064        }
 5065
 5066        self.take_active_inline_completion(cx)
 5067    }
 5068
 5069    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5070        let Some(provider) = self.edit_prediction_provider() else {
 5071            return;
 5072        };
 5073
 5074        let Some((_, buffer, _)) = self
 5075            .buffer
 5076            .read(cx)
 5077            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5078        else {
 5079            return;
 5080        };
 5081
 5082        let extension = buffer
 5083            .read(cx)
 5084            .file()
 5085            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5086
 5087        let event_type = match accepted {
 5088            true => "Edit Prediction Accepted",
 5089            false => "Edit Prediction Discarded",
 5090        };
 5091        telemetry::event!(
 5092            event_type,
 5093            provider = provider.name(),
 5094            prediction_id = id,
 5095            suggestion_accepted = accepted,
 5096            file_extension = extension,
 5097        );
 5098    }
 5099
 5100    pub fn has_active_inline_completion(&self) -> bool {
 5101        self.active_inline_completion.is_some()
 5102    }
 5103
 5104    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5105        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5106            return false;
 5107        };
 5108
 5109        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5110        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5111        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5112        true
 5113    }
 5114
 5115    /// Returns true when we're displaying the inline completion popover below the cursor
 5116    /// like we are not previewing and the LSP autocomplete menu is visible
 5117    /// or we are in `when_holding_modifier` mode.
 5118    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5119        if self.previewing_inline_completion
 5120            || !self.show_edit_predictions_in_menu()
 5121            || !self.edit_predictions_enabled()
 5122        {
 5123            return false;
 5124        }
 5125
 5126        if self.has_visible_completions_menu() {
 5127            return true;
 5128        }
 5129
 5130        has_completion && self.edit_prediction_requires_modifier()
 5131    }
 5132
 5133    fn handle_modifiers_changed(
 5134        &mut self,
 5135        modifiers: Modifiers,
 5136        position_map: &PositionMap,
 5137        window: &mut Window,
 5138        cx: &mut Context<Self>,
 5139    ) {
 5140        if self.show_edit_predictions_in_menu() {
 5141            let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5142            if let Some(accept_keystroke) = accept_binding.keystroke() {
 5143                let was_previewing_inline_completion = self.previewing_inline_completion;
 5144                self.previewing_inline_completion = modifiers == accept_keystroke.modifiers
 5145                    && accept_keystroke.modifiers.modified();
 5146                if self.previewing_inline_completion != was_previewing_inline_completion {
 5147                    self.update_visible_inline_completion(window, cx);
 5148                }
 5149            }
 5150        }
 5151
 5152        let mouse_position = window.mouse_position();
 5153        if !position_map.text_hitbox.is_hovered(window) {
 5154            return;
 5155        }
 5156
 5157        self.update_hovered_link(
 5158            position_map.point_for_position(mouse_position),
 5159            &position_map.snapshot,
 5160            modifiers,
 5161            window,
 5162            cx,
 5163        )
 5164    }
 5165
 5166    fn update_visible_inline_completion(
 5167        &mut self,
 5168        _window: &mut Window,
 5169        cx: &mut Context<Self>,
 5170    ) -> Option<()> {
 5171        let selection = self.selections.newest_anchor();
 5172        let cursor = selection.head();
 5173        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5174        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5175        let excerpt_id = cursor.excerpt_id;
 5176
 5177        let show_in_menu = self.show_edit_predictions_in_menu();
 5178        let completions_menu_has_precedence = !show_in_menu
 5179            && (self.context_menu.borrow().is_some()
 5180                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5181
 5182        if completions_menu_has_precedence
 5183            || !offset_selection.is_empty()
 5184            || self
 5185                .active_inline_completion
 5186                .as_ref()
 5187                .map_or(false, |completion| {
 5188                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5189                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5190                    !invalidation_range.contains(&offset_selection.head())
 5191                })
 5192        {
 5193            self.discard_inline_completion(false, cx);
 5194            return None;
 5195        }
 5196
 5197        self.take_active_inline_completion(cx);
 5198        let Some(provider) = self.edit_prediction_provider() else {
 5199            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5200            return None;
 5201        };
 5202
 5203        let (buffer, cursor_buffer_position) =
 5204            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5205
 5206        self.edit_prediction_settings =
 5207            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5208
 5209        if !self.edit_prediction_settings.is_enabled() {
 5210            self.discard_inline_completion(false, cx);
 5211            return None;
 5212        }
 5213
 5214        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5215        let edits = inline_completion
 5216            .edits
 5217            .into_iter()
 5218            .flat_map(|(range, new_text)| {
 5219                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5220                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5221                Some((start..end, new_text))
 5222            })
 5223            .collect::<Vec<_>>();
 5224        if edits.is_empty() {
 5225            return None;
 5226        }
 5227
 5228        let first_edit_start = edits.first().unwrap().0.start;
 5229        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5230        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5231
 5232        let last_edit_end = edits.last().unwrap().0.end;
 5233        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5234        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5235
 5236        let cursor_row = cursor.to_point(&multibuffer).row;
 5237
 5238        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5239
 5240        let mut inlay_ids = Vec::new();
 5241        let invalidation_row_range;
 5242        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5243            Some(cursor_row..edit_end_row)
 5244        } else if cursor_row > edit_end_row {
 5245            Some(edit_start_row..cursor_row)
 5246        } else {
 5247            None
 5248        };
 5249        let is_move =
 5250            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5251        let completion = if is_move {
 5252            invalidation_row_range =
 5253                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5254            let target = first_edit_start;
 5255            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5256            // TODO: Base this off of TreeSitter or word boundaries?
 5257            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5258                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5259                Bias::Left,
 5260            ));
 5261            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5262                Point::new(target_point.row, target_point.column + 20),
 5263                Bias::Right,
 5264            ));
 5265            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5266            InlineCompletion::Move {
 5267                target,
 5268                range_around_target,
 5269                snapshot,
 5270            }
 5271        } else {
 5272            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5273                && !self.inline_completions_hidden_for_vim_mode;
 5274            if show_completions_in_buffer {
 5275                if edits
 5276                    .iter()
 5277                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5278                {
 5279                    let mut inlays = Vec::new();
 5280                    for (range, new_text) in &edits {
 5281                        let inlay = Inlay::inline_completion(
 5282                            post_inc(&mut self.next_inlay_id),
 5283                            range.start,
 5284                            new_text.as_str(),
 5285                        );
 5286                        inlay_ids.push(inlay.id);
 5287                        inlays.push(inlay);
 5288                    }
 5289
 5290                    self.splice_inlays(&[], inlays, cx);
 5291                } else {
 5292                    let background_color = cx.theme().status().deleted_background;
 5293                    self.highlight_text::<InlineCompletionHighlight>(
 5294                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5295                        HighlightStyle {
 5296                            background_color: Some(background_color),
 5297                            ..Default::default()
 5298                        },
 5299                        cx,
 5300                    );
 5301                }
 5302            }
 5303
 5304            invalidation_row_range = edit_start_row..edit_end_row;
 5305
 5306            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5307                if provider.show_tab_accept_marker() {
 5308                    EditDisplayMode::TabAccept
 5309                } else {
 5310                    EditDisplayMode::Inline
 5311                }
 5312            } else {
 5313                EditDisplayMode::DiffPopover
 5314            };
 5315
 5316            InlineCompletion::Edit {
 5317                edits,
 5318                edit_preview: inline_completion.edit_preview,
 5319                display_mode,
 5320                snapshot,
 5321            }
 5322        };
 5323
 5324        let invalidation_range = multibuffer
 5325            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5326            ..multibuffer.anchor_after(Point::new(
 5327                invalidation_row_range.end,
 5328                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5329            ));
 5330
 5331        self.stale_inline_completion_in_menu = None;
 5332        self.active_inline_completion = Some(InlineCompletionState {
 5333            inlay_ids,
 5334            completion,
 5335            completion_id: inline_completion.id,
 5336            invalidation_range,
 5337        });
 5338
 5339        cx.notify();
 5340
 5341        Some(())
 5342    }
 5343
 5344    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5345        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5346    }
 5347
 5348    fn render_code_actions_indicator(
 5349        &self,
 5350        _style: &EditorStyle,
 5351        row: DisplayRow,
 5352        is_active: bool,
 5353        cx: &mut Context<Self>,
 5354    ) -> Option<IconButton> {
 5355        if self.available_code_actions.is_some() {
 5356            Some(
 5357                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5358                    .shape(ui::IconButtonShape::Square)
 5359                    .icon_size(IconSize::XSmall)
 5360                    .icon_color(Color::Muted)
 5361                    .toggle_state(is_active)
 5362                    .tooltip({
 5363                        let focus_handle = self.focus_handle.clone();
 5364                        move |window, cx| {
 5365                            Tooltip::for_action_in(
 5366                                "Toggle Code Actions",
 5367                                &ToggleCodeActions {
 5368                                    deployed_from_indicator: None,
 5369                                },
 5370                                &focus_handle,
 5371                                window,
 5372                                cx,
 5373                            )
 5374                        }
 5375                    })
 5376                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5377                        window.focus(&editor.focus_handle(cx));
 5378                        editor.toggle_code_actions(
 5379                            &ToggleCodeActions {
 5380                                deployed_from_indicator: Some(row),
 5381                            },
 5382                            window,
 5383                            cx,
 5384                        );
 5385                    })),
 5386            )
 5387        } else {
 5388            None
 5389        }
 5390    }
 5391
 5392    fn clear_tasks(&mut self) {
 5393        self.tasks.clear()
 5394    }
 5395
 5396    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5397        if self.tasks.insert(key, value).is_some() {
 5398            // This case should hopefully be rare, but just in case...
 5399            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5400        }
 5401    }
 5402
 5403    fn build_tasks_context(
 5404        project: &Entity<Project>,
 5405        buffer: &Entity<Buffer>,
 5406        buffer_row: u32,
 5407        tasks: &Arc<RunnableTasks>,
 5408        cx: &mut Context<Self>,
 5409    ) -> Task<Option<task::TaskContext>> {
 5410        let position = Point::new(buffer_row, tasks.column);
 5411        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5412        let location = Location {
 5413            buffer: buffer.clone(),
 5414            range: range_start..range_start,
 5415        };
 5416        // Fill in the environmental variables from the tree-sitter captures
 5417        let mut captured_task_variables = TaskVariables::default();
 5418        for (capture_name, value) in tasks.extra_variables.clone() {
 5419            captured_task_variables.insert(
 5420                task::VariableName::Custom(capture_name.into()),
 5421                value.clone(),
 5422            );
 5423        }
 5424        project.update(cx, |project, cx| {
 5425            project.task_store().update(cx, |task_store, cx| {
 5426                task_store.task_context_for_location(captured_task_variables, location, cx)
 5427            })
 5428        })
 5429    }
 5430
 5431    pub fn spawn_nearest_task(
 5432        &mut self,
 5433        action: &SpawnNearestTask,
 5434        window: &mut Window,
 5435        cx: &mut Context<Self>,
 5436    ) {
 5437        let Some((workspace, _)) = self.workspace.clone() else {
 5438            return;
 5439        };
 5440        let Some(project) = self.project.clone() else {
 5441            return;
 5442        };
 5443
 5444        // Try to find a closest, enclosing node using tree-sitter that has a
 5445        // task
 5446        let Some((buffer, buffer_row, tasks)) = self
 5447            .find_enclosing_node_task(cx)
 5448            // Or find the task that's closest in row-distance.
 5449            .or_else(|| self.find_closest_task(cx))
 5450        else {
 5451            return;
 5452        };
 5453
 5454        let reveal_strategy = action.reveal;
 5455        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5456        cx.spawn_in(window, |_, mut cx| async move {
 5457            let context = task_context.await?;
 5458            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5459
 5460            let resolved = resolved_task.resolved.as_mut()?;
 5461            resolved.reveal = reveal_strategy;
 5462
 5463            workspace
 5464                .update(&mut cx, |workspace, cx| {
 5465                    workspace::tasks::schedule_resolved_task(
 5466                        workspace,
 5467                        task_source_kind,
 5468                        resolved_task,
 5469                        false,
 5470                        cx,
 5471                    );
 5472                })
 5473                .ok()
 5474        })
 5475        .detach();
 5476    }
 5477
 5478    fn find_closest_task(
 5479        &mut self,
 5480        cx: &mut Context<Self>,
 5481    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5482        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5483
 5484        let ((buffer_id, row), tasks) = self
 5485            .tasks
 5486            .iter()
 5487            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5488
 5489        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5490        let tasks = Arc::new(tasks.to_owned());
 5491        Some((buffer, *row, tasks))
 5492    }
 5493
 5494    fn find_enclosing_node_task(
 5495        &mut self,
 5496        cx: &mut Context<Self>,
 5497    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5498        let snapshot = self.buffer.read(cx).snapshot(cx);
 5499        let offset = self.selections.newest::<usize>(cx).head();
 5500        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5501        let buffer_id = excerpt.buffer().remote_id();
 5502
 5503        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5504        let mut cursor = layer.node().walk();
 5505
 5506        while cursor.goto_first_child_for_byte(offset).is_some() {
 5507            if cursor.node().end_byte() == offset {
 5508                cursor.goto_next_sibling();
 5509            }
 5510        }
 5511
 5512        // Ascend to the smallest ancestor that contains the range and has a task.
 5513        loop {
 5514            let node = cursor.node();
 5515            let node_range = node.byte_range();
 5516            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5517
 5518            // Check if this node contains our offset
 5519            if node_range.start <= offset && node_range.end >= offset {
 5520                // If it contains offset, check for task
 5521                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5522                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5523                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5524                }
 5525            }
 5526
 5527            if !cursor.goto_parent() {
 5528                break;
 5529            }
 5530        }
 5531        None
 5532    }
 5533
 5534    fn render_run_indicator(
 5535        &self,
 5536        _style: &EditorStyle,
 5537        is_active: bool,
 5538        row: DisplayRow,
 5539        cx: &mut Context<Self>,
 5540    ) -> IconButton {
 5541        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5542            .shape(ui::IconButtonShape::Square)
 5543            .icon_size(IconSize::XSmall)
 5544            .icon_color(Color::Muted)
 5545            .toggle_state(is_active)
 5546            .on_click(cx.listener(move |editor, _e, window, cx| {
 5547                window.focus(&editor.focus_handle(cx));
 5548                editor.toggle_code_actions(
 5549                    &ToggleCodeActions {
 5550                        deployed_from_indicator: Some(row),
 5551                    },
 5552                    window,
 5553                    cx,
 5554                );
 5555            }))
 5556    }
 5557
 5558    pub fn context_menu_visible(&self) -> bool {
 5559        !self.previewing_inline_completion
 5560            && self
 5561                .context_menu
 5562                .borrow()
 5563                .as_ref()
 5564                .map_or(false, |menu| menu.visible())
 5565    }
 5566
 5567    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5568        self.context_menu
 5569            .borrow()
 5570            .as_ref()
 5571            .map(|menu| menu.origin())
 5572    }
 5573
 5574    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5575        px(30.)
 5576    }
 5577
 5578    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5579        if self.read_only(cx) {
 5580            cx.theme().players().read_only()
 5581        } else {
 5582            self.style.as_ref().unwrap().local_player
 5583        }
 5584    }
 5585
 5586    #[allow(clippy::too_many_arguments)]
 5587    fn render_edit_prediction_cursor_popover(
 5588        &self,
 5589        min_width: Pixels,
 5590        max_width: Pixels,
 5591        cursor_point: Point,
 5592        style: &EditorStyle,
 5593        accept_keystroke: &gpui::Keystroke,
 5594        window: &Window,
 5595        cx: &mut Context<Editor>,
 5596    ) -> Option<AnyElement> {
 5597        let provider = self.edit_prediction_provider.as_ref()?;
 5598
 5599        if provider.provider.needs_terms_acceptance(cx) {
 5600            return Some(
 5601                h_flex()
 5602                    .min_w(min_width)
 5603                    .flex_1()
 5604                    .px_2()
 5605                    .py_1()
 5606                    .gap_3()
 5607                    .elevation_2(cx)
 5608                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5609                    .id("accept-terms")
 5610                    .cursor_pointer()
 5611                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5612                    .on_click(cx.listener(|this, _event, window, cx| {
 5613                        cx.stop_propagation();
 5614                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5615                        window.dispatch_action(
 5616                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5617                            cx,
 5618                        );
 5619                    }))
 5620                    .child(
 5621                        h_flex()
 5622                            .flex_1()
 5623                            .gap_2()
 5624                            .child(Icon::new(IconName::ZedPredict))
 5625                            .child(Label::new("Accept Terms of Service"))
 5626                            .child(div().w_full())
 5627                            .child(
 5628                                Icon::new(IconName::ArrowUpRight)
 5629                                    .color(Color::Muted)
 5630                                    .size(IconSize::Small),
 5631                            )
 5632                            .into_any_element(),
 5633                    )
 5634                    .into_any(),
 5635            );
 5636        }
 5637
 5638        let is_refreshing = provider.provider.is_refreshing(cx);
 5639
 5640        fn pending_completion_container() -> Div {
 5641            h_flex()
 5642                .h_full()
 5643                .flex_1()
 5644                .gap_2()
 5645                .child(Icon::new(IconName::ZedPredict))
 5646        }
 5647
 5648        let completion = match &self.active_inline_completion {
 5649            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5650                completion,
 5651                cursor_point,
 5652                style,
 5653                window,
 5654                cx,
 5655            )?,
 5656
 5657            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5658                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5659                    stale_completion,
 5660                    cursor_point,
 5661                    style,
 5662                    window,
 5663                    cx,
 5664                )?,
 5665
 5666                None => {
 5667                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5668                }
 5669            },
 5670
 5671            None => pending_completion_container().child(Label::new("No Prediction")),
 5672        };
 5673
 5674        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5675        let completion = completion.font(buffer_font.clone());
 5676
 5677        let completion = if is_refreshing {
 5678            completion
 5679                .with_animation(
 5680                    "loading-completion",
 5681                    Animation::new(Duration::from_secs(2))
 5682                        .repeat()
 5683                        .with_easing(pulsating_between(0.4, 0.8)),
 5684                    |label, delta| label.opacity(delta),
 5685                )
 5686                .into_any_element()
 5687        } else {
 5688            completion.into_any_element()
 5689        };
 5690
 5691        let has_completion = self.active_inline_completion.is_some();
 5692
 5693        Some(
 5694            h_flex()
 5695                .min_w(min_width)
 5696                .max_w(max_width)
 5697                .flex_1()
 5698                .px_2()
 5699                .py_1()
 5700                .elevation_2(cx)
 5701                .child(completion)
 5702                .child(ui::Divider::vertical())
 5703                .child(
 5704                    h_flex()
 5705                        .h_full()
 5706                        .gap_1()
 5707                        .pl_2()
 5708                        .child(h_flex().font(buffer_font.clone()).gap_1().children(
 5709                            ui::render_modifiers(
 5710                                &accept_keystroke.modifiers,
 5711                                PlatformStyle::platform(),
 5712                                Some(if !has_completion {
 5713                                    Color::Muted
 5714                                } else {
 5715                                    Color::Default
 5716                                }),
 5717                                None,
 5718                                true,
 5719                            ),
 5720                        ))
 5721                        .child(Label::new("Preview").into_any_element())
 5722                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5723                )
 5724                .into_any(),
 5725        )
 5726    }
 5727
 5728    fn render_edit_prediction_cursor_popover_preview(
 5729        &self,
 5730        completion: &InlineCompletionState,
 5731        cursor_point: Point,
 5732        style: &EditorStyle,
 5733        window: &Window,
 5734        cx: &mut Context<Editor>,
 5735    ) -> Option<Div> {
 5736        use text::ToPoint as _;
 5737
 5738        fn render_relative_row_jump(
 5739            prefix: impl Into<String>,
 5740            current_row: u32,
 5741            target_row: u32,
 5742        ) -> Div {
 5743            let (row_diff, arrow) = if target_row < current_row {
 5744                (current_row - target_row, IconName::ArrowUp)
 5745            } else {
 5746                (target_row - current_row, IconName::ArrowDown)
 5747            };
 5748
 5749            h_flex()
 5750                .child(
 5751                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5752                        .color(Color::Muted)
 5753                        .size(LabelSize::Small),
 5754                )
 5755                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5756        }
 5757
 5758        match &completion.completion {
 5759            InlineCompletion::Edit {
 5760                edits,
 5761                edit_preview,
 5762                snapshot,
 5763                display_mode: _,
 5764            } => {
 5765                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5766
 5767                let highlighted_edits = crate::inline_completion_edit_text(
 5768                    &snapshot,
 5769                    &edits,
 5770                    edit_preview.as_ref()?,
 5771                    true,
 5772                    cx,
 5773                );
 5774
 5775                let len_total = highlighted_edits.text.len();
 5776                let first_line = &highlighted_edits.text
 5777                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5778                let first_line_len = first_line.len();
 5779
 5780                let first_highlight_start = highlighted_edits
 5781                    .highlights
 5782                    .first()
 5783                    .map_or(0, |(range, _)| range.start);
 5784                let drop_prefix_len = first_line
 5785                    .char_indices()
 5786                    .find(|(_, c)| !c.is_whitespace())
 5787                    .map_or(first_highlight_start, |(ix, _)| {
 5788                        ix.min(first_highlight_start)
 5789                    });
 5790
 5791                let preview_text = &first_line[drop_prefix_len..];
 5792                let preview_len = preview_text.len();
 5793                let highlights = highlighted_edits
 5794                    .highlights
 5795                    .into_iter()
 5796                    .take_until(|(range, _)| range.start > first_line_len)
 5797                    .map(|(range, style)| {
 5798                        (
 5799                            range.start - drop_prefix_len
 5800                                ..(range.end - drop_prefix_len).min(preview_len),
 5801                            style,
 5802                        )
 5803                    });
 5804
 5805                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5806                    .with_highlights(&style.text, highlights);
 5807
 5808                let preview = h_flex()
 5809                    .gap_1()
 5810                    .min_w_16()
 5811                    .child(styled_text)
 5812                    .when(len_total > first_line_len, |parent| parent.child(""));
 5813
 5814                let left = if first_edit_row != cursor_point.row {
 5815                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5816                        .into_any_element()
 5817                } else {
 5818                    Icon::new(IconName::ZedPredict).into_any_element()
 5819                };
 5820
 5821                Some(
 5822                    h_flex()
 5823                        .h_full()
 5824                        .flex_1()
 5825                        .gap_2()
 5826                        .pr_1()
 5827                        .overflow_x_hidden()
 5828                        .child(left)
 5829                        .child(preview),
 5830                )
 5831            }
 5832
 5833            InlineCompletion::Move {
 5834                target,
 5835                range_around_target,
 5836                snapshot,
 5837            } => {
 5838                let highlighted_text = snapshot.highlighted_text_for_range(
 5839                    range_around_target.clone(),
 5840                    None,
 5841                    &style.syntax,
 5842                );
 5843                let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
 5844                    "Jump ",
 5845                    cursor_point.row,
 5846                    target.text_anchor.to_point(&snapshot).row,
 5847                ));
 5848
 5849                if highlighted_text.text.is_empty() {
 5850                    return Some(base);
 5851                }
 5852
 5853                let cursor_color = self.current_user_player_color(cx).cursor;
 5854
 5855                let start_point = range_around_target.start.to_point(&snapshot);
 5856                let end_point = range_around_target.end.to_point(&snapshot);
 5857                let target_point = target.text_anchor.to_point(&snapshot);
 5858
 5859                let styled_text = highlighted_text.to_styled_text(&style.text);
 5860                let text_len = highlighted_text.text.len();
 5861
 5862                let cursor_relative_position = window
 5863                    .text_system()
 5864                    .layout_line(
 5865                        highlighted_text.text,
 5866                        style.text.font_size.to_pixels(window.rem_size()),
 5867                        // We don't need to include highlights
 5868                        // because we are only using this for the cursor position
 5869                        &[TextRun {
 5870                            len: text_len,
 5871                            font: style.text.font(),
 5872                            color: style.text.color,
 5873                            background_color: None,
 5874                            underline: None,
 5875                            strikethrough: None,
 5876                        }],
 5877                    )
 5878                    .log_err()
 5879                    .map(|line| {
 5880                        line.x_for_index(
 5881                            target_point.column.saturating_sub(start_point.column) as usize
 5882                        )
 5883                    });
 5884
 5885                let fade_before = start_point.column > 0;
 5886                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5887
 5888                let background = cx.theme().colors().elevated_surface_background;
 5889
 5890                let preview = h_flex()
 5891                    .relative()
 5892                    .child(styled_text)
 5893                    .when(fade_before, |parent| {
 5894                        parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
 5895                            linear_gradient(
 5896                                90.,
 5897                                linear_color_stop(background, 0.),
 5898                                linear_color_stop(background.opacity(0.), 1.),
 5899                            ),
 5900                        ))
 5901                    })
 5902                    .when(fade_after, |parent| {
 5903                        parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
 5904                            linear_gradient(
 5905                                -90.,
 5906                                linear_color_stop(background, 0.),
 5907                                linear_color_stop(background.opacity(0.), 1.),
 5908                            ),
 5909                        ))
 5910                    })
 5911                    .when_some(cursor_relative_position, |parent, position| {
 5912                        parent.child(
 5913                            div()
 5914                                .w(px(2.))
 5915                                .h_full()
 5916                                .bg(cursor_color)
 5917                                .absolute()
 5918                                .top_0()
 5919                                .left(position),
 5920                        )
 5921                    });
 5922
 5923                Some(base.child(preview))
 5924            }
 5925        }
 5926    }
 5927
 5928    fn render_context_menu(
 5929        &self,
 5930        style: &EditorStyle,
 5931        max_height_in_lines: u32,
 5932        y_flipped: bool,
 5933        window: &mut Window,
 5934        cx: &mut Context<Editor>,
 5935    ) -> Option<AnyElement> {
 5936        let menu = self.context_menu.borrow();
 5937        let menu = menu.as_ref()?;
 5938        if !menu.visible() {
 5939            return None;
 5940        };
 5941        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5942    }
 5943
 5944    fn render_context_menu_aside(
 5945        &self,
 5946        style: &EditorStyle,
 5947        max_size: Size<Pixels>,
 5948        cx: &mut Context<Editor>,
 5949    ) -> Option<AnyElement> {
 5950        self.context_menu.borrow().as_ref().and_then(|menu| {
 5951            if menu.visible() {
 5952                menu.render_aside(
 5953                    style,
 5954                    max_size,
 5955                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5956                    cx,
 5957                )
 5958            } else {
 5959                None
 5960            }
 5961        })
 5962    }
 5963
 5964    fn hide_context_menu(
 5965        &mut self,
 5966        window: &mut Window,
 5967        cx: &mut Context<Self>,
 5968    ) -> Option<CodeContextMenu> {
 5969        cx.notify();
 5970        self.completion_tasks.clear();
 5971        let context_menu = self.context_menu.borrow_mut().take();
 5972        self.stale_inline_completion_in_menu.take();
 5973        self.update_visible_inline_completion(window, cx);
 5974        context_menu
 5975    }
 5976
 5977    fn show_snippet_choices(
 5978        &mut self,
 5979        choices: &Vec<String>,
 5980        selection: Range<Anchor>,
 5981        cx: &mut Context<Self>,
 5982    ) {
 5983        if selection.start.buffer_id.is_none() {
 5984            return;
 5985        }
 5986        let buffer_id = selection.start.buffer_id.unwrap();
 5987        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5988        let id = post_inc(&mut self.next_completion_id);
 5989
 5990        if let Some(buffer) = buffer {
 5991            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5992                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5993            ));
 5994        }
 5995    }
 5996
 5997    pub fn insert_snippet(
 5998        &mut self,
 5999        insertion_ranges: &[Range<usize>],
 6000        snippet: Snippet,
 6001        window: &mut Window,
 6002        cx: &mut Context<Self>,
 6003    ) -> Result<()> {
 6004        struct Tabstop<T> {
 6005            is_end_tabstop: bool,
 6006            ranges: Vec<Range<T>>,
 6007            choices: Option<Vec<String>>,
 6008        }
 6009
 6010        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6011            let snippet_text: Arc<str> = snippet.text.clone().into();
 6012            buffer.edit(
 6013                insertion_ranges
 6014                    .iter()
 6015                    .cloned()
 6016                    .map(|range| (range, snippet_text.clone())),
 6017                Some(AutoindentMode::EachLine),
 6018                cx,
 6019            );
 6020
 6021            let snapshot = &*buffer.read(cx);
 6022            let snippet = &snippet;
 6023            snippet
 6024                .tabstops
 6025                .iter()
 6026                .map(|tabstop| {
 6027                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6028                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6029                    });
 6030                    let mut tabstop_ranges = tabstop
 6031                        .ranges
 6032                        .iter()
 6033                        .flat_map(|tabstop_range| {
 6034                            let mut delta = 0_isize;
 6035                            insertion_ranges.iter().map(move |insertion_range| {
 6036                                let insertion_start = insertion_range.start as isize + delta;
 6037                                delta +=
 6038                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6039
 6040                                let start = ((insertion_start + tabstop_range.start) as usize)
 6041                                    .min(snapshot.len());
 6042                                let end = ((insertion_start + tabstop_range.end) as usize)
 6043                                    .min(snapshot.len());
 6044                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6045                            })
 6046                        })
 6047                        .collect::<Vec<_>>();
 6048                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6049
 6050                    Tabstop {
 6051                        is_end_tabstop,
 6052                        ranges: tabstop_ranges,
 6053                        choices: tabstop.choices.clone(),
 6054                    }
 6055                })
 6056                .collect::<Vec<_>>()
 6057        });
 6058        if let Some(tabstop) = tabstops.first() {
 6059            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6060                s.select_ranges(tabstop.ranges.iter().cloned());
 6061            });
 6062
 6063            if let Some(choices) = &tabstop.choices {
 6064                if let Some(selection) = tabstop.ranges.first() {
 6065                    self.show_snippet_choices(choices, selection.clone(), cx)
 6066                }
 6067            }
 6068
 6069            // If we're already at the last tabstop and it's at the end of the snippet,
 6070            // we're done, we don't need to keep the state around.
 6071            if !tabstop.is_end_tabstop {
 6072                let choices = tabstops
 6073                    .iter()
 6074                    .map(|tabstop| tabstop.choices.clone())
 6075                    .collect();
 6076
 6077                let ranges = tabstops
 6078                    .into_iter()
 6079                    .map(|tabstop| tabstop.ranges)
 6080                    .collect::<Vec<_>>();
 6081
 6082                self.snippet_stack.push(SnippetState {
 6083                    active_index: 0,
 6084                    ranges,
 6085                    choices,
 6086                });
 6087            }
 6088
 6089            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6090            if self.autoclose_regions.is_empty() {
 6091                let snapshot = self.buffer.read(cx).snapshot(cx);
 6092                for selection in &mut self.selections.all::<Point>(cx) {
 6093                    let selection_head = selection.head();
 6094                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6095                        continue;
 6096                    };
 6097
 6098                    let mut bracket_pair = None;
 6099                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6100                    let prev_chars = snapshot
 6101                        .reversed_chars_at(selection_head)
 6102                        .collect::<String>();
 6103                    for (pair, enabled) in scope.brackets() {
 6104                        if enabled
 6105                            && pair.close
 6106                            && prev_chars.starts_with(pair.start.as_str())
 6107                            && next_chars.starts_with(pair.end.as_str())
 6108                        {
 6109                            bracket_pair = Some(pair.clone());
 6110                            break;
 6111                        }
 6112                    }
 6113                    if let Some(pair) = bracket_pair {
 6114                        let start = snapshot.anchor_after(selection_head);
 6115                        let end = snapshot.anchor_after(selection_head);
 6116                        self.autoclose_regions.push(AutocloseRegion {
 6117                            selection_id: selection.id,
 6118                            range: start..end,
 6119                            pair,
 6120                        });
 6121                    }
 6122                }
 6123            }
 6124        }
 6125        Ok(())
 6126    }
 6127
 6128    pub fn move_to_next_snippet_tabstop(
 6129        &mut self,
 6130        window: &mut Window,
 6131        cx: &mut Context<Self>,
 6132    ) -> bool {
 6133        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6134    }
 6135
 6136    pub fn move_to_prev_snippet_tabstop(
 6137        &mut self,
 6138        window: &mut Window,
 6139        cx: &mut Context<Self>,
 6140    ) -> bool {
 6141        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6142    }
 6143
 6144    pub fn move_to_snippet_tabstop(
 6145        &mut self,
 6146        bias: Bias,
 6147        window: &mut Window,
 6148        cx: &mut Context<Self>,
 6149    ) -> bool {
 6150        if let Some(mut snippet) = self.snippet_stack.pop() {
 6151            match bias {
 6152                Bias::Left => {
 6153                    if snippet.active_index > 0 {
 6154                        snippet.active_index -= 1;
 6155                    } else {
 6156                        self.snippet_stack.push(snippet);
 6157                        return false;
 6158                    }
 6159                }
 6160                Bias::Right => {
 6161                    if snippet.active_index + 1 < snippet.ranges.len() {
 6162                        snippet.active_index += 1;
 6163                    } else {
 6164                        self.snippet_stack.push(snippet);
 6165                        return false;
 6166                    }
 6167                }
 6168            }
 6169            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6170                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6171                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6172                });
 6173
 6174                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6175                    if let Some(selection) = current_ranges.first() {
 6176                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6177                    }
 6178                }
 6179
 6180                // If snippet state is not at the last tabstop, push it back on the stack
 6181                if snippet.active_index + 1 < snippet.ranges.len() {
 6182                    self.snippet_stack.push(snippet);
 6183                }
 6184                return true;
 6185            }
 6186        }
 6187
 6188        false
 6189    }
 6190
 6191    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6192        self.transact(window, cx, |this, window, cx| {
 6193            this.select_all(&SelectAll, window, cx);
 6194            this.insert("", window, cx);
 6195        });
 6196    }
 6197
 6198    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6199        self.transact(window, cx, |this, window, cx| {
 6200            this.select_autoclose_pair(window, cx);
 6201            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6202            if !this.linked_edit_ranges.is_empty() {
 6203                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6204                let snapshot = this.buffer.read(cx).snapshot(cx);
 6205
 6206                for selection in selections.iter() {
 6207                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6208                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6209                    if selection_start.buffer_id != selection_end.buffer_id {
 6210                        continue;
 6211                    }
 6212                    if let Some(ranges) =
 6213                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6214                    {
 6215                        for (buffer, entries) in ranges {
 6216                            linked_ranges.entry(buffer).or_default().extend(entries);
 6217                        }
 6218                    }
 6219                }
 6220            }
 6221
 6222            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6223            if !this.selections.line_mode {
 6224                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6225                for selection in &mut selections {
 6226                    if selection.is_empty() {
 6227                        let old_head = selection.head();
 6228                        let mut new_head =
 6229                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6230                                .to_point(&display_map);
 6231                        if let Some((buffer, line_buffer_range)) = display_map
 6232                            .buffer_snapshot
 6233                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6234                        {
 6235                            let indent_size =
 6236                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6237                            let indent_len = match indent_size.kind {
 6238                                IndentKind::Space => {
 6239                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6240                                }
 6241                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6242                            };
 6243                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6244                                let indent_len = indent_len.get();
 6245                                new_head = cmp::min(
 6246                                    new_head,
 6247                                    MultiBufferPoint::new(
 6248                                        old_head.row,
 6249                                        ((old_head.column - 1) / indent_len) * indent_len,
 6250                                    ),
 6251                                );
 6252                            }
 6253                        }
 6254
 6255                        selection.set_head(new_head, SelectionGoal::None);
 6256                    }
 6257                }
 6258            }
 6259
 6260            this.signature_help_state.set_backspace_pressed(true);
 6261            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6262                s.select(selections)
 6263            });
 6264            this.insert("", window, cx);
 6265            let empty_str: Arc<str> = Arc::from("");
 6266            for (buffer, edits) in linked_ranges {
 6267                let snapshot = buffer.read(cx).snapshot();
 6268                use text::ToPoint as TP;
 6269
 6270                let edits = edits
 6271                    .into_iter()
 6272                    .map(|range| {
 6273                        let end_point = TP::to_point(&range.end, &snapshot);
 6274                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6275
 6276                        if end_point == start_point {
 6277                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6278                                .saturating_sub(1);
 6279                            start_point =
 6280                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6281                        };
 6282
 6283                        (start_point..end_point, empty_str.clone())
 6284                    })
 6285                    .sorted_by_key(|(range, _)| range.start)
 6286                    .collect::<Vec<_>>();
 6287                buffer.update(cx, |this, cx| {
 6288                    this.edit(edits, None, cx);
 6289                })
 6290            }
 6291            this.refresh_inline_completion(true, false, window, cx);
 6292            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6293        });
 6294    }
 6295
 6296    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6297        self.transact(window, cx, |this, window, cx| {
 6298            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6299                let line_mode = s.line_mode;
 6300                s.move_with(|map, selection| {
 6301                    if selection.is_empty() && !line_mode {
 6302                        let cursor = movement::right(map, selection.head());
 6303                        selection.end = cursor;
 6304                        selection.reversed = true;
 6305                        selection.goal = SelectionGoal::None;
 6306                    }
 6307                })
 6308            });
 6309            this.insert("", window, cx);
 6310            this.refresh_inline_completion(true, false, window, cx);
 6311        });
 6312    }
 6313
 6314    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6315        if self.move_to_prev_snippet_tabstop(window, cx) {
 6316            return;
 6317        }
 6318
 6319        self.outdent(&Outdent, window, cx);
 6320    }
 6321
 6322    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6323        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6324            return;
 6325        }
 6326
 6327        let mut selections = self.selections.all_adjusted(cx);
 6328        let buffer = self.buffer.read(cx);
 6329        let snapshot = buffer.snapshot(cx);
 6330        let rows_iter = selections.iter().map(|s| s.head().row);
 6331        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6332
 6333        let mut edits = Vec::new();
 6334        let mut prev_edited_row = 0;
 6335        let mut row_delta = 0;
 6336        for selection in &mut selections {
 6337            if selection.start.row != prev_edited_row {
 6338                row_delta = 0;
 6339            }
 6340            prev_edited_row = selection.end.row;
 6341
 6342            // If the selection is non-empty, then increase the indentation of the selected lines.
 6343            if !selection.is_empty() {
 6344                row_delta =
 6345                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6346                continue;
 6347            }
 6348
 6349            // If the selection is empty and the cursor is in the leading whitespace before the
 6350            // suggested indentation, then auto-indent the line.
 6351            let cursor = selection.head();
 6352            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6353            if let Some(suggested_indent) =
 6354                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6355            {
 6356                if cursor.column < suggested_indent.len
 6357                    && cursor.column <= current_indent.len
 6358                    && current_indent.len <= suggested_indent.len
 6359                {
 6360                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6361                    selection.end = selection.start;
 6362                    if row_delta == 0 {
 6363                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6364                            cursor.row,
 6365                            current_indent,
 6366                            suggested_indent,
 6367                        ));
 6368                        row_delta = suggested_indent.len - current_indent.len;
 6369                    }
 6370                    continue;
 6371                }
 6372            }
 6373
 6374            // Otherwise, insert a hard or soft tab.
 6375            let settings = buffer.settings_at(cursor, cx);
 6376            let tab_size = if settings.hard_tabs {
 6377                IndentSize::tab()
 6378            } else {
 6379                let tab_size = settings.tab_size.get();
 6380                let char_column = snapshot
 6381                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6382                    .flat_map(str::chars)
 6383                    .count()
 6384                    + row_delta as usize;
 6385                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6386                IndentSize::spaces(chars_to_next_tab_stop)
 6387            };
 6388            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6389            selection.end = selection.start;
 6390            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6391            row_delta += tab_size.len;
 6392        }
 6393
 6394        self.transact(window, cx, |this, window, cx| {
 6395            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6396            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6397                s.select(selections)
 6398            });
 6399            this.refresh_inline_completion(true, false, window, cx);
 6400        });
 6401    }
 6402
 6403    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6404        if self.read_only(cx) {
 6405            return;
 6406        }
 6407        let mut selections = self.selections.all::<Point>(cx);
 6408        let mut prev_edited_row = 0;
 6409        let mut row_delta = 0;
 6410        let mut edits = Vec::new();
 6411        let buffer = self.buffer.read(cx);
 6412        let snapshot = buffer.snapshot(cx);
 6413        for selection in &mut selections {
 6414            if selection.start.row != prev_edited_row {
 6415                row_delta = 0;
 6416            }
 6417            prev_edited_row = selection.end.row;
 6418
 6419            row_delta =
 6420                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6421        }
 6422
 6423        self.transact(window, cx, |this, window, cx| {
 6424            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6425            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6426                s.select(selections)
 6427            });
 6428        });
 6429    }
 6430
 6431    fn indent_selection(
 6432        buffer: &MultiBuffer,
 6433        snapshot: &MultiBufferSnapshot,
 6434        selection: &mut Selection<Point>,
 6435        edits: &mut Vec<(Range<Point>, String)>,
 6436        delta_for_start_row: u32,
 6437        cx: &App,
 6438    ) -> u32 {
 6439        let settings = buffer.settings_at(selection.start, cx);
 6440        let tab_size = settings.tab_size.get();
 6441        let indent_kind = if settings.hard_tabs {
 6442            IndentKind::Tab
 6443        } else {
 6444            IndentKind::Space
 6445        };
 6446        let mut start_row = selection.start.row;
 6447        let mut end_row = selection.end.row + 1;
 6448
 6449        // If a selection ends at the beginning of a line, don't indent
 6450        // that last line.
 6451        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6452            end_row -= 1;
 6453        }
 6454
 6455        // Avoid re-indenting a row that has already been indented by a
 6456        // previous selection, but still update this selection's column
 6457        // to reflect that indentation.
 6458        if delta_for_start_row > 0 {
 6459            start_row += 1;
 6460            selection.start.column += delta_for_start_row;
 6461            if selection.end.row == selection.start.row {
 6462                selection.end.column += delta_for_start_row;
 6463            }
 6464        }
 6465
 6466        let mut delta_for_end_row = 0;
 6467        let has_multiple_rows = start_row + 1 != end_row;
 6468        for row in start_row..end_row {
 6469            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6470            let indent_delta = match (current_indent.kind, indent_kind) {
 6471                (IndentKind::Space, IndentKind::Space) => {
 6472                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6473                    IndentSize::spaces(columns_to_next_tab_stop)
 6474                }
 6475                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6476                (_, IndentKind::Tab) => IndentSize::tab(),
 6477            };
 6478
 6479            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6480                0
 6481            } else {
 6482                selection.start.column
 6483            };
 6484            let row_start = Point::new(row, start);
 6485            edits.push((
 6486                row_start..row_start,
 6487                indent_delta.chars().collect::<String>(),
 6488            ));
 6489
 6490            // Update this selection's endpoints to reflect the indentation.
 6491            if row == selection.start.row {
 6492                selection.start.column += indent_delta.len;
 6493            }
 6494            if row == selection.end.row {
 6495                selection.end.column += indent_delta.len;
 6496                delta_for_end_row = indent_delta.len;
 6497            }
 6498        }
 6499
 6500        if selection.start.row == selection.end.row {
 6501            delta_for_start_row + delta_for_end_row
 6502        } else {
 6503            delta_for_end_row
 6504        }
 6505    }
 6506
 6507    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6508        if self.read_only(cx) {
 6509            return;
 6510        }
 6511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6512        let selections = self.selections.all::<Point>(cx);
 6513        let mut deletion_ranges = Vec::new();
 6514        let mut last_outdent = None;
 6515        {
 6516            let buffer = self.buffer.read(cx);
 6517            let snapshot = buffer.snapshot(cx);
 6518            for selection in &selections {
 6519                let settings = buffer.settings_at(selection.start, cx);
 6520                let tab_size = settings.tab_size.get();
 6521                let mut rows = selection.spanned_rows(false, &display_map);
 6522
 6523                // Avoid re-outdenting a row that has already been outdented by a
 6524                // previous selection.
 6525                if let Some(last_row) = last_outdent {
 6526                    if last_row == rows.start {
 6527                        rows.start = rows.start.next_row();
 6528                    }
 6529                }
 6530                let has_multiple_rows = rows.len() > 1;
 6531                for row in rows.iter_rows() {
 6532                    let indent_size = snapshot.indent_size_for_line(row);
 6533                    if indent_size.len > 0 {
 6534                        let deletion_len = match indent_size.kind {
 6535                            IndentKind::Space => {
 6536                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6537                                if columns_to_prev_tab_stop == 0 {
 6538                                    tab_size
 6539                                } else {
 6540                                    columns_to_prev_tab_stop
 6541                                }
 6542                            }
 6543                            IndentKind::Tab => 1,
 6544                        };
 6545                        let start = if has_multiple_rows
 6546                            || deletion_len > selection.start.column
 6547                            || indent_size.len < selection.start.column
 6548                        {
 6549                            0
 6550                        } else {
 6551                            selection.start.column - deletion_len
 6552                        };
 6553                        deletion_ranges.push(
 6554                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6555                        );
 6556                        last_outdent = Some(row);
 6557                    }
 6558                }
 6559            }
 6560        }
 6561
 6562        self.transact(window, cx, |this, window, cx| {
 6563            this.buffer.update(cx, |buffer, cx| {
 6564                let empty_str: Arc<str> = Arc::default();
 6565                buffer.edit(
 6566                    deletion_ranges
 6567                        .into_iter()
 6568                        .map(|range| (range, empty_str.clone())),
 6569                    None,
 6570                    cx,
 6571                );
 6572            });
 6573            let selections = this.selections.all::<usize>(cx);
 6574            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6575                s.select(selections)
 6576            });
 6577        });
 6578    }
 6579
 6580    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6581        if self.read_only(cx) {
 6582            return;
 6583        }
 6584        let selections = self
 6585            .selections
 6586            .all::<usize>(cx)
 6587            .into_iter()
 6588            .map(|s| s.range());
 6589
 6590        self.transact(window, cx, |this, window, cx| {
 6591            this.buffer.update(cx, |buffer, cx| {
 6592                buffer.autoindent_ranges(selections, cx);
 6593            });
 6594            let selections = this.selections.all::<usize>(cx);
 6595            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6596                s.select(selections)
 6597            });
 6598        });
 6599    }
 6600
 6601    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6602        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6603        let selections = self.selections.all::<Point>(cx);
 6604
 6605        let mut new_cursors = Vec::new();
 6606        let mut edit_ranges = Vec::new();
 6607        let mut selections = selections.iter().peekable();
 6608        while let Some(selection) = selections.next() {
 6609            let mut rows = selection.spanned_rows(false, &display_map);
 6610            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6611
 6612            // Accumulate contiguous regions of rows that we want to delete.
 6613            while let Some(next_selection) = selections.peek() {
 6614                let next_rows = next_selection.spanned_rows(false, &display_map);
 6615                if next_rows.start <= rows.end {
 6616                    rows.end = next_rows.end;
 6617                    selections.next().unwrap();
 6618                } else {
 6619                    break;
 6620                }
 6621            }
 6622
 6623            let buffer = &display_map.buffer_snapshot;
 6624            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6625            let edit_end;
 6626            let cursor_buffer_row;
 6627            if buffer.max_point().row >= rows.end.0 {
 6628                // If there's a line after the range, delete the \n from the end of the row range
 6629                // and position the cursor on the next line.
 6630                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6631                cursor_buffer_row = rows.end;
 6632            } else {
 6633                // If there isn't a line after the range, delete the \n from the line before the
 6634                // start of the row range and position the cursor there.
 6635                edit_start = edit_start.saturating_sub(1);
 6636                edit_end = buffer.len();
 6637                cursor_buffer_row = rows.start.previous_row();
 6638            }
 6639
 6640            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6641            *cursor.column_mut() =
 6642                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6643
 6644            new_cursors.push((
 6645                selection.id,
 6646                buffer.anchor_after(cursor.to_point(&display_map)),
 6647            ));
 6648            edit_ranges.push(edit_start..edit_end);
 6649        }
 6650
 6651        self.transact(window, cx, |this, window, cx| {
 6652            let buffer = this.buffer.update(cx, |buffer, cx| {
 6653                let empty_str: Arc<str> = Arc::default();
 6654                buffer.edit(
 6655                    edit_ranges
 6656                        .into_iter()
 6657                        .map(|range| (range, empty_str.clone())),
 6658                    None,
 6659                    cx,
 6660                );
 6661                buffer.snapshot(cx)
 6662            });
 6663            let new_selections = new_cursors
 6664                .into_iter()
 6665                .map(|(id, cursor)| {
 6666                    let cursor = cursor.to_point(&buffer);
 6667                    Selection {
 6668                        id,
 6669                        start: cursor,
 6670                        end: cursor,
 6671                        reversed: false,
 6672                        goal: SelectionGoal::None,
 6673                    }
 6674                })
 6675                .collect();
 6676
 6677            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6678                s.select(new_selections);
 6679            });
 6680        });
 6681    }
 6682
 6683    pub fn join_lines_impl(
 6684        &mut self,
 6685        insert_whitespace: bool,
 6686        window: &mut Window,
 6687        cx: &mut Context<Self>,
 6688    ) {
 6689        if self.read_only(cx) {
 6690            return;
 6691        }
 6692        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6693        for selection in self.selections.all::<Point>(cx) {
 6694            let start = MultiBufferRow(selection.start.row);
 6695            // Treat single line selections as if they include the next line. Otherwise this action
 6696            // would do nothing for single line selections individual cursors.
 6697            let end = if selection.start.row == selection.end.row {
 6698                MultiBufferRow(selection.start.row + 1)
 6699            } else {
 6700                MultiBufferRow(selection.end.row)
 6701            };
 6702
 6703            if let Some(last_row_range) = row_ranges.last_mut() {
 6704                if start <= last_row_range.end {
 6705                    last_row_range.end = end;
 6706                    continue;
 6707                }
 6708            }
 6709            row_ranges.push(start..end);
 6710        }
 6711
 6712        let snapshot = self.buffer.read(cx).snapshot(cx);
 6713        let mut cursor_positions = Vec::new();
 6714        for row_range in &row_ranges {
 6715            let anchor = snapshot.anchor_before(Point::new(
 6716                row_range.end.previous_row().0,
 6717                snapshot.line_len(row_range.end.previous_row()),
 6718            ));
 6719            cursor_positions.push(anchor..anchor);
 6720        }
 6721
 6722        self.transact(window, cx, |this, window, cx| {
 6723            for row_range in row_ranges.into_iter().rev() {
 6724                for row in row_range.iter_rows().rev() {
 6725                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6726                    let next_line_row = row.next_row();
 6727                    let indent = snapshot.indent_size_for_line(next_line_row);
 6728                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6729
 6730                    let replace =
 6731                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6732                            " "
 6733                        } else {
 6734                            ""
 6735                        };
 6736
 6737                    this.buffer.update(cx, |buffer, cx| {
 6738                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6739                    });
 6740                }
 6741            }
 6742
 6743            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6744                s.select_anchor_ranges(cursor_positions)
 6745            });
 6746        });
 6747    }
 6748
 6749    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6750        self.join_lines_impl(true, window, cx);
 6751    }
 6752
 6753    pub fn sort_lines_case_sensitive(
 6754        &mut self,
 6755        _: &SortLinesCaseSensitive,
 6756        window: &mut Window,
 6757        cx: &mut Context<Self>,
 6758    ) {
 6759        self.manipulate_lines(window, cx, |lines| lines.sort())
 6760    }
 6761
 6762    pub fn sort_lines_case_insensitive(
 6763        &mut self,
 6764        _: &SortLinesCaseInsensitive,
 6765        window: &mut Window,
 6766        cx: &mut Context<Self>,
 6767    ) {
 6768        self.manipulate_lines(window, cx, |lines| {
 6769            lines.sort_by_key(|line| line.to_lowercase())
 6770        })
 6771    }
 6772
 6773    pub fn unique_lines_case_insensitive(
 6774        &mut self,
 6775        _: &UniqueLinesCaseInsensitive,
 6776        window: &mut Window,
 6777        cx: &mut Context<Self>,
 6778    ) {
 6779        self.manipulate_lines(window, cx, |lines| {
 6780            let mut seen = HashSet::default();
 6781            lines.retain(|line| seen.insert(line.to_lowercase()));
 6782        })
 6783    }
 6784
 6785    pub fn unique_lines_case_sensitive(
 6786        &mut self,
 6787        _: &UniqueLinesCaseSensitive,
 6788        window: &mut Window,
 6789        cx: &mut Context<Self>,
 6790    ) {
 6791        self.manipulate_lines(window, cx, |lines| {
 6792            let mut seen = HashSet::default();
 6793            lines.retain(|line| seen.insert(*line));
 6794        })
 6795    }
 6796
 6797    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6798        let mut revert_changes = HashMap::default();
 6799        let snapshot = self.snapshot(window, cx);
 6800        for hunk in snapshot
 6801            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6802        {
 6803            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6804        }
 6805        if !revert_changes.is_empty() {
 6806            self.transact(window, cx, |editor, window, cx| {
 6807                editor.revert(revert_changes, window, cx);
 6808            });
 6809        }
 6810    }
 6811
 6812    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6813        let Some(project) = self.project.clone() else {
 6814            return;
 6815        };
 6816        self.reload(project, window, cx)
 6817            .detach_and_notify_err(window, cx);
 6818    }
 6819
 6820    pub fn revert_selected_hunks(
 6821        &mut self,
 6822        _: &RevertSelectedHunks,
 6823        window: &mut Window,
 6824        cx: &mut Context<Self>,
 6825    ) {
 6826        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6827        self.revert_hunks_in_ranges(selections, window, cx);
 6828    }
 6829
 6830    fn revert_hunks_in_ranges(
 6831        &mut self,
 6832        ranges: impl Iterator<Item = Range<Point>>,
 6833        window: &mut Window,
 6834        cx: &mut Context<Editor>,
 6835    ) {
 6836        let mut revert_changes = HashMap::default();
 6837        let snapshot = self.snapshot(window, cx);
 6838        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6839            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6840        }
 6841        if !revert_changes.is_empty() {
 6842            self.transact(window, cx, |editor, window, cx| {
 6843                editor.revert(revert_changes, window, cx);
 6844            });
 6845        }
 6846    }
 6847
 6848    pub fn open_active_item_in_terminal(
 6849        &mut self,
 6850        _: &OpenInTerminal,
 6851        window: &mut Window,
 6852        cx: &mut Context<Self>,
 6853    ) {
 6854        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6855            let project_path = buffer.read(cx).project_path(cx)?;
 6856            let project = self.project.as_ref()?.read(cx);
 6857            let entry = project.entry_for_path(&project_path, cx)?;
 6858            let parent = match &entry.canonical_path {
 6859                Some(canonical_path) => canonical_path.to_path_buf(),
 6860                None => project.absolute_path(&project_path, cx)?,
 6861            }
 6862            .parent()?
 6863            .to_path_buf();
 6864            Some(parent)
 6865        }) {
 6866            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6867        }
 6868    }
 6869
 6870    pub fn prepare_revert_change(
 6871        &self,
 6872        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6873        hunk: &MultiBufferDiffHunk,
 6874        cx: &mut App,
 6875    ) -> Option<()> {
 6876        let buffer = self.buffer.read(cx);
 6877        let diff = buffer.diff_for(hunk.buffer_id)?;
 6878        let buffer = buffer.buffer(hunk.buffer_id)?;
 6879        let buffer = buffer.read(cx);
 6880        let original_text = diff
 6881            .read(cx)
 6882            .base_text()
 6883            .as_ref()?
 6884            .as_rope()
 6885            .slice(hunk.diff_base_byte_range.clone());
 6886        let buffer_snapshot = buffer.snapshot();
 6887        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6888        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6889            probe
 6890                .0
 6891                .start
 6892                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6893                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6894        }) {
 6895            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6896            Some(())
 6897        } else {
 6898            None
 6899        }
 6900    }
 6901
 6902    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6903        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6904    }
 6905
 6906    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6907        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6908    }
 6909
 6910    fn manipulate_lines<Fn>(
 6911        &mut self,
 6912        window: &mut Window,
 6913        cx: &mut Context<Self>,
 6914        mut callback: Fn,
 6915    ) where
 6916        Fn: FnMut(&mut Vec<&str>),
 6917    {
 6918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6919        let buffer = self.buffer.read(cx).snapshot(cx);
 6920
 6921        let mut edits = Vec::new();
 6922
 6923        let selections = self.selections.all::<Point>(cx);
 6924        let mut selections = selections.iter().peekable();
 6925        let mut contiguous_row_selections = Vec::new();
 6926        let mut new_selections = Vec::new();
 6927        let mut added_lines = 0;
 6928        let mut removed_lines = 0;
 6929
 6930        while let Some(selection) = selections.next() {
 6931            let (start_row, end_row) = consume_contiguous_rows(
 6932                &mut contiguous_row_selections,
 6933                selection,
 6934                &display_map,
 6935                &mut selections,
 6936            );
 6937
 6938            let start_point = Point::new(start_row.0, 0);
 6939            let end_point = Point::new(
 6940                end_row.previous_row().0,
 6941                buffer.line_len(end_row.previous_row()),
 6942            );
 6943            let text = buffer
 6944                .text_for_range(start_point..end_point)
 6945                .collect::<String>();
 6946
 6947            let mut lines = text.split('\n').collect_vec();
 6948
 6949            let lines_before = lines.len();
 6950            callback(&mut lines);
 6951            let lines_after = lines.len();
 6952
 6953            edits.push((start_point..end_point, lines.join("\n")));
 6954
 6955            // Selections must change based on added and removed line count
 6956            let start_row =
 6957                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6958            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6959            new_selections.push(Selection {
 6960                id: selection.id,
 6961                start: start_row,
 6962                end: end_row,
 6963                goal: SelectionGoal::None,
 6964                reversed: selection.reversed,
 6965            });
 6966
 6967            if lines_after > lines_before {
 6968                added_lines += lines_after - lines_before;
 6969            } else if lines_before > lines_after {
 6970                removed_lines += lines_before - lines_after;
 6971            }
 6972        }
 6973
 6974        self.transact(window, cx, |this, window, cx| {
 6975            let buffer = this.buffer.update(cx, |buffer, cx| {
 6976                buffer.edit(edits, None, cx);
 6977                buffer.snapshot(cx)
 6978            });
 6979
 6980            // Recalculate offsets on newly edited buffer
 6981            let new_selections = new_selections
 6982                .iter()
 6983                .map(|s| {
 6984                    let start_point = Point::new(s.start.0, 0);
 6985                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6986                    Selection {
 6987                        id: s.id,
 6988                        start: buffer.point_to_offset(start_point),
 6989                        end: buffer.point_to_offset(end_point),
 6990                        goal: s.goal,
 6991                        reversed: s.reversed,
 6992                    }
 6993                })
 6994                .collect();
 6995
 6996            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6997                s.select(new_selections);
 6998            });
 6999
 7000            this.request_autoscroll(Autoscroll::fit(), cx);
 7001        });
 7002    }
 7003
 7004    pub fn convert_to_upper_case(
 7005        &mut self,
 7006        _: &ConvertToUpperCase,
 7007        window: &mut Window,
 7008        cx: &mut Context<Self>,
 7009    ) {
 7010        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7011    }
 7012
 7013    pub fn convert_to_lower_case(
 7014        &mut self,
 7015        _: &ConvertToLowerCase,
 7016        window: &mut Window,
 7017        cx: &mut Context<Self>,
 7018    ) {
 7019        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7020    }
 7021
 7022    pub fn convert_to_title_case(
 7023        &mut self,
 7024        _: &ConvertToTitleCase,
 7025        window: &mut Window,
 7026        cx: &mut Context<Self>,
 7027    ) {
 7028        self.manipulate_text(window, cx, |text| {
 7029            text.split('\n')
 7030                .map(|line| line.to_case(Case::Title))
 7031                .join("\n")
 7032        })
 7033    }
 7034
 7035    pub fn convert_to_snake_case(
 7036        &mut self,
 7037        _: &ConvertToSnakeCase,
 7038        window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7042    }
 7043
 7044    pub fn convert_to_kebab_case(
 7045        &mut self,
 7046        _: &ConvertToKebabCase,
 7047        window: &mut Window,
 7048        cx: &mut Context<Self>,
 7049    ) {
 7050        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7051    }
 7052
 7053    pub fn convert_to_upper_camel_case(
 7054        &mut self,
 7055        _: &ConvertToUpperCamelCase,
 7056        window: &mut Window,
 7057        cx: &mut Context<Self>,
 7058    ) {
 7059        self.manipulate_text(window, cx, |text| {
 7060            text.split('\n')
 7061                .map(|line| line.to_case(Case::UpperCamel))
 7062                .join("\n")
 7063        })
 7064    }
 7065
 7066    pub fn convert_to_lower_camel_case(
 7067        &mut self,
 7068        _: &ConvertToLowerCamelCase,
 7069        window: &mut Window,
 7070        cx: &mut Context<Self>,
 7071    ) {
 7072        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7073    }
 7074
 7075    pub fn convert_to_opposite_case(
 7076        &mut self,
 7077        _: &ConvertToOppositeCase,
 7078        window: &mut Window,
 7079        cx: &mut Context<Self>,
 7080    ) {
 7081        self.manipulate_text(window, cx, |text| {
 7082            text.chars()
 7083                .fold(String::with_capacity(text.len()), |mut t, c| {
 7084                    if c.is_uppercase() {
 7085                        t.extend(c.to_lowercase());
 7086                    } else {
 7087                        t.extend(c.to_uppercase());
 7088                    }
 7089                    t
 7090                })
 7091        })
 7092    }
 7093
 7094    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7095    where
 7096        Fn: FnMut(&str) -> String,
 7097    {
 7098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7099        let buffer = self.buffer.read(cx).snapshot(cx);
 7100
 7101        let mut new_selections = Vec::new();
 7102        let mut edits = Vec::new();
 7103        let mut selection_adjustment = 0i32;
 7104
 7105        for selection in self.selections.all::<usize>(cx) {
 7106            let selection_is_empty = selection.is_empty();
 7107
 7108            let (start, end) = if selection_is_empty {
 7109                let word_range = movement::surrounding_word(
 7110                    &display_map,
 7111                    selection.start.to_display_point(&display_map),
 7112                );
 7113                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7114                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7115                (start, end)
 7116            } else {
 7117                (selection.start, selection.end)
 7118            };
 7119
 7120            let text = buffer.text_for_range(start..end).collect::<String>();
 7121            let old_length = text.len() as i32;
 7122            let text = callback(&text);
 7123
 7124            new_selections.push(Selection {
 7125                start: (start as i32 - selection_adjustment) as usize,
 7126                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7127                goal: SelectionGoal::None,
 7128                ..selection
 7129            });
 7130
 7131            selection_adjustment += old_length - text.len() as i32;
 7132
 7133            edits.push((start..end, text));
 7134        }
 7135
 7136        self.transact(window, cx, |this, window, cx| {
 7137            this.buffer.update(cx, |buffer, cx| {
 7138                buffer.edit(edits, None, cx);
 7139            });
 7140
 7141            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7142                s.select(new_selections);
 7143            });
 7144
 7145            this.request_autoscroll(Autoscroll::fit(), cx);
 7146        });
 7147    }
 7148
 7149    pub fn duplicate(
 7150        &mut self,
 7151        upwards: bool,
 7152        whole_lines: bool,
 7153        window: &mut Window,
 7154        cx: &mut Context<Self>,
 7155    ) {
 7156        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7157        let buffer = &display_map.buffer_snapshot;
 7158        let selections = self.selections.all::<Point>(cx);
 7159
 7160        let mut edits = Vec::new();
 7161        let mut selections_iter = selections.iter().peekable();
 7162        while let Some(selection) = selections_iter.next() {
 7163            let mut rows = selection.spanned_rows(false, &display_map);
 7164            // duplicate line-wise
 7165            if whole_lines || selection.start == selection.end {
 7166                // Avoid duplicating the same lines twice.
 7167                while let Some(next_selection) = selections_iter.peek() {
 7168                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7169                    if next_rows.start < rows.end {
 7170                        rows.end = next_rows.end;
 7171                        selections_iter.next().unwrap();
 7172                    } else {
 7173                        break;
 7174                    }
 7175                }
 7176
 7177                // Copy the text from the selected row region and splice it either at the start
 7178                // or end of the region.
 7179                let start = Point::new(rows.start.0, 0);
 7180                let end = Point::new(
 7181                    rows.end.previous_row().0,
 7182                    buffer.line_len(rows.end.previous_row()),
 7183                );
 7184                let text = buffer
 7185                    .text_for_range(start..end)
 7186                    .chain(Some("\n"))
 7187                    .collect::<String>();
 7188                let insert_location = if upwards {
 7189                    Point::new(rows.end.0, 0)
 7190                } else {
 7191                    start
 7192                };
 7193                edits.push((insert_location..insert_location, text));
 7194            } else {
 7195                // duplicate character-wise
 7196                let start = selection.start;
 7197                let end = selection.end;
 7198                let text = buffer.text_for_range(start..end).collect::<String>();
 7199                edits.push((selection.end..selection.end, text));
 7200            }
 7201        }
 7202
 7203        self.transact(window, cx, |this, _, cx| {
 7204            this.buffer.update(cx, |buffer, cx| {
 7205                buffer.edit(edits, None, cx);
 7206            });
 7207
 7208            this.request_autoscroll(Autoscroll::fit(), cx);
 7209        });
 7210    }
 7211
 7212    pub fn duplicate_line_up(
 7213        &mut self,
 7214        _: &DuplicateLineUp,
 7215        window: &mut Window,
 7216        cx: &mut Context<Self>,
 7217    ) {
 7218        self.duplicate(true, true, window, cx);
 7219    }
 7220
 7221    pub fn duplicate_line_down(
 7222        &mut self,
 7223        _: &DuplicateLineDown,
 7224        window: &mut Window,
 7225        cx: &mut Context<Self>,
 7226    ) {
 7227        self.duplicate(false, true, window, cx);
 7228    }
 7229
 7230    pub fn duplicate_selection(
 7231        &mut self,
 7232        _: &DuplicateSelection,
 7233        window: &mut Window,
 7234        cx: &mut Context<Self>,
 7235    ) {
 7236        self.duplicate(false, false, window, cx);
 7237    }
 7238
 7239    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7241        let buffer = self.buffer.read(cx).snapshot(cx);
 7242
 7243        let mut edits = Vec::new();
 7244        let mut unfold_ranges = Vec::new();
 7245        let mut refold_creases = Vec::new();
 7246
 7247        let selections = self.selections.all::<Point>(cx);
 7248        let mut selections = selections.iter().peekable();
 7249        let mut contiguous_row_selections = Vec::new();
 7250        let mut new_selections = Vec::new();
 7251
 7252        while let Some(selection) = selections.next() {
 7253            // Find all the selections that span a contiguous row range
 7254            let (start_row, end_row) = consume_contiguous_rows(
 7255                &mut contiguous_row_selections,
 7256                selection,
 7257                &display_map,
 7258                &mut selections,
 7259            );
 7260
 7261            // Move the text spanned by the row range to be before the line preceding the row range
 7262            if start_row.0 > 0 {
 7263                let range_to_move = Point::new(
 7264                    start_row.previous_row().0,
 7265                    buffer.line_len(start_row.previous_row()),
 7266                )
 7267                    ..Point::new(
 7268                        end_row.previous_row().0,
 7269                        buffer.line_len(end_row.previous_row()),
 7270                    );
 7271                let insertion_point = display_map
 7272                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7273                    .0;
 7274
 7275                // Don't move lines across excerpts
 7276                if buffer
 7277                    .excerpt_containing(insertion_point..range_to_move.end)
 7278                    .is_some()
 7279                {
 7280                    let text = buffer
 7281                        .text_for_range(range_to_move.clone())
 7282                        .flat_map(|s| s.chars())
 7283                        .skip(1)
 7284                        .chain(['\n'])
 7285                        .collect::<String>();
 7286
 7287                    edits.push((
 7288                        buffer.anchor_after(range_to_move.start)
 7289                            ..buffer.anchor_before(range_to_move.end),
 7290                        String::new(),
 7291                    ));
 7292                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7293                    edits.push((insertion_anchor..insertion_anchor, text));
 7294
 7295                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7296
 7297                    // Move selections up
 7298                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7299                        |mut selection| {
 7300                            selection.start.row -= row_delta;
 7301                            selection.end.row -= row_delta;
 7302                            selection
 7303                        },
 7304                    ));
 7305
 7306                    // Move folds up
 7307                    unfold_ranges.push(range_to_move.clone());
 7308                    for fold in display_map.folds_in_range(
 7309                        buffer.anchor_before(range_to_move.start)
 7310                            ..buffer.anchor_after(range_to_move.end),
 7311                    ) {
 7312                        let mut start = fold.range.start.to_point(&buffer);
 7313                        let mut end = fold.range.end.to_point(&buffer);
 7314                        start.row -= row_delta;
 7315                        end.row -= row_delta;
 7316                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7317                    }
 7318                }
 7319            }
 7320
 7321            // If we didn't move line(s), preserve the existing selections
 7322            new_selections.append(&mut contiguous_row_selections);
 7323        }
 7324
 7325        self.transact(window, cx, |this, window, cx| {
 7326            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7327            this.buffer.update(cx, |buffer, cx| {
 7328                for (range, text) in edits {
 7329                    buffer.edit([(range, text)], None, cx);
 7330                }
 7331            });
 7332            this.fold_creases(refold_creases, true, window, cx);
 7333            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7334                s.select(new_selections);
 7335            })
 7336        });
 7337    }
 7338
 7339    pub fn move_line_down(
 7340        &mut self,
 7341        _: &MoveLineDown,
 7342        window: &mut Window,
 7343        cx: &mut Context<Self>,
 7344    ) {
 7345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7346        let buffer = self.buffer.read(cx).snapshot(cx);
 7347
 7348        let mut edits = Vec::new();
 7349        let mut unfold_ranges = Vec::new();
 7350        let mut refold_creases = Vec::new();
 7351
 7352        let selections = self.selections.all::<Point>(cx);
 7353        let mut selections = selections.iter().peekable();
 7354        let mut contiguous_row_selections = Vec::new();
 7355        let mut new_selections = Vec::new();
 7356
 7357        while let Some(selection) = selections.next() {
 7358            // Find all the selections that span a contiguous row range
 7359            let (start_row, end_row) = consume_contiguous_rows(
 7360                &mut contiguous_row_selections,
 7361                selection,
 7362                &display_map,
 7363                &mut selections,
 7364            );
 7365
 7366            // Move the text spanned by the row range to be after the last line of the row range
 7367            if end_row.0 <= buffer.max_point().row {
 7368                let range_to_move =
 7369                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7370                let insertion_point = display_map
 7371                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7372                    .0;
 7373
 7374                // Don't move lines across excerpt boundaries
 7375                if buffer
 7376                    .excerpt_containing(range_to_move.start..insertion_point)
 7377                    .is_some()
 7378                {
 7379                    let mut text = String::from("\n");
 7380                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7381                    text.pop(); // Drop trailing newline
 7382                    edits.push((
 7383                        buffer.anchor_after(range_to_move.start)
 7384                            ..buffer.anchor_before(range_to_move.end),
 7385                        String::new(),
 7386                    ));
 7387                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7388                    edits.push((insertion_anchor..insertion_anchor, text));
 7389
 7390                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7391
 7392                    // Move selections down
 7393                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7394                        |mut selection| {
 7395                            selection.start.row += row_delta;
 7396                            selection.end.row += row_delta;
 7397                            selection
 7398                        },
 7399                    ));
 7400
 7401                    // Move folds down
 7402                    unfold_ranges.push(range_to_move.clone());
 7403                    for fold in display_map.folds_in_range(
 7404                        buffer.anchor_before(range_to_move.start)
 7405                            ..buffer.anchor_after(range_to_move.end),
 7406                    ) {
 7407                        let mut start = fold.range.start.to_point(&buffer);
 7408                        let mut end = fold.range.end.to_point(&buffer);
 7409                        start.row += row_delta;
 7410                        end.row += row_delta;
 7411                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7412                    }
 7413                }
 7414            }
 7415
 7416            // If we didn't move line(s), preserve the existing selections
 7417            new_selections.append(&mut contiguous_row_selections);
 7418        }
 7419
 7420        self.transact(window, cx, |this, window, cx| {
 7421            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7422            this.buffer.update(cx, |buffer, cx| {
 7423                for (range, text) in edits {
 7424                    buffer.edit([(range, text)], None, cx);
 7425                }
 7426            });
 7427            this.fold_creases(refold_creases, true, window, cx);
 7428            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7429                s.select(new_selections)
 7430            });
 7431        });
 7432    }
 7433
 7434    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7435        let text_layout_details = &self.text_layout_details(window);
 7436        self.transact(window, cx, |this, window, cx| {
 7437            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7438                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7439                let line_mode = s.line_mode;
 7440                s.move_with(|display_map, selection| {
 7441                    if !selection.is_empty() || line_mode {
 7442                        return;
 7443                    }
 7444
 7445                    let mut head = selection.head();
 7446                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7447                    if head.column() == display_map.line_len(head.row()) {
 7448                        transpose_offset = display_map
 7449                            .buffer_snapshot
 7450                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7451                    }
 7452
 7453                    if transpose_offset == 0 {
 7454                        return;
 7455                    }
 7456
 7457                    *head.column_mut() += 1;
 7458                    head = display_map.clip_point(head, Bias::Right);
 7459                    let goal = SelectionGoal::HorizontalPosition(
 7460                        display_map
 7461                            .x_for_display_point(head, text_layout_details)
 7462                            .into(),
 7463                    );
 7464                    selection.collapse_to(head, goal);
 7465
 7466                    let transpose_start = display_map
 7467                        .buffer_snapshot
 7468                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7469                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7470                        let transpose_end = display_map
 7471                            .buffer_snapshot
 7472                            .clip_offset(transpose_offset + 1, Bias::Right);
 7473                        if let Some(ch) =
 7474                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7475                        {
 7476                            edits.push((transpose_start..transpose_offset, String::new()));
 7477                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7478                        }
 7479                    }
 7480                });
 7481                edits
 7482            });
 7483            this.buffer
 7484                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7485            let selections = this.selections.all::<usize>(cx);
 7486            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7487                s.select(selections);
 7488            });
 7489        });
 7490    }
 7491
 7492    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7493        self.rewrap_impl(IsVimMode::No, cx)
 7494    }
 7495
 7496    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7497        let buffer = self.buffer.read(cx).snapshot(cx);
 7498        let selections = self.selections.all::<Point>(cx);
 7499        let mut selections = selections.iter().peekable();
 7500
 7501        let mut edits = Vec::new();
 7502        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7503
 7504        while let Some(selection) = selections.next() {
 7505            let mut start_row = selection.start.row;
 7506            let mut end_row = selection.end.row;
 7507
 7508            // Skip selections that overlap with a range that has already been rewrapped.
 7509            let selection_range = start_row..end_row;
 7510            if rewrapped_row_ranges
 7511                .iter()
 7512                .any(|range| range.overlaps(&selection_range))
 7513            {
 7514                continue;
 7515            }
 7516
 7517            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7518
 7519            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7520                match language_scope.language_name().as_ref() {
 7521                    "Markdown" | "Plain Text" => {
 7522                        should_rewrap = true;
 7523                    }
 7524                    _ => {}
 7525                }
 7526            }
 7527
 7528            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7529
 7530            // Since not all lines in the selection may be at the same indent
 7531            // level, choose the indent size that is the most common between all
 7532            // of the lines.
 7533            //
 7534            // If there is a tie, we use the deepest indent.
 7535            let (indent_size, indent_end) = {
 7536                let mut indent_size_occurrences = HashMap::default();
 7537                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7538
 7539                for row in start_row..=end_row {
 7540                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7541                    rows_by_indent_size.entry(indent).or_default().push(row);
 7542                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7543                }
 7544
 7545                let indent_size = indent_size_occurrences
 7546                    .into_iter()
 7547                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7548                    .map(|(indent, _)| indent)
 7549                    .unwrap_or_default();
 7550                let row = rows_by_indent_size[&indent_size][0];
 7551                let indent_end = Point::new(row, indent_size.len);
 7552
 7553                (indent_size, indent_end)
 7554            };
 7555
 7556            let mut line_prefix = indent_size.chars().collect::<String>();
 7557
 7558            if let Some(comment_prefix) =
 7559                buffer
 7560                    .language_scope_at(selection.head())
 7561                    .and_then(|language| {
 7562                        language
 7563                            .line_comment_prefixes()
 7564                            .iter()
 7565                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7566                            .cloned()
 7567                    })
 7568            {
 7569                line_prefix.push_str(&comment_prefix);
 7570                should_rewrap = true;
 7571            }
 7572
 7573            if !should_rewrap {
 7574                continue;
 7575            }
 7576
 7577            if selection.is_empty() {
 7578                'expand_upwards: while start_row > 0 {
 7579                    let prev_row = start_row - 1;
 7580                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7581                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7582                    {
 7583                        start_row = prev_row;
 7584                    } else {
 7585                        break 'expand_upwards;
 7586                    }
 7587                }
 7588
 7589                'expand_downwards: while end_row < buffer.max_point().row {
 7590                    let next_row = end_row + 1;
 7591                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7592                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7593                    {
 7594                        end_row = next_row;
 7595                    } else {
 7596                        break 'expand_downwards;
 7597                    }
 7598                }
 7599            }
 7600
 7601            let start = Point::new(start_row, 0);
 7602            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7603            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7604            let Some(lines_without_prefixes) = selection_text
 7605                .lines()
 7606                .map(|line| {
 7607                    line.strip_prefix(&line_prefix)
 7608                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7609                        .ok_or_else(|| {
 7610                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7611                        })
 7612                })
 7613                .collect::<Result<Vec<_>, _>>()
 7614                .log_err()
 7615            else {
 7616                continue;
 7617            };
 7618
 7619            let wrap_column = buffer
 7620                .settings_at(Point::new(start_row, 0), cx)
 7621                .preferred_line_length as usize;
 7622            let wrapped_text = wrap_with_prefix(
 7623                line_prefix,
 7624                lines_without_prefixes.join(" "),
 7625                wrap_column,
 7626                tab_size,
 7627            );
 7628
 7629            // TODO: should always use char-based diff while still supporting cursor behavior that
 7630            // matches vim.
 7631            let diff = match is_vim_mode {
 7632                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7633                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7634            };
 7635            let mut offset = start.to_offset(&buffer);
 7636            let mut moved_since_edit = true;
 7637
 7638            for change in diff.iter_all_changes() {
 7639                let value = change.value();
 7640                match change.tag() {
 7641                    ChangeTag::Equal => {
 7642                        offset += value.len();
 7643                        moved_since_edit = true;
 7644                    }
 7645                    ChangeTag::Delete => {
 7646                        let start = buffer.anchor_after(offset);
 7647                        let end = buffer.anchor_before(offset + value.len());
 7648
 7649                        if moved_since_edit {
 7650                            edits.push((start..end, String::new()));
 7651                        } else {
 7652                            edits.last_mut().unwrap().0.end = end;
 7653                        }
 7654
 7655                        offset += value.len();
 7656                        moved_since_edit = false;
 7657                    }
 7658                    ChangeTag::Insert => {
 7659                        if moved_since_edit {
 7660                            let anchor = buffer.anchor_after(offset);
 7661                            edits.push((anchor..anchor, value.to_string()));
 7662                        } else {
 7663                            edits.last_mut().unwrap().1.push_str(value);
 7664                        }
 7665
 7666                        moved_since_edit = false;
 7667                    }
 7668                }
 7669            }
 7670
 7671            rewrapped_row_ranges.push(start_row..=end_row);
 7672        }
 7673
 7674        self.buffer
 7675            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7676    }
 7677
 7678    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7679        let mut text = String::new();
 7680        let buffer = self.buffer.read(cx).snapshot(cx);
 7681        let mut selections = self.selections.all::<Point>(cx);
 7682        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7683        {
 7684            let max_point = buffer.max_point();
 7685            let mut is_first = true;
 7686            for selection in &mut selections {
 7687                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7688                if is_entire_line {
 7689                    selection.start = Point::new(selection.start.row, 0);
 7690                    if !selection.is_empty() && selection.end.column == 0 {
 7691                        selection.end = cmp::min(max_point, selection.end);
 7692                    } else {
 7693                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7694                    }
 7695                    selection.goal = SelectionGoal::None;
 7696                }
 7697                if is_first {
 7698                    is_first = false;
 7699                } else {
 7700                    text += "\n";
 7701                }
 7702                let mut len = 0;
 7703                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7704                    text.push_str(chunk);
 7705                    len += chunk.len();
 7706                }
 7707                clipboard_selections.push(ClipboardSelection {
 7708                    len,
 7709                    is_entire_line,
 7710                    first_line_indent: buffer
 7711                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7712                        .len,
 7713                });
 7714            }
 7715        }
 7716
 7717        self.transact(window, cx, |this, window, cx| {
 7718            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7719                s.select(selections);
 7720            });
 7721            this.insert("", window, cx);
 7722        });
 7723        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7724    }
 7725
 7726    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7727        let item = self.cut_common(window, cx);
 7728        cx.write_to_clipboard(item);
 7729    }
 7730
 7731    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7732        self.change_selections(None, window, cx, |s| {
 7733            s.move_with(|snapshot, sel| {
 7734                if sel.is_empty() {
 7735                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7736                }
 7737            });
 7738        });
 7739        let item = self.cut_common(window, cx);
 7740        cx.set_global(KillRing(item))
 7741    }
 7742
 7743    pub fn kill_ring_yank(
 7744        &mut self,
 7745        _: &KillRingYank,
 7746        window: &mut Window,
 7747        cx: &mut Context<Self>,
 7748    ) {
 7749        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7750            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7751                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7752            } else {
 7753                return;
 7754            }
 7755        } else {
 7756            return;
 7757        };
 7758        self.do_paste(&text, metadata, false, window, cx);
 7759    }
 7760
 7761    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7762        let selections = self.selections.all::<Point>(cx);
 7763        let buffer = self.buffer.read(cx).read(cx);
 7764        let mut text = String::new();
 7765
 7766        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7767        {
 7768            let max_point = buffer.max_point();
 7769            let mut is_first = true;
 7770            for selection in selections.iter() {
 7771                let mut start = selection.start;
 7772                let mut end = selection.end;
 7773                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7774                if is_entire_line {
 7775                    start = Point::new(start.row, 0);
 7776                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7777                }
 7778                if is_first {
 7779                    is_first = false;
 7780                } else {
 7781                    text += "\n";
 7782                }
 7783                let mut len = 0;
 7784                for chunk in buffer.text_for_range(start..end) {
 7785                    text.push_str(chunk);
 7786                    len += chunk.len();
 7787                }
 7788                clipboard_selections.push(ClipboardSelection {
 7789                    len,
 7790                    is_entire_line,
 7791                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7792                });
 7793            }
 7794        }
 7795
 7796        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7797            text,
 7798            clipboard_selections,
 7799        ));
 7800    }
 7801
 7802    pub fn do_paste(
 7803        &mut self,
 7804        text: &String,
 7805        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7806        handle_entire_lines: bool,
 7807        window: &mut Window,
 7808        cx: &mut Context<Self>,
 7809    ) {
 7810        if self.read_only(cx) {
 7811            return;
 7812        }
 7813
 7814        let clipboard_text = Cow::Borrowed(text);
 7815
 7816        self.transact(window, cx, |this, window, cx| {
 7817            if let Some(mut clipboard_selections) = clipboard_selections {
 7818                let old_selections = this.selections.all::<usize>(cx);
 7819                let all_selections_were_entire_line =
 7820                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7821                let first_selection_indent_column =
 7822                    clipboard_selections.first().map(|s| s.first_line_indent);
 7823                if clipboard_selections.len() != old_selections.len() {
 7824                    clipboard_selections.drain(..);
 7825                }
 7826                let cursor_offset = this.selections.last::<usize>(cx).head();
 7827                let mut auto_indent_on_paste = true;
 7828
 7829                this.buffer.update(cx, |buffer, cx| {
 7830                    let snapshot = buffer.read(cx);
 7831                    auto_indent_on_paste =
 7832                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7833
 7834                    let mut start_offset = 0;
 7835                    let mut edits = Vec::new();
 7836                    let mut original_indent_columns = Vec::new();
 7837                    for (ix, selection) in old_selections.iter().enumerate() {
 7838                        let to_insert;
 7839                        let entire_line;
 7840                        let original_indent_column;
 7841                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7842                            let end_offset = start_offset + clipboard_selection.len;
 7843                            to_insert = &clipboard_text[start_offset..end_offset];
 7844                            entire_line = clipboard_selection.is_entire_line;
 7845                            start_offset = end_offset + 1;
 7846                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7847                        } else {
 7848                            to_insert = clipboard_text.as_str();
 7849                            entire_line = all_selections_were_entire_line;
 7850                            original_indent_column = first_selection_indent_column
 7851                        }
 7852
 7853                        // If the corresponding selection was empty when this slice of the
 7854                        // clipboard text was written, then the entire line containing the
 7855                        // selection was copied. If this selection is also currently empty,
 7856                        // then paste the line before the current line of the buffer.
 7857                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7858                            let column = selection.start.to_point(&snapshot).column as usize;
 7859                            let line_start = selection.start - column;
 7860                            line_start..line_start
 7861                        } else {
 7862                            selection.range()
 7863                        };
 7864
 7865                        edits.push((range, to_insert));
 7866                        original_indent_columns.extend(original_indent_column);
 7867                    }
 7868                    drop(snapshot);
 7869
 7870                    buffer.edit(
 7871                        edits,
 7872                        if auto_indent_on_paste {
 7873                            Some(AutoindentMode::Block {
 7874                                original_indent_columns,
 7875                            })
 7876                        } else {
 7877                            None
 7878                        },
 7879                        cx,
 7880                    );
 7881                });
 7882
 7883                let selections = this.selections.all::<usize>(cx);
 7884                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7885                    s.select(selections)
 7886                });
 7887            } else {
 7888                this.insert(&clipboard_text, window, cx);
 7889            }
 7890        });
 7891    }
 7892
 7893    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7894        if let Some(item) = cx.read_from_clipboard() {
 7895            let entries = item.entries();
 7896
 7897            match entries.first() {
 7898                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7899                // of all the pasted entries.
 7900                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7901                    .do_paste(
 7902                        clipboard_string.text(),
 7903                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7904                        true,
 7905                        window,
 7906                        cx,
 7907                    ),
 7908                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7909            }
 7910        }
 7911    }
 7912
 7913    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7914        if self.read_only(cx) {
 7915            return;
 7916        }
 7917
 7918        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7919            if let Some((selections, _)) =
 7920                self.selection_history.transaction(transaction_id).cloned()
 7921            {
 7922                self.change_selections(None, window, cx, |s| {
 7923                    s.select_anchors(selections.to_vec());
 7924                });
 7925            }
 7926            self.request_autoscroll(Autoscroll::fit(), cx);
 7927            self.unmark_text(window, cx);
 7928            self.refresh_inline_completion(true, false, window, cx);
 7929            cx.emit(EditorEvent::Edited { transaction_id });
 7930            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7931        }
 7932    }
 7933
 7934    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7935        if self.read_only(cx) {
 7936            return;
 7937        }
 7938
 7939        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7940            if let Some((_, Some(selections))) =
 7941                self.selection_history.transaction(transaction_id).cloned()
 7942            {
 7943                self.change_selections(None, window, cx, |s| {
 7944                    s.select_anchors(selections.to_vec());
 7945                });
 7946            }
 7947            self.request_autoscroll(Autoscroll::fit(), cx);
 7948            self.unmark_text(window, cx);
 7949            self.refresh_inline_completion(true, false, window, cx);
 7950            cx.emit(EditorEvent::Edited { transaction_id });
 7951        }
 7952    }
 7953
 7954    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7955        self.buffer
 7956            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7957    }
 7958
 7959    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7960        self.buffer
 7961            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7962    }
 7963
 7964    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7966            let line_mode = s.line_mode;
 7967            s.move_with(|map, selection| {
 7968                let cursor = if selection.is_empty() && !line_mode {
 7969                    movement::left(map, selection.start)
 7970                } else {
 7971                    selection.start
 7972                };
 7973                selection.collapse_to(cursor, SelectionGoal::None);
 7974            });
 7975        })
 7976    }
 7977
 7978    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7980            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7981        })
 7982    }
 7983
 7984    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7985        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7986            let line_mode = s.line_mode;
 7987            s.move_with(|map, selection| {
 7988                let cursor = if selection.is_empty() && !line_mode {
 7989                    movement::right(map, selection.end)
 7990                } else {
 7991                    selection.end
 7992                };
 7993                selection.collapse_to(cursor, SelectionGoal::None)
 7994            });
 7995        })
 7996    }
 7997
 7998    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7999        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8000            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8001        })
 8002    }
 8003
 8004    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8005        if self.take_rename(true, window, cx).is_some() {
 8006            return;
 8007        }
 8008
 8009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8010            cx.propagate();
 8011            return;
 8012        }
 8013
 8014        let text_layout_details = &self.text_layout_details(window);
 8015        let selection_count = self.selections.count();
 8016        let first_selection = self.selections.first_anchor();
 8017
 8018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8019            let line_mode = s.line_mode;
 8020            s.move_with(|map, selection| {
 8021                if !selection.is_empty() && !line_mode {
 8022                    selection.goal = SelectionGoal::None;
 8023                }
 8024                let (cursor, goal) = movement::up(
 8025                    map,
 8026                    selection.start,
 8027                    selection.goal,
 8028                    false,
 8029                    text_layout_details,
 8030                );
 8031                selection.collapse_to(cursor, goal);
 8032            });
 8033        });
 8034
 8035        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8036        {
 8037            cx.propagate();
 8038        }
 8039    }
 8040
 8041    pub fn move_up_by_lines(
 8042        &mut self,
 8043        action: &MoveUpByLines,
 8044        window: &mut Window,
 8045        cx: &mut Context<Self>,
 8046    ) {
 8047        if self.take_rename(true, window, cx).is_some() {
 8048            return;
 8049        }
 8050
 8051        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8052            cx.propagate();
 8053            return;
 8054        }
 8055
 8056        let text_layout_details = &self.text_layout_details(window);
 8057
 8058        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8059            let line_mode = s.line_mode;
 8060            s.move_with(|map, selection| {
 8061                if !selection.is_empty() && !line_mode {
 8062                    selection.goal = SelectionGoal::None;
 8063                }
 8064                let (cursor, goal) = movement::up_by_rows(
 8065                    map,
 8066                    selection.start,
 8067                    action.lines,
 8068                    selection.goal,
 8069                    false,
 8070                    text_layout_details,
 8071                );
 8072                selection.collapse_to(cursor, goal);
 8073            });
 8074        })
 8075    }
 8076
 8077    pub fn move_down_by_lines(
 8078        &mut self,
 8079        action: &MoveDownByLines,
 8080        window: &mut Window,
 8081        cx: &mut Context<Self>,
 8082    ) {
 8083        if self.take_rename(true, window, cx).is_some() {
 8084            return;
 8085        }
 8086
 8087        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8088            cx.propagate();
 8089            return;
 8090        }
 8091
 8092        let text_layout_details = &self.text_layout_details(window);
 8093
 8094        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8095            let line_mode = s.line_mode;
 8096            s.move_with(|map, selection| {
 8097                if !selection.is_empty() && !line_mode {
 8098                    selection.goal = SelectionGoal::None;
 8099                }
 8100                let (cursor, goal) = movement::down_by_rows(
 8101                    map,
 8102                    selection.start,
 8103                    action.lines,
 8104                    selection.goal,
 8105                    false,
 8106                    text_layout_details,
 8107                );
 8108                selection.collapse_to(cursor, goal);
 8109            });
 8110        })
 8111    }
 8112
 8113    pub fn select_down_by_lines(
 8114        &mut self,
 8115        action: &SelectDownByLines,
 8116        window: &mut Window,
 8117        cx: &mut Context<Self>,
 8118    ) {
 8119        let text_layout_details = &self.text_layout_details(window);
 8120        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8121            s.move_heads_with(|map, head, goal| {
 8122                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8123            })
 8124        })
 8125    }
 8126
 8127    pub fn select_up_by_lines(
 8128        &mut self,
 8129        action: &SelectUpByLines,
 8130        window: &mut Window,
 8131        cx: &mut Context<Self>,
 8132    ) {
 8133        let text_layout_details = &self.text_layout_details(window);
 8134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8135            s.move_heads_with(|map, head, goal| {
 8136                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8137            })
 8138        })
 8139    }
 8140
 8141    pub fn select_page_up(
 8142        &mut self,
 8143        _: &SelectPageUp,
 8144        window: &mut Window,
 8145        cx: &mut Context<Self>,
 8146    ) {
 8147        let Some(row_count) = self.visible_row_count() else {
 8148            return;
 8149        };
 8150
 8151        let text_layout_details = &self.text_layout_details(window);
 8152
 8153        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8154            s.move_heads_with(|map, head, goal| {
 8155                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8156            })
 8157        })
 8158    }
 8159
 8160    pub fn move_page_up(
 8161        &mut self,
 8162        action: &MovePageUp,
 8163        window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) {
 8166        if self.take_rename(true, window, cx).is_some() {
 8167            return;
 8168        }
 8169
 8170        if self
 8171            .context_menu
 8172            .borrow_mut()
 8173            .as_mut()
 8174            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8175            .unwrap_or(false)
 8176        {
 8177            return;
 8178        }
 8179
 8180        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8181            cx.propagate();
 8182            return;
 8183        }
 8184
 8185        let Some(row_count) = self.visible_row_count() else {
 8186            return;
 8187        };
 8188
 8189        let autoscroll = if action.center_cursor {
 8190            Autoscroll::center()
 8191        } else {
 8192            Autoscroll::fit()
 8193        };
 8194
 8195        let text_layout_details = &self.text_layout_details(window);
 8196
 8197        self.change_selections(Some(autoscroll), window, cx, |s| {
 8198            let line_mode = s.line_mode;
 8199            s.move_with(|map, selection| {
 8200                if !selection.is_empty() && !line_mode {
 8201                    selection.goal = SelectionGoal::None;
 8202                }
 8203                let (cursor, goal) = movement::up_by_rows(
 8204                    map,
 8205                    selection.end,
 8206                    row_count,
 8207                    selection.goal,
 8208                    false,
 8209                    text_layout_details,
 8210                );
 8211                selection.collapse_to(cursor, goal);
 8212            });
 8213        });
 8214    }
 8215
 8216    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8217        let text_layout_details = &self.text_layout_details(window);
 8218        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8219            s.move_heads_with(|map, head, goal| {
 8220                movement::up(map, head, goal, false, text_layout_details)
 8221            })
 8222        })
 8223    }
 8224
 8225    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8226        self.take_rename(true, window, cx);
 8227
 8228        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8229            cx.propagate();
 8230            return;
 8231        }
 8232
 8233        let text_layout_details = &self.text_layout_details(window);
 8234        let selection_count = self.selections.count();
 8235        let first_selection = self.selections.first_anchor();
 8236
 8237        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8238            let line_mode = s.line_mode;
 8239            s.move_with(|map, selection| {
 8240                if !selection.is_empty() && !line_mode {
 8241                    selection.goal = SelectionGoal::None;
 8242                }
 8243                let (cursor, goal) = movement::down(
 8244                    map,
 8245                    selection.end,
 8246                    selection.goal,
 8247                    false,
 8248                    text_layout_details,
 8249                );
 8250                selection.collapse_to(cursor, goal);
 8251            });
 8252        });
 8253
 8254        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8255        {
 8256            cx.propagate();
 8257        }
 8258    }
 8259
 8260    pub fn select_page_down(
 8261        &mut self,
 8262        _: &SelectPageDown,
 8263        window: &mut Window,
 8264        cx: &mut Context<Self>,
 8265    ) {
 8266        let Some(row_count) = self.visible_row_count() else {
 8267            return;
 8268        };
 8269
 8270        let text_layout_details = &self.text_layout_details(window);
 8271
 8272        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8273            s.move_heads_with(|map, head, goal| {
 8274                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8275            })
 8276        })
 8277    }
 8278
 8279    pub fn move_page_down(
 8280        &mut self,
 8281        action: &MovePageDown,
 8282        window: &mut Window,
 8283        cx: &mut Context<Self>,
 8284    ) {
 8285        if self.take_rename(true, window, cx).is_some() {
 8286            return;
 8287        }
 8288
 8289        if self
 8290            .context_menu
 8291            .borrow_mut()
 8292            .as_mut()
 8293            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8294            .unwrap_or(false)
 8295        {
 8296            return;
 8297        }
 8298
 8299        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8300            cx.propagate();
 8301            return;
 8302        }
 8303
 8304        let Some(row_count) = self.visible_row_count() else {
 8305            return;
 8306        };
 8307
 8308        let autoscroll = if action.center_cursor {
 8309            Autoscroll::center()
 8310        } else {
 8311            Autoscroll::fit()
 8312        };
 8313
 8314        let text_layout_details = &self.text_layout_details(window);
 8315        self.change_selections(Some(autoscroll), window, cx, |s| {
 8316            let line_mode = s.line_mode;
 8317            s.move_with(|map, selection| {
 8318                if !selection.is_empty() && !line_mode {
 8319                    selection.goal = SelectionGoal::None;
 8320                }
 8321                let (cursor, goal) = movement::down_by_rows(
 8322                    map,
 8323                    selection.end,
 8324                    row_count,
 8325                    selection.goal,
 8326                    false,
 8327                    text_layout_details,
 8328                );
 8329                selection.collapse_to(cursor, goal);
 8330            });
 8331        });
 8332    }
 8333
 8334    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8335        let text_layout_details = &self.text_layout_details(window);
 8336        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8337            s.move_heads_with(|map, head, goal| {
 8338                movement::down(map, head, goal, false, text_layout_details)
 8339            })
 8340        });
 8341    }
 8342
 8343    pub fn context_menu_first(
 8344        &mut self,
 8345        _: &ContextMenuFirst,
 8346        _window: &mut Window,
 8347        cx: &mut Context<Self>,
 8348    ) {
 8349        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8350            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8351        }
 8352    }
 8353
 8354    pub fn context_menu_prev(
 8355        &mut self,
 8356        _: &ContextMenuPrev,
 8357        _window: &mut Window,
 8358        cx: &mut Context<Self>,
 8359    ) {
 8360        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8361            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8362        }
 8363    }
 8364
 8365    pub fn context_menu_next(
 8366        &mut self,
 8367        _: &ContextMenuNext,
 8368        _window: &mut Window,
 8369        cx: &mut Context<Self>,
 8370    ) {
 8371        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8372            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8373        }
 8374    }
 8375
 8376    pub fn context_menu_last(
 8377        &mut self,
 8378        _: &ContextMenuLast,
 8379        _window: &mut Window,
 8380        cx: &mut Context<Self>,
 8381    ) {
 8382        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8383            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8384        }
 8385    }
 8386
 8387    pub fn move_to_previous_word_start(
 8388        &mut self,
 8389        _: &MoveToPreviousWordStart,
 8390        window: &mut Window,
 8391        cx: &mut Context<Self>,
 8392    ) {
 8393        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8394            s.move_cursors_with(|map, head, _| {
 8395                (
 8396                    movement::previous_word_start(map, head),
 8397                    SelectionGoal::None,
 8398                )
 8399            });
 8400        })
 8401    }
 8402
 8403    pub fn move_to_previous_subword_start(
 8404        &mut self,
 8405        _: &MoveToPreviousSubwordStart,
 8406        window: &mut Window,
 8407        cx: &mut Context<Self>,
 8408    ) {
 8409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8410            s.move_cursors_with(|map, head, _| {
 8411                (
 8412                    movement::previous_subword_start(map, head),
 8413                    SelectionGoal::None,
 8414                )
 8415            });
 8416        })
 8417    }
 8418
 8419    pub fn select_to_previous_word_start(
 8420        &mut self,
 8421        _: &SelectToPreviousWordStart,
 8422        window: &mut Window,
 8423        cx: &mut Context<Self>,
 8424    ) {
 8425        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8426            s.move_heads_with(|map, head, _| {
 8427                (
 8428                    movement::previous_word_start(map, head),
 8429                    SelectionGoal::None,
 8430                )
 8431            });
 8432        })
 8433    }
 8434
 8435    pub fn select_to_previous_subword_start(
 8436        &mut self,
 8437        _: &SelectToPreviousSubwordStart,
 8438        window: &mut Window,
 8439        cx: &mut Context<Self>,
 8440    ) {
 8441        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8442            s.move_heads_with(|map, head, _| {
 8443                (
 8444                    movement::previous_subword_start(map, head),
 8445                    SelectionGoal::None,
 8446                )
 8447            });
 8448        })
 8449    }
 8450
 8451    pub fn delete_to_previous_word_start(
 8452        &mut self,
 8453        action: &DeleteToPreviousWordStart,
 8454        window: &mut Window,
 8455        cx: &mut Context<Self>,
 8456    ) {
 8457        self.transact(window, cx, |this, window, cx| {
 8458            this.select_autoclose_pair(window, cx);
 8459            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8460                let line_mode = s.line_mode;
 8461                s.move_with(|map, selection| {
 8462                    if selection.is_empty() && !line_mode {
 8463                        let cursor = if action.ignore_newlines {
 8464                            movement::previous_word_start(map, selection.head())
 8465                        } else {
 8466                            movement::previous_word_start_or_newline(map, selection.head())
 8467                        };
 8468                        selection.set_head(cursor, SelectionGoal::None);
 8469                    }
 8470                });
 8471            });
 8472            this.insert("", window, cx);
 8473        });
 8474    }
 8475
 8476    pub fn delete_to_previous_subword_start(
 8477        &mut self,
 8478        _: &DeleteToPreviousSubwordStart,
 8479        window: &mut Window,
 8480        cx: &mut Context<Self>,
 8481    ) {
 8482        self.transact(window, cx, |this, window, cx| {
 8483            this.select_autoclose_pair(window, cx);
 8484            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8485                let line_mode = s.line_mode;
 8486                s.move_with(|map, selection| {
 8487                    if selection.is_empty() && !line_mode {
 8488                        let cursor = movement::previous_subword_start(map, selection.head());
 8489                        selection.set_head(cursor, SelectionGoal::None);
 8490                    }
 8491                });
 8492            });
 8493            this.insert("", window, cx);
 8494        });
 8495    }
 8496
 8497    pub fn move_to_next_word_end(
 8498        &mut self,
 8499        _: &MoveToNextWordEnd,
 8500        window: &mut Window,
 8501        cx: &mut Context<Self>,
 8502    ) {
 8503        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8504            s.move_cursors_with(|map, head, _| {
 8505                (movement::next_word_end(map, head), SelectionGoal::None)
 8506            });
 8507        })
 8508    }
 8509
 8510    pub fn move_to_next_subword_end(
 8511        &mut self,
 8512        _: &MoveToNextSubwordEnd,
 8513        window: &mut Window,
 8514        cx: &mut Context<Self>,
 8515    ) {
 8516        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8517            s.move_cursors_with(|map, head, _| {
 8518                (movement::next_subword_end(map, head), SelectionGoal::None)
 8519            });
 8520        })
 8521    }
 8522
 8523    pub fn select_to_next_word_end(
 8524        &mut self,
 8525        _: &SelectToNextWordEnd,
 8526        window: &mut Window,
 8527        cx: &mut Context<Self>,
 8528    ) {
 8529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8530            s.move_heads_with(|map, head, _| {
 8531                (movement::next_word_end(map, head), SelectionGoal::None)
 8532            });
 8533        })
 8534    }
 8535
 8536    pub fn select_to_next_subword_end(
 8537        &mut self,
 8538        _: &SelectToNextSubwordEnd,
 8539        window: &mut Window,
 8540        cx: &mut Context<Self>,
 8541    ) {
 8542        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8543            s.move_heads_with(|map, head, _| {
 8544                (movement::next_subword_end(map, head), SelectionGoal::None)
 8545            });
 8546        })
 8547    }
 8548
 8549    pub fn delete_to_next_word_end(
 8550        &mut self,
 8551        action: &DeleteToNextWordEnd,
 8552        window: &mut Window,
 8553        cx: &mut Context<Self>,
 8554    ) {
 8555        self.transact(window, cx, |this, window, cx| {
 8556            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8557                let line_mode = s.line_mode;
 8558                s.move_with(|map, selection| {
 8559                    if selection.is_empty() && !line_mode {
 8560                        let cursor = if action.ignore_newlines {
 8561                            movement::next_word_end(map, selection.head())
 8562                        } else {
 8563                            movement::next_word_end_or_newline(map, selection.head())
 8564                        };
 8565                        selection.set_head(cursor, SelectionGoal::None);
 8566                    }
 8567                });
 8568            });
 8569            this.insert("", window, cx);
 8570        });
 8571    }
 8572
 8573    pub fn delete_to_next_subword_end(
 8574        &mut self,
 8575        _: &DeleteToNextSubwordEnd,
 8576        window: &mut Window,
 8577        cx: &mut Context<Self>,
 8578    ) {
 8579        self.transact(window, cx, |this, window, cx| {
 8580            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8581                s.move_with(|map, selection| {
 8582                    if selection.is_empty() {
 8583                        let cursor = movement::next_subword_end(map, selection.head());
 8584                        selection.set_head(cursor, SelectionGoal::None);
 8585                    }
 8586                });
 8587            });
 8588            this.insert("", window, cx);
 8589        });
 8590    }
 8591
 8592    pub fn move_to_beginning_of_line(
 8593        &mut self,
 8594        action: &MoveToBeginningOfLine,
 8595        window: &mut Window,
 8596        cx: &mut Context<Self>,
 8597    ) {
 8598        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8599            s.move_cursors_with(|map, head, _| {
 8600                (
 8601                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8602                    SelectionGoal::None,
 8603                )
 8604            });
 8605        })
 8606    }
 8607
 8608    pub fn select_to_beginning_of_line(
 8609        &mut self,
 8610        action: &SelectToBeginningOfLine,
 8611        window: &mut Window,
 8612        cx: &mut Context<Self>,
 8613    ) {
 8614        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8615            s.move_heads_with(|map, head, _| {
 8616                (
 8617                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8618                    SelectionGoal::None,
 8619                )
 8620            });
 8621        });
 8622    }
 8623
 8624    pub fn delete_to_beginning_of_line(
 8625        &mut self,
 8626        _: &DeleteToBeginningOfLine,
 8627        window: &mut Window,
 8628        cx: &mut Context<Self>,
 8629    ) {
 8630        self.transact(window, cx, |this, window, cx| {
 8631            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632                s.move_with(|_, selection| {
 8633                    selection.reversed = true;
 8634                });
 8635            });
 8636
 8637            this.select_to_beginning_of_line(
 8638                &SelectToBeginningOfLine {
 8639                    stop_at_soft_wraps: false,
 8640                },
 8641                window,
 8642                cx,
 8643            );
 8644            this.backspace(&Backspace, window, cx);
 8645        });
 8646    }
 8647
 8648    pub fn move_to_end_of_line(
 8649        &mut self,
 8650        action: &MoveToEndOfLine,
 8651        window: &mut Window,
 8652        cx: &mut Context<Self>,
 8653    ) {
 8654        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8655            s.move_cursors_with(|map, head, _| {
 8656                (
 8657                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8658                    SelectionGoal::None,
 8659                )
 8660            });
 8661        })
 8662    }
 8663
 8664    pub fn select_to_end_of_line(
 8665        &mut self,
 8666        action: &SelectToEndOfLine,
 8667        window: &mut Window,
 8668        cx: &mut Context<Self>,
 8669    ) {
 8670        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8671            s.move_heads_with(|map, head, _| {
 8672                (
 8673                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8674                    SelectionGoal::None,
 8675                )
 8676            });
 8677        })
 8678    }
 8679
 8680    pub fn delete_to_end_of_line(
 8681        &mut self,
 8682        _: &DeleteToEndOfLine,
 8683        window: &mut Window,
 8684        cx: &mut Context<Self>,
 8685    ) {
 8686        self.transact(window, cx, |this, window, cx| {
 8687            this.select_to_end_of_line(
 8688                &SelectToEndOfLine {
 8689                    stop_at_soft_wraps: false,
 8690                },
 8691                window,
 8692                cx,
 8693            );
 8694            this.delete(&Delete, window, cx);
 8695        });
 8696    }
 8697
 8698    pub fn cut_to_end_of_line(
 8699        &mut self,
 8700        _: &CutToEndOfLine,
 8701        window: &mut Window,
 8702        cx: &mut Context<Self>,
 8703    ) {
 8704        self.transact(window, cx, |this, window, cx| {
 8705            this.select_to_end_of_line(
 8706                &SelectToEndOfLine {
 8707                    stop_at_soft_wraps: false,
 8708                },
 8709                window,
 8710                cx,
 8711            );
 8712            this.cut(&Cut, window, cx);
 8713        });
 8714    }
 8715
 8716    pub fn move_to_start_of_paragraph(
 8717        &mut self,
 8718        _: &MoveToStartOfParagraph,
 8719        window: &mut Window,
 8720        cx: &mut Context<Self>,
 8721    ) {
 8722        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8723            cx.propagate();
 8724            return;
 8725        }
 8726
 8727        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8728            s.move_with(|map, selection| {
 8729                selection.collapse_to(
 8730                    movement::start_of_paragraph(map, selection.head(), 1),
 8731                    SelectionGoal::None,
 8732                )
 8733            });
 8734        })
 8735    }
 8736
 8737    pub fn move_to_end_of_paragraph(
 8738        &mut self,
 8739        _: &MoveToEndOfParagraph,
 8740        window: &mut Window,
 8741        cx: &mut Context<Self>,
 8742    ) {
 8743        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8744            cx.propagate();
 8745            return;
 8746        }
 8747
 8748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8749            s.move_with(|map, selection| {
 8750                selection.collapse_to(
 8751                    movement::end_of_paragraph(map, selection.head(), 1),
 8752                    SelectionGoal::None,
 8753                )
 8754            });
 8755        })
 8756    }
 8757
 8758    pub fn select_to_start_of_paragraph(
 8759        &mut self,
 8760        _: &SelectToStartOfParagraph,
 8761        window: &mut Window,
 8762        cx: &mut Context<Self>,
 8763    ) {
 8764        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8765            cx.propagate();
 8766            return;
 8767        }
 8768
 8769        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8770            s.move_heads_with(|map, head, _| {
 8771                (
 8772                    movement::start_of_paragraph(map, head, 1),
 8773                    SelectionGoal::None,
 8774                )
 8775            });
 8776        })
 8777    }
 8778
 8779    pub fn select_to_end_of_paragraph(
 8780        &mut self,
 8781        _: &SelectToEndOfParagraph,
 8782        window: &mut Window,
 8783        cx: &mut Context<Self>,
 8784    ) {
 8785        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8786            cx.propagate();
 8787            return;
 8788        }
 8789
 8790        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8791            s.move_heads_with(|map, head, _| {
 8792                (
 8793                    movement::end_of_paragraph(map, head, 1),
 8794                    SelectionGoal::None,
 8795                )
 8796            });
 8797        })
 8798    }
 8799
 8800    pub fn move_to_beginning(
 8801        &mut self,
 8802        _: &MoveToBeginning,
 8803        window: &mut Window,
 8804        cx: &mut Context<Self>,
 8805    ) {
 8806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8807            cx.propagate();
 8808            return;
 8809        }
 8810
 8811        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8812            s.select_ranges(vec![0..0]);
 8813        });
 8814    }
 8815
 8816    pub fn select_to_beginning(
 8817        &mut self,
 8818        _: &SelectToBeginning,
 8819        window: &mut Window,
 8820        cx: &mut Context<Self>,
 8821    ) {
 8822        let mut selection = self.selections.last::<Point>(cx);
 8823        selection.set_head(Point::zero(), SelectionGoal::None);
 8824
 8825        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8826            s.select(vec![selection]);
 8827        });
 8828    }
 8829
 8830    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8831        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8832            cx.propagate();
 8833            return;
 8834        }
 8835
 8836        let cursor = self.buffer.read(cx).read(cx).len();
 8837        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8838            s.select_ranges(vec![cursor..cursor])
 8839        });
 8840    }
 8841
 8842    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8843        self.nav_history = nav_history;
 8844    }
 8845
 8846    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8847        self.nav_history.as_ref()
 8848    }
 8849
 8850    fn push_to_nav_history(
 8851        &mut self,
 8852        cursor_anchor: Anchor,
 8853        new_position: Option<Point>,
 8854        cx: &mut Context<Self>,
 8855    ) {
 8856        if let Some(nav_history) = self.nav_history.as_mut() {
 8857            let buffer = self.buffer.read(cx).read(cx);
 8858            let cursor_position = cursor_anchor.to_point(&buffer);
 8859            let scroll_state = self.scroll_manager.anchor();
 8860            let scroll_top_row = scroll_state.top_row(&buffer);
 8861            drop(buffer);
 8862
 8863            if let Some(new_position) = new_position {
 8864                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8865                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8866                    return;
 8867                }
 8868            }
 8869
 8870            nav_history.push(
 8871                Some(NavigationData {
 8872                    cursor_anchor,
 8873                    cursor_position,
 8874                    scroll_anchor: scroll_state,
 8875                    scroll_top_row,
 8876                }),
 8877                cx,
 8878            );
 8879        }
 8880    }
 8881
 8882    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8883        let buffer = self.buffer.read(cx).snapshot(cx);
 8884        let mut selection = self.selections.first::<usize>(cx);
 8885        selection.set_head(buffer.len(), SelectionGoal::None);
 8886        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8887            s.select(vec![selection]);
 8888        });
 8889    }
 8890
 8891    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8892        let end = self.buffer.read(cx).read(cx).len();
 8893        self.change_selections(None, window, cx, |s| {
 8894            s.select_ranges(vec![0..end]);
 8895        });
 8896    }
 8897
 8898    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8899        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8900        let mut selections = self.selections.all::<Point>(cx);
 8901        let max_point = display_map.buffer_snapshot.max_point();
 8902        for selection in &mut selections {
 8903            let rows = selection.spanned_rows(true, &display_map);
 8904            selection.start = Point::new(rows.start.0, 0);
 8905            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8906            selection.reversed = false;
 8907        }
 8908        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8909            s.select(selections);
 8910        });
 8911    }
 8912
 8913    pub fn split_selection_into_lines(
 8914        &mut self,
 8915        _: &SplitSelectionIntoLines,
 8916        window: &mut Window,
 8917        cx: &mut Context<Self>,
 8918    ) {
 8919        let mut to_unfold = Vec::new();
 8920        let mut new_selection_ranges = Vec::new();
 8921        {
 8922            let selections = self.selections.all::<Point>(cx);
 8923            let buffer = self.buffer.read(cx).read(cx);
 8924            for selection in selections {
 8925                for row in selection.start.row..selection.end.row {
 8926                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8927                    new_selection_ranges.push(cursor..cursor);
 8928                }
 8929                new_selection_ranges.push(selection.end..selection.end);
 8930                to_unfold.push(selection.start..selection.end);
 8931            }
 8932        }
 8933        self.unfold_ranges(&to_unfold, true, true, cx);
 8934        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8935            s.select_ranges(new_selection_ranges);
 8936        });
 8937    }
 8938
 8939    pub fn add_selection_above(
 8940        &mut self,
 8941        _: &AddSelectionAbove,
 8942        window: &mut Window,
 8943        cx: &mut Context<Self>,
 8944    ) {
 8945        self.add_selection(true, window, cx);
 8946    }
 8947
 8948    pub fn add_selection_below(
 8949        &mut self,
 8950        _: &AddSelectionBelow,
 8951        window: &mut Window,
 8952        cx: &mut Context<Self>,
 8953    ) {
 8954        self.add_selection(false, window, cx);
 8955    }
 8956
 8957    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8958        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8959        let mut selections = self.selections.all::<Point>(cx);
 8960        let text_layout_details = self.text_layout_details(window);
 8961        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8962            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8963            let range = oldest_selection.display_range(&display_map).sorted();
 8964
 8965            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8966            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8967            let positions = start_x.min(end_x)..start_x.max(end_x);
 8968
 8969            selections.clear();
 8970            let mut stack = Vec::new();
 8971            for row in range.start.row().0..=range.end.row().0 {
 8972                if let Some(selection) = self.selections.build_columnar_selection(
 8973                    &display_map,
 8974                    DisplayRow(row),
 8975                    &positions,
 8976                    oldest_selection.reversed,
 8977                    &text_layout_details,
 8978                ) {
 8979                    stack.push(selection.id);
 8980                    selections.push(selection);
 8981                }
 8982            }
 8983
 8984            if above {
 8985                stack.reverse();
 8986            }
 8987
 8988            AddSelectionsState { above, stack }
 8989        });
 8990
 8991        let last_added_selection = *state.stack.last().unwrap();
 8992        let mut new_selections = Vec::new();
 8993        if above == state.above {
 8994            let end_row = if above {
 8995                DisplayRow(0)
 8996            } else {
 8997                display_map.max_point().row()
 8998            };
 8999
 9000            'outer: for selection in selections {
 9001                if selection.id == last_added_selection {
 9002                    let range = selection.display_range(&display_map).sorted();
 9003                    debug_assert_eq!(range.start.row(), range.end.row());
 9004                    let mut row = range.start.row();
 9005                    let positions =
 9006                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9007                            px(start)..px(end)
 9008                        } else {
 9009                            let start_x =
 9010                                display_map.x_for_display_point(range.start, &text_layout_details);
 9011                            let end_x =
 9012                                display_map.x_for_display_point(range.end, &text_layout_details);
 9013                            start_x.min(end_x)..start_x.max(end_x)
 9014                        };
 9015
 9016                    while row != end_row {
 9017                        if above {
 9018                            row.0 -= 1;
 9019                        } else {
 9020                            row.0 += 1;
 9021                        }
 9022
 9023                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9024                            &display_map,
 9025                            row,
 9026                            &positions,
 9027                            selection.reversed,
 9028                            &text_layout_details,
 9029                        ) {
 9030                            state.stack.push(new_selection.id);
 9031                            if above {
 9032                                new_selections.push(new_selection);
 9033                                new_selections.push(selection);
 9034                            } else {
 9035                                new_selections.push(selection);
 9036                                new_selections.push(new_selection);
 9037                            }
 9038
 9039                            continue 'outer;
 9040                        }
 9041                    }
 9042                }
 9043
 9044                new_selections.push(selection);
 9045            }
 9046        } else {
 9047            new_selections = selections;
 9048            new_selections.retain(|s| s.id != last_added_selection);
 9049            state.stack.pop();
 9050        }
 9051
 9052        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9053            s.select(new_selections);
 9054        });
 9055        if state.stack.len() > 1 {
 9056            self.add_selections_state = Some(state);
 9057        }
 9058    }
 9059
 9060    pub fn select_next_match_internal(
 9061        &mut self,
 9062        display_map: &DisplaySnapshot,
 9063        replace_newest: bool,
 9064        autoscroll: Option<Autoscroll>,
 9065        window: &mut Window,
 9066        cx: &mut Context<Self>,
 9067    ) -> Result<()> {
 9068        fn select_next_match_ranges(
 9069            this: &mut Editor,
 9070            range: Range<usize>,
 9071            replace_newest: bool,
 9072            auto_scroll: Option<Autoscroll>,
 9073            window: &mut Window,
 9074            cx: &mut Context<Editor>,
 9075        ) {
 9076            this.unfold_ranges(&[range.clone()], false, true, cx);
 9077            this.change_selections(auto_scroll, window, cx, |s| {
 9078                if replace_newest {
 9079                    s.delete(s.newest_anchor().id);
 9080                }
 9081                s.insert_range(range.clone());
 9082            });
 9083        }
 9084
 9085        let buffer = &display_map.buffer_snapshot;
 9086        let mut selections = self.selections.all::<usize>(cx);
 9087        if let Some(mut select_next_state) = self.select_next_state.take() {
 9088            let query = &select_next_state.query;
 9089            if !select_next_state.done {
 9090                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9091                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9092                let mut next_selected_range = None;
 9093
 9094                let bytes_after_last_selection =
 9095                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9096                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9097                let query_matches = query
 9098                    .stream_find_iter(bytes_after_last_selection)
 9099                    .map(|result| (last_selection.end, result))
 9100                    .chain(
 9101                        query
 9102                            .stream_find_iter(bytes_before_first_selection)
 9103                            .map(|result| (0, result)),
 9104                    );
 9105
 9106                for (start_offset, query_match) in query_matches {
 9107                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9108                    let offset_range =
 9109                        start_offset + query_match.start()..start_offset + query_match.end();
 9110                    let display_range = offset_range.start.to_display_point(display_map)
 9111                        ..offset_range.end.to_display_point(display_map);
 9112
 9113                    if !select_next_state.wordwise
 9114                        || (!movement::is_inside_word(display_map, display_range.start)
 9115                            && !movement::is_inside_word(display_map, display_range.end))
 9116                    {
 9117                        // TODO: This is n^2, because we might check all the selections
 9118                        if !selections
 9119                            .iter()
 9120                            .any(|selection| selection.range().overlaps(&offset_range))
 9121                        {
 9122                            next_selected_range = Some(offset_range);
 9123                            break;
 9124                        }
 9125                    }
 9126                }
 9127
 9128                if let Some(next_selected_range) = next_selected_range {
 9129                    select_next_match_ranges(
 9130                        self,
 9131                        next_selected_range,
 9132                        replace_newest,
 9133                        autoscroll,
 9134                        window,
 9135                        cx,
 9136                    );
 9137                } else {
 9138                    select_next_state.done = true;
 9139                }
 9140            }
 9141
 9142            self.select_next_state = Some(select_next_state);
 9143        } else {
 9144            let mut only_carets = true;
 9145            let mut same_text_selected = true;
 9146            let mut selected_text = None;
 9147
 9148            let mut selections_iter = selections.iter().peekable();
 9149            while let Some(selection) = selections_iter.next() {
 9150                if selection.start != selection.end {
 9151                    only_carets = false;
 9152                }
 9153
 9154                if same_text_selected {
 9155                    if selected_text.is_none() {
 9156                        selected_text =
 9157                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9158                    }
 9159
 9160                    if let Some(next_selection) = selections_iter.peek() {
 9161                        if next_selection.range().len() == selection.range().len() {
 9162                            let next_selected_text = buffer
 9163                                .text_for_range(next_selection.range())
 9164                                .collect::<String>();
 9165                            if Some(next_selected_text) != selected_text {
 9166                                same_text_selected = false;
 9167                                selected_text = None;
 9168                            }
 9169                        } else {
 9170                            same_text_selected = false;
 9171                            selected_text = None;
 9172                        }
 9173                    }
 9174                }
 9175            }
 9176
 9177            if only_carets {
 9178                for selection in &mut selections {
 9179                    let word_range = movement::surrounding_word(
 9180                        display_map,
 9181                        selection.start.to_display_point(display_map),
 9182                    );
 9183                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9184                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9185                    selection.goal = SelectionGoal::None;
 9186                    selection.reversed = false;
 9187                    select_next_match_ranges(
 9188                        self,
 9189                        selection.start..selection.end,
 9190                        replace_newest,
 9191                        autoscroll,
 9192                        window,
 9193                        cx,
 9194                    );
 9195                }
 9196
 9197                if selections.len() == 1 {
 9198                    let selection = selections
 9199                        .last()
 9200                        .expect("ensured that there's only one selection");
 9201                    let query = buffer
 9202                        .text_for_range(selection.start..selection.end)
 9203                        .collect::<String>();
 9204                    let is_empty = query.is_empty();
 9205                    let select_state = SelectNextState {
 9206                        query: AhoCorasick::new(&[query])?,
 9207                        wordwise: true,
 9208                        done: is_empty,
 9209                    };
 9210                    self.select_next_state = Some(select_state);
 9211                } else {
 9212                    self.select_next_state = None;
 9213                }
 9214            } else if let Some(selected_text) = selected_text {
 9215                self.select_next_state = Some(SelectNextState {
 9216                    query: AhoCorasick::new(&[selected_text])?,
 9217                    wordwise: false,
 9218                    done: false,
 9219                });
 9220                self.select_next_match_internal(
 9221                    display_map,
 9222                    replace_newest,
 9223                    autoscroll,
 9224                    window,
 9225                    cx,
 9226                )?;
 9227            }
 9228        }
 9229        Ok(())
 9230    }
 9231
 9232    pub fn select_all_matches(
 9233        &mut self,
 9234        _action: &SelectAllMatches,
 9235        window: &mut Window,
 9236        cx: &mut Context<Self>,
 9237    ) -> Result<()> {
 9238        self.push_to_selection_history();
 9239        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9240
 9241        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9242        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9243            return Ok(());
 9244        };
 9245        if select_next_state.done {
 9246            return Ok(());
 9247        }
 9248
 9249        let mut new_selections = self.selections.all::<usize>(cx);
 9250
 9251        let buffer = &display_map.buffer_snapshot;
 9252        let query_matches = select_next_state
 9253            .query
 9254            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9255
 9256        for query_match in query_matches {
 9257            let query_match = query_match.unwrap(); // can only fail due to I/O
 9258            let offset_range = query_match.start()..query_match.end();
 9259            let display_range = offset_range.start.to_display_point(&display_map)
 9260                ..offset_range.end.to_display_point(&display_map);
 9261
 9262            if !select_next_state.wordwise
 9263                || (!movement::is_inside_word(&display_map, display_range.start)
 9264                    && !movement::is_inside_word(&display_map, display_range.end))
 9265            {
 9266                self.selections.change_with(cx, |selections| {
 9267                    new_selections.push(Selection {
 9268                        id: selections.new_selection_id(),
 9269                        start: offset_range.start,
 9270                        end: offset_range.end,
 9271                        reversed: false,
 9272                        goal: SelectionGoal::None,
 9273                    });
 9274                });
 9275            }
 9276        }
 9277
 9278        new_selections.sort_by_key(|selection| selection.start);
 9279        let mut ix = 0;
 9280        while ix + 1 < new_selections.len() {
 9281            let current_selection = &new_selections[ix];
 9282            let next_selection = &new_selections[ix + 1];
 9283            if current_selection.range().overlaps(&next_selection.range()) {
 9284                if current_selection.id < next_selection.id {
 9285                    new_selections.remove(ix + 1);
 9286                } else {
 9287                    new_selections.remove(ix);
 9288                }
 9289            } else {
 9290                ix += 1;
 9291            }
 9292        }
 9293
 9294        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9295
 9296        for selection in new_selections.iter_mut() {
 9297            selection.reversed = reversed;
 9298        }
 9299
 9300        select_next_state.done = true;
 9301        self.unfold_ranges(
 9302            &new_selections
 9303                .iter()
 9304                .map(|selection| selection.range())
 9305                .collect::<Vec<_>>(),
 9306            false,
 9307            false,
 9308            cx,
 9309        );
 9310        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9311            selections.select(new_selections)
 9312        });
 9313
 9314        Ok(())
 9315    }
 9316
 9317    pub fn select_next(
 9318        &mut self,
 9319        action: &SelectNext,
 9320        window: &mut Window,
 9321        cx: &mut Context<Self>,
 9322    ) -> Result<()> {
 9323        self.push_to_selection_history();
 9324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9325        self.select_next_match_internal(
 9326            &display_map,
 9327            action.replace_newest,
 9328            Some(Autoscroll::newest()),
 9329            window,
 9330            cx,
 9331        )?;
 9332        Ok(())
 9333    }
 9334
 9335    pub fn select_previous(
 9336        &mut self,
 9337        action: &SelectPrevious,
 9338        window: &mut Window,
 9339        cx: &mut Context<Self>,
 9340    ) -> Result<()> {
 9341        self.push_to_selection_history();
 9342        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9343        let buffer = &display_map.buffer_snapshot;
 9344        let mut selections = self.selections.all::<usize>(cx);
 9345        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9346            let query = &select_prev_state.query;
 9347            if !select_prev_state.done {
 9348                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9349                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9350                let mut next_selected_range = None;
 9351                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9352                let bytes_before_last_selection =
 9353                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9354                let bytes_after_first_selection =
 9355                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9356                let query_matches = query
 9357                    .stream_find_iter(bytes_before_last_selection)
 9358                    .map(|result| (last_selection.start, result))
 9359                    .chain(
 9360                        query
 9361                            .stream_find_iter(bytes_after_first_selection)
 9362                            .map(|result| (buffer.len(), result)),
 9363                    );
 9364                for (end_offset, query_match) in query_matches {
 9365                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9366                    let offset_range =
 9367                        end_offset - query_match.end()..end_offset - query_match.start();
 9368                    let display_range = offset_range.start.to_display_point(&display_map)
 9369                        ..offset_range.end.to_display_point(&display_map);
 9370
 9371                    if !select_prev_state.wordwise
 9372                        || (!movement::is_inside_word(&display_map, display_range.start)
 9373                            && !movement::is_inside_word(&display_map, display_range.end))
 9374                    {
 9375                        next_selected_range = Some(offset_range);
 9376                        break;
 9377                    }
 9378                }
 9379
 9380                if let Some(next_selected_range) = next_selected_range {
 9381                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9382                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9383                        if action.replace_newest {
 9384                            s.delete(s.newest_anchor().id);
 9385                        }
 9386                        s.insert_range(next_selected_range);
 9387                    });
 9388                } else {
 9389                    select_prev_state.done = true;
 9390                }
 9391            }
 9392
 9393            self.select_prev_state = Some(select_prev_state);
 9394        } else {
 9395            let mut only_carets = true;
 9396            let mut same_text_selected = true;
 9397            let mut selected_text = None;
 9398
 9399            let mut selections_iter = selections.iter().peekable();
 9400            while let Some(selection) = selections_iter.next() {
 9401                if selection.start != selection.end {
 9402                    only_carets = false;
 9403                }
 9404
 9405                if same_text_selected {
 9406                    if selected_text.is_none() {
 9407                        selected_text =
 9408                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9409                    }
 9410
 9411                    if let Some(next_selection) = selections_iter.peek() {
 9412                        if next_selection.range().len() == selection.range().len() {
 9413                            let next_selected_text = buffer
 9414                                .text_for_range(next_selection.range())
 9415                                .collect::<String>();
 9416                            if Some(next_selected_text) != selected_text {
 9417                                same_text_selected = false;
 9418                                selected_text = None;
 9419                            }
 9420                        } else {
 9421                            same_text_selected = false;
 9422                            selected_text = None;
 9423                        }
 9424                    }
 9425                }
 9426            }
 9427
 9428            if only_carets {
 9429                for selection in &mut selections {
 9430                    let word_range = movement::surrounding_word(
 9431                        &display_map,
 9432                        selection.start.to_display_point(&display_map),
 9433                    );
 9434                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9435                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9436                    selection.goal = SelectionGoal::None;
 9437                    selection.reversed = false;
 9438                }
 9439                if selections.len() == 1 {
 9440                    let selection = selections
 9441                        .last()
 9442                        .expect("ensured that there's only one selection");
 9443                    let query = buffer
 9444                        .text_for_range(selection.start..selection.end)
 9445                        .collect::<String>();
 9446                    let is_empty = query.is_empty();
 9447                    let select_state = SelectNextState {
 9448                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9449                        wordwise: true,
 9450                        done: is_empty,
 9451                    };
 9452                    self.select_prev_state = Some(select_state);
 9453                } else {
 9454                    self.select_prev_state = None;
 9455                }
 9456
 9457                self.unfold_ranges(
 9458                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9459                    false,
 9460                    true,
 9461                    cx,
 9462                );
 9463                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9464                    s.select(selections);
 9465                });
 9466            } else if let Some(selected_text) = selected_text {
 9467                self.select_prev_state = Some(SelectNextState {
 9468                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9469                    wordwise: false,
 9470                    done: false,
 9471                });
 9472                self.select_previous(action, window, cx)?;
 9473            }
 9474        }
 9475        Ok(())
 9476    }
 9477
 9478    pub fn toggle_comments(
 9479        &mut self,
 9480        action: &ToggleComments,
 9481        window: &mut Window,
 9482        cx: &mut Context<Self>,
 9483    ) {
 9484        if self.read_only(cx) {
 9485            return;
 9486        }
 9487        let text_layout_details = &self.text_layout_details(window);
 9488        self.transact(window, cx, |this, window, cx| {
 9489            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9490            let mut edits = Vec::new();
 9491            let mut selection_edit_ranges = Vec::new();
 9492            let mut last_toggled_row = None;
 9493            let snapshot = this.buffer.read(cx).read(cx);
 9494            let empty_str: Arc<str> = Arc::default();
 9495            let mut suffixes_inserted = Vec::new();
 9496            let ignore_indent = action.ignore_indent;
 9497
 9498            fn comment_prefix_range(
 9499                snapshot: &MultiBufferSnapshot,
 9500                row: MultiBufferRow,
 9501                comment_prefix: &str,
 9502                comment_prefix_whitespace: &str,
 9503                ignore_indent: bool,
 9504            ) -> Range<Point> {
 9505                let indent_size = if ignore_indent {
 9506                    0
 9507                } else {
 9508                    snapshot.indent_size_for_line(row).len
 9509                };
 9510
 9511                let start = Point::new(row.0, indent_size);
 9512
 9513                let mut line_bytes = snapshot
 9514                    .bytes_in_range(start..snapshot.max_point())
 9515                    .flatten()
 9516                    .copied();
 9517
 9518                // If this line currently begins with the line comment prefix, then record
 9519                // the range containing the prefix.
 9520                if line_bytes
 9521                    .by_ref()
 9522                    .take(comment_prefix.len())
 9523                    .eq(comment_prefix.bytes())
 9524                {
 9525                    // Include any whitespace that matches the comment prefix.
 9526                    let matching_whitespace_len = line_bytes
 9527                        .zip(comment_prefix_whitespace.bytes())
 9528                        .take_while(|(a, b)| a == b)
 9529                        .count() as u32;
 9530                    let end = Point::new(
 9531                        start.row,
 9532                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9533                    );
 9534                    start..end
 9535                } else {
 9536                    start..start
 9537                }
 9538            }
 9539
 9540            fn comment_suffix_range(
 9541                snapshot: &MultiBufferSnapshot,
 9542                row: MultiBufferRow,
 9543                comment_suffix: &str,
 9544                comment_suffix_has_leading_space: bool,
 9545            ) -> Range<Point> {
 9546                let end = Point::new(row.0, snapshot.line_len(row));
 9547                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9548
 9549                let mut line_end_bytes = snapshot
 9550                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9551                    .flatten()
 9552                    .copied();
 9553
 9554                let leading_space_len = if suffix_start_column > 0
 9555                    && line_end_bytes.next() == Some(b' ')
 9556                    && comment_suffix_has_leading_space
 9557                {
 9558                    1
 9559                } else {
 9560                    0
 9561                };
 9562
 9563                // If this line currently begins with the line comment prefix, then record
 9564                // the range containing the prefix.
 9565                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9566                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9567                    start..end
 9568                } else {
 9569                    end..end
 9570                }
 9571            }
 9572
 9573            // TODO: Handle selections that cross excerpts
 9574            for selection in &mut selections {
 9575                let start_column = snapshot
 9576                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9577                    .len;
 9578                let language = if let Some(language) =
 9579                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9580                {
 9581                    language
 9582                } else {
 9583                    continue;
 9584                };
 9585
 9586                selection_edit_ranges.clear();
 9587
 9588                // If multiple selections contain a given row, avoid processing that
 9589                // row more than once.
 9590                let mut start_row = MultiBufferRow(selection.start.row);
 9591                if last_toggled_row == Some(start_row) {
 9592                    start_row = start_row.next_row();
 9593                }
 9594                let end_row =
 9595                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9596                        MultiBufferRow(selection.end.row - 1)
 9597                    } else {
 9598                        MultiBufferRow(selection.end.row)
 9599                    };
 9600                last_toggled_row = Some(end_row);
 9601
 9602                if start_row > end_row {
 9603                    continue;
 9604                }
 9605
 9606                // If the language has line comments, toggle those.
 9607                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9608
 9609                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9610                if ignore_indent {
 9611                    full_comment_prefixes = full_comment_prefixes
 9612                        .into_iter()
 9613                        .map(|s| Arc::from(s.trim_end()))
 9614                        .collect();
 9615                }
 9616
 9617                if !full_comment_prefixes.is_empty() {
 9618                    let first_prefix = full_comment_prefixes
 9619                        .first()
 9620                        .expect("prefixes is non-empty");
 9621                    let prefix_trimmed_lengths = full_comment_prefixes
 9622                        .iter()
 9623                        .map(|p| p.trim_end_matches(' ').len())
 9624                        .collect::<SmallVec<[usize; 4]>>();
 9625
 9626                    let mut all_selection_lines_are_comments = true;
 9627
 9628                    for row in start_row.0..=end_row.0 {
 9629                        let row = MultiBufferRow(row);
 9630                        if start_row < end_row && snapshot.is_line_blank(row) {
 9631                            continue;
 9632                        }
 9633
 9634                        let prefix_range = full_comment_prefixes
 9635                            .iter()
 9636                            .zip(prefix_trimmed_lengths.iter().copied())
 9637                            .map(|(prefix, trimmed_prefix_len)| {
 9638                                comment_prefix_range(
 9639                                    snapshot.deref(),
 9640                                    row,
 9641                                    &prefix[..trimmed_prefix_len],
 9642                                    &prefix[trimmed_prefix_len..],
 9643                                    ignore_indent,
 9644                                )
 9645                            })
 9646                            .max_by_key(|range| range.end.column - range.start.column)
 9647                            .expect("prefixes is non-empty");
 9648
 9649                        if prefix_range.is_empty() {
 9650                            all_selection_lines_are_comments = false;
 9651                        }
 9652
 9653                        selection_edit_ranges.push(prefix_range);
 9654                    }
 9655
 9656                    if all_selection_lines_are_comments {
 9657                        edits.extend(
 9658                            selection_edit_ranges
 9659                                .iter()
 9660                                .cloned()
 9661                                .map(|range| (range, empty_str.clone())),
 9662                        );
 9663                    } else {
 9664                        let min_column = selection_edit_ranges
 9665                            .iter()
 9666                            .map(|range| range.start.column)
 9667                            .min()
 9668                            .unwrap_or(0);
 9669                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9670                            let position = Point::new(range.start.row, min_column);
 9671                            (position..position, first_prefix.clone())
 9672                        }));
 9673                    }
 9674                } else if let Some((full_comment_prefix, comment_suffix)) =
 9675                    language.block_comment_delimiters()
 9676                {
 9677                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9678                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9679                    let prefix_range = comment_prefix_range(
 9680                        snapshot.deref(),
 9681                        start_row,
 9682                        comment_prefix,
 9683                        comment_prefix_whitespace,
 9684                        ignore_indent,
 9685                    );
 9686                    let suffix_range = comment_suffix_range(
 9687                        snapshot.deref(),
 9688                        end_row,
 9689                        comment_suffix.trim_start_matches(' '),
 9690                        comment_suffix.starts_with(' '),
 9691                    );
 9692
 9693                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9694                        edits.push((
 9695                            prefix_range.start..prefix_range.start,
 9696                            full_comment_prefix.clone(),
 9697                        ));
 9698                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9699                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9700                    } else {
 9701                        edits.push((prefix_range, empty_str.clone()));
 9702                        edits.push((suffix_range, empty_str.clone()));
 9703                    }
 9704                } else {
 9705                    continue;
 9706                }
 9707            }
 9708
 9709            drop(snapshot);
 9710            this.buffer.update(cx, |buffer, cx| {
 9711                buffer.edit(edits, None, cx);
 9712            });
 9713
 9714            // Adjust selections so that they end before any comment suffixes that
 9715            // were inserted.
 9716            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9717            let mut selections = this.selections.all::<Point>(cx);
 9718            let snapshot = this.buffer.read(cx).read(cx);
 9719            for selection in &mut selections {
 9720                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9721                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9722                        Ordering::Less => {
 9723                            suffixes_inserted.next();
 9724                            continue;
 9725                        }
 9726                        Ordering::Greater => break,
 9727                        Ordering::Equal => {
 9728                            if selection.end.column == snapshot.line_len(row) {
 9729                                if selection.is_empty() {
 9730                                    selection.start.column -= suffix_len as u32;
 9731                                }
 9732                                selection.end.column -= suffix_len as u32;
 9733                            }
 9734                            break;
 9735                        }
 9736                    }
 9737                }
 9738            }
 9739
 9740            drop(snapshot);
 9741            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9742                s.select(selections)
 9743            });
 9744
 9745            let selections = this.selections.all::<Point>(cx);
 9746            let selections_on_single_row = selections.windows(2).all(|selections| {
 9747                selections[0].start.row == selections[1].start.row
 9748                    && selections[0].end.row == selections[1].end.row
 9749                    && selections[0].start.row == selections[0].end.row
 9750            });
 9751            let selections_selecting = selections
 9752                .iter()
 9753                .any(|selection| selection.start != selection.end);
 9754            let advance_downwards = action.advance_downwards
 9755                && selections_on_single_row
 9756                && !selections_selecting
 9757                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9758
 9759            if advance_downwards {
 9760                let snapshot = this.buffer.read(cx).snapshot(cx);
 9761
 9762                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9763                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9764                        let mut point = display_point.to_point(display_snapshot);
 9765                        point.row += 1;
 9766                        point = snapshot.clip_point(point, Bias::Left);
 9767                        let display_point = point.to_display_point(display_snapshot);
 9768                        let goal = SelectionGoal::HorizontalPosition(
 9769                            display_snapshot
 9770                                .x_for_display_point(display_point, text_layout_details)
 9771                                .into(),
 9772                        );
 9773                        (display_point, goal)
 9774                    })
 9775                });
 9776            }
 9777        });
 9778    }
 9779
 9780    pub fn select_enclosing_symbol(
 9781        &mut self,
 9782        _: &SelectEnclosingSymbol,
 9783        window: &mut Window,
 9784        cx: &mut Context<Self>,
 9785    ) {
 9786        let buffer = self.buffer.read(cx).snapshot(cx);
 9787        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9788
 9789        fn update_selection(
 9790            selection: &Selection<usize>,
 9791            buffer_snap: &MultiBufferSnapshot,
 9792        ) -> Option<Selection<usize>> {
 9793            let cursor = selection.head();
 9794            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9795            for symbol in symbols.iter().rev() {
 9796                let start = symbol.range.start.to_offset(buffer_snap);
 9797                let end = symbol.range.end.to_offset(buffer_snap);
 9798                let new_range = start..end;
 9799                if start < selection.start || end > selection.end {
 9800                    return Some(Selection {
 9801                        id: selection.id,
 9802                        start: new_range.start,
 9803                        end: new_range.end,
 9804                        goal: SelectionGoal::None,
 9805                        reversed: selection.reversed,
 9806                    });
 9807                }
 9808            }
 9809            None
 9810        }
 9811
 9812        let mut selected_larger_symbol = false;
 9813        let new_selections = old_selections
 9814            .iter()
 9815            .map(|selection| match update_selection(selection, &buffer) {
 9816                Some(new_selection) => {
 9817                    if new_selection.range() != selection.range() {
 9818                        selected_larger_symbol = true;
 9819                    }
 9820                    new_selection
 9821                }
 9822                None => selection.clone(),
 9823            })
 9824            .collect::<Vec<_>>();
 9825
 9826        if selected_larger_symbol {
 9827            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9828                s.select(new_selections);
 9829            });
 9830        }
 9831    }
 9832
 9833    pub fn select_larger_syntax_node(
 9834        &mut self,
 9835        _: &SelectLargerSyntaxNode,
 9836        window: &mut Window,
 9837        cx: &mut Context<Self>,
 9838    ) {
 9839        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9840        let buffer = self.buffer.read(cx).snapshot(cx);
 9841        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9842
 9843        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9844        let mut selected_larger_node = false;
 9845        let new_selections = old_selections
 9846            .iter()
 9847            .map(|selection| {
 9848                let old_range = selection.start..selection.end;
 9849                let mut new_range = old_range.clone();
 9850                let mut new_node = None;
 9851                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9852                {
 9853                    new_node = Some(node);
 9854                    new_range = containing_range;
 9855                    if !display_map.intersects_fold(new_range.start)
 9856                        && !display_map.intersects_fold(new_range.end)
 9857                    {
 9858                        break;
 9859                    }
 9860                }
 9861
 9862                if let Some(node) = new_node {
 9863                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9864                    // nodes. Parent and grandparent are also logged because this operation will not
 9865                    // visit nodes that have the same range as their parent.
 9866                    log::info!("Node: {node:?}");
 9867                    let parent = node.parent();
 9868                    log::info!("Parent: {parent:?}");
 9869                    let grandparent = parent.and_then(|x| x.parent());
 9870                    log::info!("Grandparent: {grandparent:?}");
 9871                }
 9872
 9873                selected_larger_node |= new_range != old_range;
 9874                Selection {
 9875                    id: selection.id,
 9876                    start: new_range.start,
 9877                    end: new_range.end,
 9878                    goal: SelectionGoal::None,
 9879                    reversed: selection.reversed,
 9880                }
 9881            })
 9882            .collect::<Vec<_>>();
 9883
 9884        if selected_larger_node {
 9885            stack.push(old_selections);
 9886            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9887                s.select(new_selections);
 9888            });
 9889        }
 9890        self.select_larger_syntax_node_stack = stack;
 9891    }
 9892
 9893    pub fn select_smaller_syntax_node(
 9894        &mut self,
 9895        _: &SelectSmallerSyntaxNode,
 9896        window: &mut Window,
 9897        cx: &mut Context<Self>,
 9898    ) {
 9899        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9900        if let Some(selections) = stack.pop() {
 9901            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9902                s.select(selections.to_vec());
 9903            });
 9904        }
 9905        self.select_larger_syntax_node_stack = stack;
 9906    }
 9907
 9908    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9909        if !EditorSettings::get_global(cx).gutter.runnables {
 9910            self.clear_tasks();
 9911            return Task::ready(());
 9912        }
 9913        let project = self.project.as_ref().map(Entity::downgrade);
 9914        cx.spawn_in(window, |this, mut cx| async move {
 9915            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9916            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9917                return;
 9918            };
 9919            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9920                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9921            }) else {
 9922                return;
 9923            };
 9924
 9925            let hide_runnables = project
 9926                .update(&mut cx, |project, cx| {
 9927                    // Do not display any test indicators in non-dev server remote projects.
 9928                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9929                })
 9930                .unwrap_or(true);
 9931            if hide_runnables {
 9932                return;
 9933            }
 9934            let new_rows =
 9935                cx.background_executor()
 9936                    .spawn({
 9937                        let snapshot = display_snapshot.clone();
 9938                        async move {
 9939                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9940                        }
 9941                    })
 9942                    .await;
 9943
 9944            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9945            this.update(&mut cx, |this, _| {
 9946                this.clear_tasks();
 9947                for (key, value) in rows {
 9948                    this.insert_tasks(key, value);
 9949                }
 9950            })
 9951            .ok();
 9952        })
 9953    }
 9954    fn fetch_runnable_ranges(
 9955        snapshot: &DisplaySnapshot,
 9956        range: Range<Anchor>,
 9957    ) -> Vec<language::RunnableRange> {
 9958        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9959    }
 9960
 9961    fn runnable_rows(
 9962        project: Entity<Project>,
 9963        snapshot: DisplaySnapshot,
 9964        runnable_ranges: Vec<RunnableRange>,
 9965        mut cx: AsyncWindowContext,
 9966    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9967        runnable_ranges
 9968            .into_iter()
 9969            .filter_map(|mut runnable| {
 9970                let tasks = cx
 9971                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9972                    .ok()?;
 9973                if tasks.is_empty() {
 9974                    return None;
 9975                }
 9976
 9977                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9978
 9979                let row = snapshot
 9980                    .buffer_snapshot
 9981                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9982                    .1
 9983                    .start
 9984                    .row;
 9985
 9986                let context_range =
 9987                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9988                Some((
 9989                    (runnable.buffer_id, row),
 9990                    RunnableTasks {
 9991                        templates: tasks,
 9992                        offset: MultiBufferOffset(runnable.run_range.start),
 9993                        context_range,
 9994                        column: point.column,
 9995                        extra_variables: runnable.extra_captures,
 9996                    },
 9997                ))
 9998            })
 9999            .collect()
10000    }
10001
10002    fn templates_with_tags(
10003        project: &Entity<Project>,
10004        runnable: &mut Runnable,
10005        cx: &mut App,
10006    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10007        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10008            let (worktree_id, file) = project
10009                .buffer_for_id(runnable.buffer, cx)
10010                .and_then(|buffer| buffer.read(cx).file())
10011                .map(|file| (file.worktree_id(cx), file.clone()))
10012                .unzip();
10013
10014            (
10015                project.task_store().read(cx).task_inventory().cloned(),
10016                worktree_id,
10017                file,
10018            )
10019        });
10020
10021        let tags = mem::take(&mut runnable.tags);
10022        let mut tags: Vec<_> = tags
10023            .into_iter()
10024            .flat_map(|tag| {
10025                let tag = tag.0.clone();
10026                inventory
10027                    .as_ref()
10028                    .into_iter()
10029                    .flat_map(|inventory| {
10030                        inventory.read(cx).list_tasks(
10031                            file.clone(),
10032                            Some(runnable.language.clone()),
10033                            worktree_id,
10034                            cx,
10035                        )
10036                    })
10037                    .filter(move |(_, template)| {
10038                        template.tags.iter().any(|source_tag| source_tag == &tag)
10039                    })
10040            })
10041            .sorted_by_key(|(kind, _)| kind.to_owned())
10042            .collect();
10043        if let Some((leading_tag_source, _)) = tags.first() {
10044            // Strongest source wins; if we have worktree tag binding, prefer that to
10045            // global and language bindings;
10046            // if we have a global binding, prefer that to language binding.
10047            let first_mismatch = tags
10048                .iter()
10049                .position(|(tag_source, _)| tag_source != leading_tag_source);
10050            if let Some(index) = first_mismatch {
10051                tags.truncate(index);
10052            }
10053        }
10054
10055        tags
10056    }
10057
10058    pub fn move_to_enclosing_bracket(
10059        &mut self,
10060        _: &MoveToEnclosingBracket,
10061        window: &mut Window,
10062        cx: &mut Context<Self>,
10063    ) {
10064        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10065            s.move_offsets_with(|snapshot, selection| {
10066                let Some(enclosing_bracket_ranges) =
10067                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10068                else {
10069                    return;
10070                };
10071
10072                let mut best_length = usize::MAX;
10073                let mut best_inside = false;
10074                let mut best_in_bracket_range = false;
10075                let mut best_destination = None;
10076                for (open, close) in enclosing_bracket_ranges {
10077                    let close = close.to_inclusive();
10078                    let length = close.end() - open.start;
10079                    let inside = selection.start >= open.end && selection.end <= *close.start();
10080                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10081                        || close.contains(&selection.head());
10082
10083                    // If best is next to a bracket and current isn't, skip
10084                    if !in_bracket_range && best_in_bracket_range {
10085                        continue;
10086                    }
10087
10088                    // Prefer smaller lengths unless best is inside and current isn't
10089                    if length > best_length && (best_inside || !inside) {
10090                        continue;
10091                    }
10092
10093                    best_length = length;
10094                    best_inside = inside;
10095                    best_in_bracket_range = in_bracket_range;
10096                    best_destination = Some(
10097                        if close.contains(&selection.start) && close.contains(&selection.end) {
10098                            if inside {
10099                                open.end
10100                            } else {
10101                                open.start
10102                            }
10103                        } else if inside {
10104                            *close.start()
10105                        } else {
10106                            *close.end()
10107                        },
10108                    );
10109                }
10110
10111                if let Some(destination) = best_destination {
10112                    selection.collapse_to(destination, SelectionGoal::None);
10113                }
10114            })
10115        });
10116    }
10117
10118    pub fn undo_selection(
10119        &mut self,
10120        _: &UndoSelection,
10121        window: &mut Window,
10122        cx: &mut Context<Self>,
10123    ) {
10124        self.end_selection(window, cx);
10125        self.selection_history.mode = SelectionHistoryMode::Undoing;
10126        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10127            self.change_selections(None, window, cx, |s| {
10128                s.select_anchors(entry.selections.to_vec())
10129            });
10130            self.select_next_state = entry.select_next_state;
10131            self.select_prev_state = entry.select_prev_state;
10132            self.add_selections_state = entry.add_selections_state;
10133            self.request_autoscroll(Autoscroll::newest(), cx);
10134        }
10135        self.selection_history.mode = SelectionHistoryMode::Normal;
10136    }
10137
10138    pub fn redo_selection(
10139        &mut self,
10140        _: &RedoSelection,
10141        window: &mut Window,
10142        cx: &mut Context<Self>,
10143    ) {
10144        self.end_selection(window, cx);
10145        self.selection_history.mode = SelectionHistoryMode::Redoing;
10146        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10147            self.change_selections(None, window, cx, |s| {
10148                s.select_anchors(entry.selections.to_vec())
10149            });
10150            self.select_next_state = entry.select_next_state;
10151            self.select_prev_state = entry.select_prev_state;
10152            self.add_selections_state = entry.add_selections_state;
10153            self.request_autoscroll(Autoscroll::newest(), cx);
10154        }
10155        self.selection_history.mode = SelectionHistoryMode::Normal;
10156    }
10157
10158    pub fn expand_excerpts(
10159        &mut self,
10160        action: &ExpandExcerpts,
10161        _: &mut Window,
10162        cx: &mut Context<Self>,
10163    ) {
10164        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10165    }
10166
10167    pub fn expand_excerpts_down(
10168        &mut self,
10169        action: &ExpandExcerptsDown,
10170        _: &mut Window,
10171        cx: &mut Context<Self>,
10172    ) {
10173        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10174    }
10175
10176    pub fn expand_excerpts_up(
10177        &mut self,
10178        action: &ExpandExcerptsUp,
10179        _: &mut Window,
10180        cx: &mut Context<Self>,
10181    ) {
10182        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10183    }
10184
10185    pub fn expand_excerpts_for_direction(
10186        &mut self,
10187        lines: u32,
10188        direction: ExpandExcerptDirection,
10189
10190        cx: &mut Context<Self>,
10191    ) {
10192        let selections = self.selections.disjoint_anchors();
10193
10194        let lines = if lines == 0 {
10195            EditorSettings::get_global(cx).expand_excerpt_lines
10196        } else {
10197            lines
10198        };
10199
10200        self.buffer.update(cx, |buffer, cx| {
10201            let snapshot = buffer.snapshot(cx);
10202            let mut excerpt_ids = selections
10203                .iter()
10204                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10205                .collect::<Vec<_>>();
10206            excerpt_ids.sort();
10207            excerpt_ids.dedup();
10208            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10209        })
10210    }
10211
10212    pub fn expand_excerpt(
10213        &mut self,
10214        excerpt: ExcerptId,
10215        direction: ExpandExcerptDirection,
10216        cx: &mut Context<Self>,
10217    ) {
10218        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10219        self.buffer.update(cx, |buffer, cx| {
10220            buffer.expand_excerpts([excerpt], lines, direction, cx)
10221        })
10222    }
10223
10224    pub fn go_to_singleton_buffer_point(
10225        &mut self,
10226        point: Point,
10227        window: &mut Window,
10228        cx: &mut Context<Self>,
10229    ) {
10230        self.go_to_singleton_buffer_range(point..point, window, cx);
10231    }
10232
10233    pub fn go_to_singleton_buffer_range(
10234        &mut self,
10235        range: Range<Point>,
10236        window: &mut Window,
10237        cx: &mut Context<Self>,
10238    ) {
10239        let multibuffer = self.buffer().read(cx);
10240        let Some(buffer) = multibuffer.as_singleton() else {
10241            return;
10242        };
10243        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10244            return;
10245        };
10246        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10247            return;
10248        };
10249        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10250            s.select_anchor_ranges([start..end])
10251        });
10252    }
10253
10254    fn go_to_diagnostic(
10255        &mut self,
10256        _: &GoToDiagnostic,
10257        window: &mut Window,
10258        cx: &mut Context<Self>,
10259    ) {
10260        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10261    }
10262
10263    fn go_to_prev_diagnostic(
10264        &mut self,
10265        _: &GoToPrevDiagnostic,
10266        window: &mut Window,
10267        cx: &mut Context<Self>,
10268    ) {
10269        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10270    }
10271
10272    pub fn go_to_diagnostic_impl(
10273        &mut self,
10274        direction: Direction,
10275        window: &mut Window,
10276        cx: &mut Context<Self>,
10277    ) {
10278        let buffer = self.buffer.read(cx).snapshot(cx);
10279        let selection = self.selections.newest::<usize>(cx);
10280
10281        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10282        if direction == Direction::Next {
10283            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10284                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10285                    return;
10286                };
10287                self.activate_diagnostics(
10288                    buffer_id,
10289                    popover.local_diagnostic.diagnostic.group_id,
10290                    window,
10291                    cx,
10292                );
10293                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10294                    let primary_range_start = active_diagnostics.primary_range.start;
10295                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10296                        let mut new_selection = s.newest_anchor().clone();
10297                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10298                        s.select_anchors(vec![new_selection.clone()]);
10299                    });
10300                    self.refresh_inline_completion(false, true, window, cx);
10301                }
10302                return;
10303            }
10304        }
10305
10306        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10307            active_diagnostics
10308                .primary_range
10309                .to_offset(&buffer)
10310                .to_inclusive()
10311        });
10312        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10313            if active_primary_range.contains(&selection.head()) {
10314                *active_primary_range.start()
10315            } else {
10316                selection.head()
10317            }
10318        } else {
10319            selection.head()
10320        };
10321        let snapshot = self.snapshot(window, cx);
10322        loop {
10323            let mut diagnostics;
10324            if direction == Direction::Prev {
10325                diagnostics = buffer
10326                    .diagnostics_in_range::<usize>(0..search_start)
10327                    .collect::<Vec<_>>();
10328                diagnostics.reverse();
10329            } else {
10330                diagnostics = buffer
10331                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10332                    .collect::<Vec<_>>();
10333            };
10334            let group = diagnostics
10335                .into_iter()
10336                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10337                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10338                // be sorted in a stable way
10339                // skip until we are at current active diagnostic, if it exists
10340                .skip_while(|entry| {
10341                    let is_in_range = match direction {
10342                        Direction::Prev => entry.range.end > search_start,
10343                        Direction::Next => entry.range.start < search_start,
10344                    };
10345                    is_in_range
10346                        && self
10347                            .active_diagnostics
10348                            .as_ref()
10349                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10350                })
10351                .find_map(|entry| {
10352                    if entry.diagnostic.is_primary
10353                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10354                        && entry.range.start != entry.range.end
10355                        // if we match with the active diagnostic, skip it
10356                        && Some(entry.diagnostic.group_id)
10357                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10358                    {
10359                        Some((entry.range, entry.diagnostic.group_id))
10360                    } else {
10361                        None
10362                    }
10363                });
10364
10365            if let Some((primary_range, group_id)) = group {
10366                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10367                    return;
10368                };
10369                self.activate_diagnostics(buffer_id, group_id, window, cx);
10370                if self.active_diagnostics.is_some() {
10371                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10372                        s.select(vec![Selection {
10373                            id: selection.id,
10374                            start: primary_range.start,
10375                            end: primary_range.start,
10376                            reversed: false,
10377                            goal: SelectionGoal::None,
10378                        }]);
10379                    });
10380                    self.refresh_inline_completion(false, true, window, cx);
10381                }
10382                break;
10383            } else {
10384                // Cycle around to the start of the buffer, potentially moving back to the start of
10385                // the currently active diagnostic.
10386                active_primary_range.take();
10387                if direction == Direction::Prev {
10388                    if search_start == buffer.len() {
10389                        break;
10390                    } else {
10391                        search_start = buffer.len();
10392                    }
10393                } else if search_start == 0 {
10394                    break;
10395                } else {
10396                    search_start = 0;
10397                }
10398            }
10399        }
10400    }
10401
10402    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10403        let snapshot = self.snapshot(window, cx);
10404        let selection = self.selections.newest::<Point>(cx);
10405        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10406    }
10407
10408    fn go_to_hunk_after_position(
10409        &mut self,
10410        snapshot: &EditorSnapshot,
10411        position: Point,
10412        window: &mut Window,
10413        cx: &mut Context<Editor>,
10414    ) -> Option<MultiBufferDiffHunk> {
10415        let mut hunk = snapshot
10416            .buffer_snapshot
10417            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10418            .find(|hunk| hunk.row_range.start.0 > position.row);
10419        if hunk.is_none() {
10420            hunk = snapshot
10421                .buffer_snapshot
10422                .diff_hunks_in_range(Point::zero()..position)
10423                .find(|hunk| hunk.row_range.end.0 < position.row)
10424        }
10425        if let Some(hunk) = &hunk {
10426            let destination = Point::new(hunk.row_range.start.0, 0);
10427            self.unfold_ranges(&[destination..destination], false, false, cx);
10428            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10429                s.select_ranges(vec![destination..destination]);
10430            });
10431        }
10432
10433        hunk
10434    }
10435
10436    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10437        let snapshot = self.snapshot(window, cx);
10438        let selection = self.selections.newest::<Point>(cx);
10439        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10440    }
10441
10442    fn go_to_hunk_before_position(
10443        &mut self,
10444        snapshot: &EditorSnapshot,
10445        position: Point,
10446        window: &mut Window,
10447        cx: &mut Context<Editor>,
10448    ) -> Option<MultiBufferDiffHunk> {
10449        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10450        if hunk.is_none() {
10451            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10452        }
10453        if let Some(hunk) = &hunk {
10454            let destination = Point::new(hunk.row_range.start.0, 0);
10455            self.unfold_ranges(&[destination..destination], false, false, cx);
10456            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457                s.select_ranges(vec![destination..destination]);
10458            });
10459        }
10460
10461        hunk
10462    }
10463
10464    pub fn go_to_definition(
10465        &mut self,
10466        _: &GoToDefinition,
10467        window: &mut Window,
10468        cx: &mut Context<Self>,
10469    ) -> Task<Result<Navigated>> {
10470        let definition =
10471            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10472        cx.spawn_in(window, |editor, mut cx| async move {
10473            if definition.await? == Navigated::Yes {
10474                return Ok(Navigated::Yes);
10475            }
10476            match editor.update_in(&mut cx, |editor, window, cx| {
10477                editor.find_all_references(&FindAllReferences, window, cx)
10478            })? {
10479                Some(references) => references.await,
10480                None => Ok(Navigated::No),
10481            }
10482        })
10483    }
10484
10485    pub fn go_to_declaration(
10486        &mut self,
10487        _: &GoToDeclaration,
10488        window: &mut Window,
10489        cx: &mut Context<Self>,
10490    ) -> Task<Result<Navigated>> {
10491        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10492    }
10493
10494    pub fn go_to_declaration_split(
10495        &mut self,
10496        _: &GoToDeclaration,
10497        window: &mut Window,
10498        cx: &mut Context<Self>,
10499    ) -> Task<Result<Navigated>> {
10500        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10501    }
10502
10503    pub fn go_to_implementation(
10504        &mut self,
10505        _: &GoToImplementation,
10506        window: &mut Window,
10507        cx: &mut Context<Self>,
10508    ) -> Task<Result<Navigated>> {
10509        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10510    }
10511
10512    pub fn go_to_implementation_split(
10513        &mut self,
10514        _: &GoToImplementationSplit,
10515        window: &mut Window,
10516        cx: &mut Context<Self>,
10517    ) -> Task<Result<Navigated>> {
10518        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10519    }
10520
10521    pub fn go_to_type_definition(
10522        &mut self,
10523        _: &GoToTypeDefinition,
10524        window: &mut Window,
10525        cx: &mut Context<Self>,
10526    ) -> Task<Result<Navigated>> {
10527        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10528    }
10529
10530    pub fn go_to_definition_split(
10531        &mut self,
10532        _: &GoToDefinitionSplit,
10533        window: &mut Window,
10534        cx: &mut Context<Self>,
10535    ) -> Task<Result<Navigated>> {
10536        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10537    }
10538
10539    pub fn go_to_type_definition_split(
10540        &mut self,
10541        _: &GoToTypeDefinitionSplit,
10542        window: &mut Window,
10543        cx: &mut Context<Self>,
10544    ) -> Task<Result<Navigated>> {
10545        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10546    }
10547
10548    fn go_to_definition_of_kind(
10549        &mut self,
10550        kind: GotoDefinitionKind,
10551        split: bool,
10552        window: &mut Window,
10553        cx: &mut Context<Self>,
10554    ) -> Task<Result<Navigated>> {
10555        let Some(provider) = self.semantics_provider.clone() else {
10556            return Task::ready(Ok(Navigated::No));
10557        };
10558        let head = self.selections.newest::<usize>(cx).head();
10559        let buffer = self.buffer.read(cx);
10560        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10561            text_anchor
10562        } else {
10563            return Task::ready(Ok(Navigated::No));
10564        };
10565
10566        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10567            return Task::ready(Ok(Navigated::No));
10568        };
10569
10570        cx.spawn_in(window, |editor, mut cx| async move {
10571            let definitions = definitions.await?;
10572            let navigated = editor
10573                .update_in(&mut cx, |editor, window, cx| {
10574                    editor.navigate_to_hover_links(
10575                        Some(kind),
10576                        definitions
10577                            .into_iter()
10578                            .filter(|location| {
10579                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10580                            })
10581                            .map(HoverLink::Text)
10582                            .collect::<Vec<_>>(),
10583                        split,
10584                        window,
10585                        cx,
10586                    )
10587                })?
10588                .await?;
10589            anyhow::Ok(navigated)
10590        })
10591    }
10592
10593    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10594        let selection = self.selections.newest_anchor();
10595        let head = selection.head();
10596        let tail = selection.tail();
10597
10598        let Some((buffer, start_position)) =
10599            self.buffer.read(cx).text_anchor_for_position(head, cx)
10600        else {
10601            return;
10602        };
10603
10604        let end_position = if head != tail {
10605            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10606                return;
10607            };
10608            Some(pos)
10609        } else {
10610            None
10611        };
10612
10613        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10614            let url = if let Some(end_pos) = end_position {
10615                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10616            } else {
10617                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10618            };
10619
10620            if let Some(url) = url {
10621                editor.update(&mut cx, |_, cx| {
10622                    cx.open_url(&url);
10623                })
10624            } else {
10625                Ok(())
10626            }
10627        });
10628
10629        url_finder.detach();
10630    }
10631
10632    pub fn open_selected_filename(
10633        &mut self,
10634        _: &OpenSelectedFilename,
10635        window: &mut Window,
10636        cx: &mut Context<Self>,
10637    ) {
10638        let Some(workspace) = self.workspace() else {
10639            return;
10640        };
10641
10642        let position = self.selections.newest_anchor().head();
10643
10644        let Some((buffer, buffer_position)) =
10645            self.buffer.read(cx).text_anchor_for_position(position, cx)
10646        else {
10647            return;
10648        };
10649
10650        let project = self.project.clone();
10651
10652        cx.spawn_in(window, |_, mut cx| async move {
10653            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10654
10655            if let Some((_, path)) = result {
10656                workspace
10657                    .update_in(&mut cx, |workspace, window, cx| {
10658                        workspace.open_resolved_path(path, window, cx)
10659                    })?
10660                    .await?;
10661            }
10662            anyhow::Ok(())
10663        })
10664        .detach();
10665    }
10666
10667    pub(crate) fn navigate_to_hover_links(
10668        &mut self,
10669        kind: Option<GotoDefinitionKind>,
10670        mut definitions: Vec<HoverLink>,
10671        split: bool,
10672        window: &mut Window,
10673        cx: &mut Context<Editor>,
10674    ) -> Task<Result<Navigated>> {
10675        // If there is one definition, just open it directly
10676        if definitions.len() == 1 {
10677            let definition = definitions.pop().unwrap();
10678
10679            enum TargetTaskResult {
10680                Location(Option<Location>),
10681                AlreadyNavigated,
10682            }
10683
10684            let target_task = match definition {
10685                HoverLink::Text(link) => {
10686                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10687                }
10688                HoverLink::InlayHint(lsp_location, server_id) => {
10689                    let computation =
10690                        self.compute_target_location(lsp_location, server_id, window, cx);
10691                    cx.background_executor().spawn(async move {
10692                        let location = computation.await?;
10693                        Ok(TargetTaskResult::Location(location))
10694                    })
10695                }
10696                HoverLink::Url(url) => {
10697                    cx.open_url(&url);
10698                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10699                }
10700                HoverLink::File(path) => {
10701                    if let Some(workspace) = self.workspace() {
10702                        cx.spawn_in(window, |_, mut cx| async move {
10703                            workspace
10704                                .update_in(&mut cx, |workspace, window, cx| {
10705                                    workspace.open_resolved_path(path, window, cx)
10706                                })?
10707                                .await
10708                                .map(|_| TargetTaskResult::AlreadyNavigated)
10709                        })
10710                    } else {
10711                        Task::ready(Ok(TargetTaskResult::Location(None)))
10712                    }
10713                }
10714            };
10715            cx.spawn_in(window, |editor, mut cx| async move {
10716                let target = match target_task.await.context("target resolution task")? {
10717                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10718                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10719                    TargetTaskResult::Location(Some(target)) => target,
10720                };
10721
10722                editor.update_in(&mut cx, |editor, window, cx| {
10723                    let Some(workspace) = editor.workspace() else {
10724                        return Navigated::No;
10725                    };
10726                    let pane = workspace.read(cx).active_pane().clone();
10727
10728                    let range = target.range.to_point(target.buffer.read(cx));
10729                    let range = editor.range_for_match(&range);
10730                    let range = collapse_multiline_range(range);
10731
10732                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10733                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10734                    } else {
10735                        window.defer(cx, move |window, cx| {
10736                            let target_editor: Entity<Self> =
10737                                workspace.update(cx, |workspace, cx| {
10738                                    let pane = if split {
10739                                        workspace.adjacent_pane(window, cx)
10740                                    } else {
10741                                        workspace.active_pane().clone()
10742                                    };
10743
10744                                    workspace.open_project_item(
10745                                        pane,
10746                                        target.buffer.clone(),
10747                                        true,
10748                                        true,
10749                                        window,
10750                                        cx,
10751                                    )
10752                                });
10753                            target_editor.update(cx, |target_editor, cx| {
10754                                // When selecting a definition in a different buffer, disable the nav history
10755                                // to avoid creating a history entry at the previous cursor location.
10756                                pane.update(cx, |pane, _| pane.disable_history());
10757                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10758                                pane.update(cx, |pane, _| pane.enable_history());
10759                            });
10760                        });
10761                    }
10762                    Navigated::Yes
10763                })
10764            })
10765        } else if !definitions.is_empty() {
10766            cx.spawn_in(window, |editor, mut cx| async move {
10767                let (title, location_tasks, workspace) = editor
10768                    .update_in(&mut cx, |editor, window, cx| {
10769                        let tab_kind = match kind {
10770                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10771                            _ => "Definitions",
10772                        };
10773                        let title = definitions
10774                            .iter()
10775                            .find_map(|definition| match definition {
10776                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10777                                    let buffer = origin.buffer.read(cx);
10778                                    format!(
10779                                        "{} for {}",
10780                                        tab_kind,
10781                                        buffer
10782                                            .text_for_range(origin.range.clone())
10783                                            .collect::<String>()
10784                                    )
10785                                }),
10786                                HoverLink::InlayHint(_, _) => None,
10787                                HoverLink::Url(_) => None,
10788                                HoverLink::File(_) => None,
10789                            })
10790                            .unwrap_or(tab_kind.to_string());
10791                        let location_tasks = definitions
10792                            .into_iter()
10793                            .map(|definition| match definition {
10794                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10795                                HoverLink::InlayHint(lsp_location, server_id) => editor
10796                                    .compute_target_location(lsp_location, server_id, window, cx),
10797                                HoverLink::Url(_) => Task::ready(Ok(None)),
10798                                HoverLink::File(_) => Task::ready(Ok(None)),
10799                            })
10800                            .collect::<Vec<_>>();
10801                        (title, location_tasks, editor.workspace().clone())
10802                    })
10803                    .context("location tasks preparation")?;
10804
10805                let locations = future::join_all(location_tasks)
10806                    .await
10807                    .into_iter()
10808                    .filter_map(|location| location.transpose())
10809                    .collect::<Result<_>>()
10810                    .context("location tasks")?;
10811
10812                let Some(workspace) = workspace else {
10813                    return Ok(Navigated::No);
10814                };
10815                let opened = workspace
10816                    .update_in(&mut cx, |workspace, window, cx| {
10817                        Self::open_locations_in_multibuffer(
10818                            workspace,
10819                            locations,
10820                            title,
10821                            split,
10822                            MultibufferSelectionMode::First,
10823                            window,
10824                            cx,
10825                        )
10826                    })
10827                    .ok();
10828
10829                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10830            })
10831        } else {
10832            Task::ready(Ok(Navigated::No))
10833        }
10834    }
10835
10836    fn compute_target_location(
10837        &self,
10838        lsp_location: lsp::Location,
10839        server_id: LanguageServerId,
10840        window: &mut Window,
10841        cx: &mut Context<Self>,
10842    ) -> Task<anyhow::Result<Option<Location>>> {
10843        let Some(project) = self.project.clone() else {
10844            return Task::ready(Ok(None));
10845        };
10846
10847        cx.spawn_in(window, move |editor, mut cx| async move {
10848            let location_task = editor.update(&mut cx, |_, cx| {
10849                project.update(cx, |project, cx| {
10850                    let language_server_name = project
10851                        .language_server_statuses(cx)
10852                        .find(|(id, _)| server_id == *id)
10853                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10854                    language_server_name.map(|language_server_name| {
10855                        project.open_local_buffer_via_lsp(
10856                            lsp_location.uri.clone(),
10857                            server_id,
10858                            language_server_name,
10859                            cx,
10860                        )
10861                    })
10862                })
10863            })?;
10864            let location = match location_task {
10865                Some(task) => Some({
10866                    let target_buffer_handle = task.await.context("open local buffer")?;
10867                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10868                        let target_start = target_buffer
10869                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10870                        let target_end = target_buffer
10871                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10872                        target_buffer.anchor_after(target_start)
10873                            ..target_buffer.anchor_before(target_end)
10874                    })?;
10875                    Location {
10876                        buffer: target_buffer_handle,
10877                        range,
10878                    }
10879                }),
10880                None => None,
10881            };
10882            Ok(location)
10883        })
10884    }
10885
10886    pub fn find_all_references(
10887        &mut self,
10888        _: &FindAllReferences,
10889        window: &mut Window,
10890        cx: &mut Context<Self>,
10891    ) -> Option<Task<Result<Navigated>>> {
10892        let selection = self.selections.newest::<usize>(cx);
10893        let multi_buffer = self.buffer.read(cx);
10894        let head = selection.head();
10895
10896        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10897        let head_anchor = multi_buffer_snapshot.anchor_at(
10898            head,
10899            if head < selection.tail() {
10900                Bias::Right
10901            } else {
10902                Bias::Left
10903            },
10904        );
10905
10906        match self
10907            .find_all_references_task_sources
10908            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10909        {
10910            Ok(_) => {
10911                log::info!(
10912                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10913                );
10914                return None;
10915            }
10916            Err(i) => {
10917                self.find_all_references_task_sources.insert(i, head_anchor);
10918            }
10919        }
10920
10921        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10922        let workspace = self.workspace()?;
10923        let project = workspace.read(cx).project().clone();
10924        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10925        Some(cx.spawn_in(window, |editor, mut cx| async move {
10926            let _cleanup = defer({
10927                let mut cx = cx.clone();
10928                move || {
10929                    let _ = editor.update(&mut cx, |editor, _| {
10930                        if let Ok(i) =
10931                            editor
10932                                .find_all_references_task_sources
10933                                .binary_search_by(|anchor| {
10934                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10935                                })
10936                        {
10937                            editor.find_all_references_task_sources.remove(i);
10938                        }
10939                    });
10940                }
10941            });
10942
10943            let locations = references.await?;
10944            if locations.is_empty() {
10945                return anyhow::Ok(Navigated::No);
10946            }
10947
10948            workspace.update_in(&mut cx, |workspace, window, cx| {
10949                let title = locations
10950                    .first()
10951                    .as_ref()
10952                    .map(|location| {
10953                        let buffer = location.buffer.read(cx);
10954                        format!(
10955                            "References to `{}`",
10956                            buffer
10957                                .text_for_range(location.range.clone())
10958                                .collect::<String>()
10959                        )
10960                    })
10961                    .unwrap();
10962                Self::open_locations_in_multibuffer(
10963                    workspace,
10964                    locations,
10965                    title,
10966                    false,
10967                    MultibufferSelectionMode::First,
10968                    window,
10969                    cx,
10970                );
10971                Navigated::Yes
10972            })
10973        }))
10974    }
10975
10976    /// Opens a multibuffer with the given project locations in it
10977    pub fn open_locations_in_multibuffer(
10978        workspace: &mut Workspace,
10979        mut locations: Vec<Location>,
10980        title: String,
10981        split: bool,
10982        multibuffer_selection_mode: MultibufferSelectionMode,
10983        window: &mut Window,
10984        cx: &mut Context<Workspace>,
10985    ) {
10986        // If there are multiple definitions, open them in a multibuffer
10987        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10988        let mut locations = locations.into_iter().peekable();
10989        let mut ranges = Vec::new();
10990        let capability = workspace.project().read(cx).capability();
10991
10992        let excerpt_buffer = cx.new(|cx| {
10993            let mut multibuffer = MultiBuffer::new(capability);
10994            while let Some(location) = locations.next() {
10995                let buffer = location.buffer.read(cx);
10996                let mut ranges_for_buffer = Vec::new();
10997                let range = location.range.to_offset(buffer);
10998                ranges_for_buffer.push(range.clone());
10999
11000                while let Some(next_location) = locations.peek() {
11001                    if next_location.buffer == location.buffer {
11002                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11003                        locations.next();
11004                    } else {
11005                        break;
11006                    }
11007                }
11008
11009                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11010                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11011                    location.buffer.clone(),
11012                    ranges_for_buffer,
11013                    DEFAULT_MULTIBUFFER_CONTEXT,
11014                    cx,
11015                ))
11016            }
11017
11018            multibuffer.with_title(title)
11019        });
11020
11021        let editor = cx.new(|cx| {
11022            Editor::for_multibuffer(
11023                excerpt_buffer,
11024                Some(workspace.project().clone()),
11025                true,
11026                window,
11027                cx,
11028            )
11029        });
11030        editor.update(cx, |editor, cx| {
11031            match multibuffer_selection_mode {
11032                MultibufferSelectionMode::First => {
11033                    if let Some(first_range) = ranges.first() {
11034                        editor.change_selections(None, window, cx, |selections| {
11035                            selections.clear_disjoint();
11036                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11037                        });
11038                    }
11039                    editor.highlight_background::<Self>(
11040                        &ranges,
11041                        |theme| theme.editor_highlighted_line_background,
11042                        cx,
11043                    );
11044                }
11045                MultibufferSelectionMode::All => {
11046                    editor.change_selections(None, window, cx, |selections| {
11047                        selections.clear_disjoint();
11048                        selections.select_anchor_ranges(ranges);
11049                    });
11050                }
11051            }
11052            editor.register_buffers_with_language_servers(cx);
11053        });
11054
11055        let item = Box::new(editor);
11056        let item_id = item.item_id();
11057
11058        if split {
11059            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11060        } else {
11061            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11062                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11063                    pane.close_current_preview_item(window, cx)
11064                } else {
11065                    None
11066                }
11067            });
11068            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11069        }
11070        workspace.active_pane().update(cx, |pane, cx| {
11071            pane.set_preview_item_id(Some(item_id), cx);
11072        });
11073    }
11074
11075    pub fn rename(
11076        &mut self,
11077        _: &Rename,
11078        window: &mut Window,
11079        cx: &mut Context<Self>,
11080    ) -> Option<Task<Result<()>>> {
11081        use language::ToOffset as _;
11082
11083        let provider = self.semantics_provider.clone()?;
11084        let selection = self.selections.newest_anchor().clone();
11085        let (cursor_buffer, cursor_buffer_position) = self
11086            .buffer
11087            .read(cx)
11088            .text_anchor_for_position(selection.head(), cx)?;
11089        let (tail_buffer, cursor_buffer_position_end) = self
11090            .buffer
11091            .read(cx)
11092            .text_anchor_for_position(selection.tail(), cx)?;
11093        if tail_buffer != cursor_buffer {
11094            return None;
11095        }
11096
11097        let snapshot = cursor_buffer.read(cx).snapshot();
11098        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11099        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11100        let prepare_rename = provider
11101            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11102            .unwrap_or_else(|| Task::ready(Ok(None)));
11103        drop(snapshot);
11104
11105        Some(cx.spawn_in(window, |this, mut cx| async move {
11106            let rename_range = if let Some(range) = prepare_rename.await? {
11107                Some(range)
11108            } else {
11109                this.update(&mut cx, |this, cx| {
11110                    let buffer = this.buffer.read(cx).snapshot(cx);
11111                    let mut buffer_highlights = this
11112                        .document_highlights_for_position(selection.head(), &buffer)
11113                        .filter(|highlight| {
11114                            highlight.start.excerpt_id == selection.head().excerpt_id
11115                                && highlight.end.excerpt_id == selection.head().excerpt_id
11116                        });
11117                    buffer_highlights
11118                        .next()
11119                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11120                })?
11121            };
11122            if let Some(rename_range) = rename_range {
11123                this.update_in(&mut cx, |this, window, cx| {
11124                    let snapshot = cursor_buffer.read(cx).snapshot();
11125                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11126                    let cursor_offset_in_rename_range =
11127                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11128                    let cursor_offset_in_rename_range_end =
11129                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11130
11131                    this.take_rename(false, window, cx);
11132                    let buffer = this.buffer.read(cx).read(cx);
11133                    let cursor_offset = selection.head().to_offset(&buffer);
11134                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11135                    let rename_end = rename_start + rename_buffer_range.len();
11136                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11137                    let mut old_highlight_id = None;
11138                    let old_name: Arc<str> = buffer
11139                        .chunks(rename_start..rename_end, true)
11140                        .map(|chunk| {
11141                            if old_highlight_id.is_none() {
11142                                old_highlight_id = chunk.syntax_highlight_id;
11143                            }
11144                            chunk.text
11145                        })
11146                        .collect::<String>()
11147                        .into();
11148
11149                    drop(buffer);
11150
11151                    // Position the selection in the rename editor so that it matches the current selection.
11152                    this.show_local_selections = false;
11153                    let rename_editor = cx.new(|cx| {
11154                        let mut editor = Editor::single_line(window, cx);
11155                        editor.buffer.update(cx, |buffer, cx| {
11156                            buffer.edit([(0..0, old_name.clone())], None, cx)
11157                        });
11158                        let rename_selection_range = match cursor_offset_in_rename_range
11159                            .cmp(&cursor_offset_in_rename_range_end)
11160                        {
11161                            Ordering::Equal => {
11162                                editor.select_all(&SelectAll, window, cx);
11163                                return editor;
11164                            }
11165                            Ordering::Less => {
11166                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11167                            }
11168                            Ordering::Greater => {
11169                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11170                            }
11171                        };
11172                        if rename_selection_range.end > old_name.len() {
11173                            editor.select_all(&SelectAll, window, cx);
11174                        } else {
11175                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11176                                s.select_ranges([rename_selection_range]);
11177                            });
11178                        }
11179                        editor
11180                    });
11181                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11182                        if e == &EditorEvent::Focused {
11183                            cx.emit(EditorEvent::FocusedIn)
11184                        }
11185                    })
11186                    .detach();
11187
11188                    let write_highlights =
11189                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11190                    let read_highlights =
11191                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11192                    let ranges = write_highlights
11193                        .iter()
11194                        .flat_map(|(_, ranges)| ranges.iter())
11195                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11196                        .cloned()
11197                        .collect();
11198
11199                    this.highlight_text::<Rename>(
11200                        ranges,
11201                        HighlightStyle {
11202                            fade_out: Some(0.6),
11203                            ..Default::default()
11204                        },
11205                        cx,
11206                    );
11207                    let rename_focus_handle = rename_editor.focus_handle(cx);
11208                    window.focus(&rename_focus_handle);
11209                    let block_id = this.insert_blocks(
11210                        [BlockProperties {
11211                            style: BlockStyle::Flex,
11212                            placement: BlockPlacement::Below(range.start),
11213                            height: 1,
11214                            render: Arc::new({
11215                                let rename_editor = rename_editor.clone();
11216                                move |cx: &mut BlockContext| {
11217                                    let mut text_style = cx.editor_style.text.clone();
11218                                    if let Some(highlight_style) = old_highlight_id
11219                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11220                                    {
11221                                        text_style = text_style.highlight(highlight_style);
11222                                    }
11223                                    div()
11224                                        .block_mouse_down()
11225                                        .pl(cx.anchor_x)
11226                                        .child(EditorElement::new(
11227                                            &rename_editor,
11228                                            EditorStyle {
11229                                                background: cx.theme().system().transparent,
11230                                                local_player: cx.editor_style.local_player,
11231                                                text: text_style,
11232                                                scrollbar_width: cx.editor_style.scrollbar_width,
11233                                                syntax: cx.editor_style.syntax.clone(),
11234                                                status: cx.editor_style.status.clone(),
11235                                                inlay_hints_style: HighlightStyle {
11236                                                    font_weight: Some(FontWeight::BOLD),
11237                                                    ..make_inlay_hints_style(cx.app)
11238                                                },
11239                                                inline_completion_styles: make_suggestion_styles(
11240                                                    cx.app,
11241                                                ),
11242                                                ..EditorStyle::default()
11243                                            },
11244                                        ))
11245                                        .into_any_element()
11246                                }
11247                            }),
11248                            priority: 0,
11249                        }],
11250                        Some(Autoscroll::fit()),
11251                        cx,
11252                    )[0];
11253                    this.pending_rename = Some(RenameState {
11254                        range,
11255                        old_name,
11256                        editor: rename_editor,
11257                        block_id,
11258                    });
11259                })?;
11260            }
11261
11262            Ok(())
11263        }))
11264    }
11265
11266    pub fn confirm_rename(
11267        &mut self,
11268        _: &ConfirmRename,
11269        window: &mut Window,
11270        cx: &mut Context<Self>,
11271    ) -> Option<Task<Result<()>>> {
11272        let rename = self.take_rename(false, window, cx)?;
11273        let workspace = self.workspace()?.downgrade();
11274        let (buffer, start) = self
11275            .buffer
11276            .read(cx)
11277            .text_anchor_for_position(rename.range.start, cx)?;
11278        let (end_buffer, _) = self
11279            .buffer
11280            .read(cx)
11281            .text_anchor_for_position(rename.range.end, cx)?;
11282        if buffer != end_buffer {
11283            return None;
11284        }
11285
11286        let old_name = rename.old_name;
11287        let new_name = rename.editor.read(cx).text(cx);
11288
11289        let rename = self.semantics_provider.as_ref()?.perform_rename(
11290            &buffer,
11291            start,
11292            new_name.clone(),
11293            cx,
11294        )?;
11295
11296        Some(cx.spawn_in(window, |editor, mut cx| async move {
11297            let project_transaction = rename.await?;
11298            Self::open_project_transaction(
11299                &editor,
11300                workspace,
11301                project_transaction,
11302                format!("Rename: {}{}", old_name, new_name),
11303                cx.clone(),
11304            )
11305            .await?;
11306
11307            editor.update(&mut cx, |editor, cx| {
11308                editor.refresh_document_highlights(cx);
11309            })?;
11310            Ok(())
11311        }))
11312    }
11313
11314    fn take_rename(
11315        &mut self,
11316        moving_cursor: bool,
11317        window: &mut Window,
11318        cx: &mut Context<Self>,
11319    ) -> Option<RenameState> {
11320        let rename = self.pending_rename.take()?;
11321        if rename.editor.focus_handle(cx).is_focused(window) {
11322            window.focus(&self.focus_handle);
11323        }
11324
11325        self.remove_blocks(
11326            [rename.block_id].into_iter().collect(),
11327            Some(Autoscroll::fit()),
11328            cx,
11329        );
11330        self.clear_highlights::<Rename>(cx);
11331        self.show_local_selections = true;
11332
11333        if moving_cursor {
11334            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11335                editor.selections.newest::<usize>(cx).head()
11336            });
11337
11338            // Update the selection to match the position of the selection inside
11339            // the rename editor.
11340            let snapshot = self.buffer.read(cx).read(cx);
11341            let rename_range = rename.range.to_offset(&snapshot);
11342            let cursor_in_editor = snapshot
11343                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11344                .min(rename_range.end);
11345            drop(snapshot);
11346
11347            self.change_selections(None, window, cx, |s| {
11348                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11349            });
11350        } else {
11351            self.refresh_document_highlights(cx);
11352        }
11353
11354        Some(rename)
11355    }
11356
11357    pub fn pending_rename(&self) -> Option<&RenameState> {
11358        self.pending_rename.as_ref()
11359    }
11360
11361    fn format(
11362        &mut self,
11363        _: &Format,
11364        window: &mut Window,
11365        cx: &mut Context<Self>,
11366    ) -> Option<Task<Result<()>>> {
11367        let project = match &self.project {
11368            Some(project) => project.clone(),
11369            None => return None,
11370        };
11371
11372        Some(self.perform_format(
11373            project,
11374            FormatTrigger::Manual,
11375            FormatTarget::Buffers,
11376            window,
11377            cx,
11378        ))
11379    }
11380
11381    fn format_selections(
11382        &mut self,
11383        _: &FormatSelections,
11384        window: &mut Window,
11385        cx: &mut Context<Self>,
11386    ) -> Option<Task<Result<()>>> {
11387        let project = match &self.project {
11388            Some(project) => project.clone(),
11389            None => return None,
11390        };
11391
11392        let ranges = self
11393            .selections
11394            .all_adjusted(cx)
11395            .into_iter()
11396            .map(|selection| selection.range())
11397            .collect_vec();
11398
11399        Some(self.perform_format(
11400            project,
11401            FormatTrigger::Manual,
11402            FormatTarget::Ranges(ranges),
11403            window,
11404            cx,
11405        ))
11406    }
11407
11408    fn perform_format(
11409        &mut self,
11410        project: Entity<Project>,
11411        trigger: FormatTrigger,
11412        target: FormatTarget,
11413        window: &mut Window,
11414        cx: &mut Context<Self>,
11415    ) -> Task<Result<()>> {
11416        let buffer = self.buffer.clone();
11417        let (buffers, target) = match target {
11418            FormatTarget::Buffers => {
11419                let mut buffers = buffer.read(cx).all_buffers();
11420                if trigger == FormatTrigger::Save {
11421                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11422                }
11423                (buffers, LspFormatTarget::Buffers)
11424            }
11425            FormatTarget::Ranges(selection_ranges) => {
11426                let multi_buffer = buffer.read(cx);
11427                let snapshot = multi_buffer.read(cx);
11428                let mut buffers = HashSet::default();
11429                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11430                    BTreeMap::new();
11431                for selection_range in selection_ranges {
11432                    for (buffer, buffer_range, _) in
11433                        snapshot.range_to_buffer_ranges(selection_range)
11434                    {
11435                        let buffer_id = buffer.remote_id();
11436                        let start = buffer.anchor_before(buffer_range.start);
11437                        let end = buffer.anchor_after(buffer_range.end);
11438                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11439                        buffer_id_to_ranges
11440                            .entry(buffer_id)
11441                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11442                            .or_insert_with(|| vec![start..end]);
11443                    }
11444                }
11445                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11446            }
11447        };
11448
11449        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11450        let format = project.update(cx, |project, cx| {
11451            project.format(buffers, target, true, trigger, cx)
11452        });
11453
11454        cx.spawn_in(window, |_, mut cx| async move {
11455            let transaction = futures::select_biased! {
11456                () = timeout => {
11457                    log::warn!("timed out waiting for formatting");
11458                    None
11459                }
11460                transaction = format.log_err().fuse() => transaction,
11461            };
11462
11463            buffer
11464                .update(&mut cx, |buffer, cx| {
11465                    if let Some(transaction) = transaction {
11466                        if !buffer.is_singleton() {
11467                            buffer.push_transaction(&transaction.0, cx);
11468                        }
11469                    }
11470
11471                    cx.notify();
11472                })
11473                .ok();
11474
11475            Ok(())
11476        })
11477    }
11478
11479    fn restart_language_server(
11480        &mut self,
11481        _: &RestartLanguageServer,
11482        _: &mut Window,
11483        cx: &mut Context<Self>,
11484    ) {
11485        if let Some(project) = self.project.clone() {
11486            self.buffer.update(cx, |multi_buffer, cx| {
11487                project.update(cx, |project, cx| {
11488                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11489                });
11490            })
11491        }
11492    }
11493
11494    fn cancel_language_server_work(
11495        workspace: &mut Workspace,
11496        _: &actions::CancelLanguageServerWork,
11497        _: &mut Window,
11498        cx: &mut Context<Workspace>,
11499    ) {
11500        let project = workspace.project();
11501        let buffers = workspace
11502            .active_item(cx)
11503            .and_then(|item| item.act_as::<Editor>(cx))
11504            .map_or(HashSet::default(), |editor| {
11505                editor.read(cx).buffer.read(cx).all_buffers()
11506            });
11507        project.update(cx, |project, cx| {
11508            project.cancel_language_server_work_for_buffers(buffers, cx);
11509        });
11510    }
11511
11512    fn show_character_palette(
11513        &mut self,
11514        _: &ShowCharacterPalette,
11515        window: &mut Window,
11516        _: &mut Context<Self>,
11517    ) {
11518        window.show_character_palette();
11519    }
11520
11521    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11522        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11523            let buffer = self.buffer.read(cx).snapshot(cx);
11524            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11525            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11526            let is_valid = buffer
11527                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11528                .any(|entry| {
11529                    entry.diagnostic.is_primary
11530                        && !entry.range.is_empty()
11531                        && entry.range.start == primary_range_start
11532                        && entry.diagnostic.message == active_diagnostics.primary_message
11533                });
11534
11535            if is_valid != active_diagnostics.is_valid {
11536                active_diagnostics.is_valid = is_valid;
11537                let mut new_styles = HashMap::default();
11538                for (block_id, diagnostic) in &active_diagnostics.blocks {
11539                    new_styles.insert(
11540                        *block_id,
11541                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11542                    );
11543                }
11544                self.display_map.update(cx, |display_map, _cx| {
11545                    display_map.replace_blocks(new_styles)
11546                });
11547            }
11548        }
11549    }
11550
11551    fn activate_diagnostics(
11552        &mut self,
11553        buffer_id: BufferId,
11554        group_id: usize,
11555        window: &mut Window,
11556        cx: &mut Context<Self>,
11557    ) {
11558        self.dismiss_diagnostics(cx);
11559        let snapshot = self.snapshot(window, cx);
11560        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11561            let buffer = self.buffer.read(cx).snapshot(cx);
11562
11563            let mut primary_range = None;
11564            let mut primary_message = None;
11565            let diagnostic_group = buffer
11566                .diagnostic_group(buffer_id, group_id)
11567                .filter_map(|entry| {
11568                    let start = entry.range.start;
11569                    let end = entry.range.end;
11570                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11571                        && (start.row == end.row
11572                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11573                    {
11574                        return None;
11575                    }
11576                    if entry.diagnostic.is_primary {
11577                        primary_range = Some(entry.range.clone());
11578                        primary_message = Some(entry.diagnostic.message.clone());
11579                    }
11580                    Some(entry)
11581                })
11582                .collect::<Vec<_>>();
11583            let primary_range = primary_range?;
11584            let primary_message = primary_message?;
11585
11586            let blocks = display_map
11587                .insert_blocks(
11588                    diagnostic_group.iter().map(|entry| {
11589                        let diagnostic = entry.diagnostic.clone();
11590                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11591                        BlockProperties {
11592                            style: BlockStyle::Fixed,
11593                            placement: BlockPlacement::Below(
11594                                buffer.anchor_after(entry.range.start),
11595                            ),
11596                            height: message_height,
11597                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11598                            priority: 0,
11599                        }
11600                    }),
11601                    cx,
11602                )
11603                .into_iter()
11604                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11605                .collect();
11606
11607            Some(ActiveDiagnosticGroup {
11608                primary_range: buffer.anchor_before(primary_range.start)
11609                    ..buffer.anchor_after(primary_range.end),
11610                primary_message,
11611                group_id,
11612                blocks,
11613                is_valid: true,
11614            })
11615        });
11616    }
11617
11618    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11619        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11620            self.display_map.update(cx, |display_map, cx| {
11621                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11622            });
11623            cx.notify();
11624        }
11625    }
11626
11627    pub fn set_selections_from_remote(
11628        &mut self,
11629        selections: Vec<Selection<Anchor>>,
11630        pending_selection: Option<Selection<Anchor>>,
11631        window: &mut Window,
11632        cx: &mut Context<Self>,
11633    ) {
11634        let old_cursor_position = self.selections.newest_anchor().head();
11635        self.selections.change_with(cx, |s| {
11636            s.select_anchors(selections);
11637            if let Some(pending_selection) = pending_selection {
11638                s.set_pending(pending_selection, SelectMode::Character);
11639            } else {
11640                s.clear_pending();
11641            }
11642        });
11643        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11644    }
11645
11646    fn push_to_selection_history(&mut self) {
11647        self.selection_history.push(SelectionHistoryEntry {
11648            selections: self.selections.disjoint_anchors(),
11649            select_next_state: self.select_next_state.clone(),
11650            select_prev_state: self.select_prev_state.clone(),
11651            add_selections_state: self.add_selections_state.clone(),
11652        });
11653    }
11654
11655    pub fn transact(
11656        &mut self,
11657        window: &mut Window,
11658        cx: &mut Context<Self>,
11659        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11660    ) -> Option<TransactionId> {
11661        self.start_transaction_at(Instant::now(), window, cx);
11662        update(self, window, cx);
11663        self.end_transaction_at(Instant::now(), cx)
11664    }
11665
11666    pub fn start_transaction_at(
11667        &mut self,
11668        now: Instant,
11669        window: &mut Window,
11670        cx: &mut Context<Self>,
11671    ) {
11672        self.end_selection(window, cx);
11673        if let Some(tx_id) = self
11674            .buffer
11675            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11676        {
11677            self.selection_history
11678                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11679            cx.emit(EditorEvent::TransactionBegun {
11680                transaction_id: tx_id,
11681            })
11682        }
11683    }
11684
11685    pub fn end_transaction_at(
11686        &mut self,
11687        now: Instant,
11688        cx: &mut Context<Self>,
11689    ) -> Option<TransactionId> {
11690        if let Some(transaction_id) = self
11691            .buffer
11692            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11693        {
11694            if let Some((_, end_selections)) =
11695                self.selection_history.transaction_mut(transaction_id)
11696            {
11697                *end_selections = Some(self.selections.disjoint_anchors());
11698            } else {
11699                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11700            }
11701
11702            cx.emit(EditorEvent::Edited { transaction_id });
11703            Some(transaction_id)
11704        } else {
11705            None
11706        }
11707    }
11708
11709    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11710        if self.selection_mark_mode {
11711            self.change_selections(None, window, cx, |s| {
11712                s.move_with(|_, sel| {
11713                    sel.collapse_to(sel.head(), SelectionGoal::None);
11714                });
11715            })
11716        }
11717        self.selection_mark_mode = true;
11718        cx.notify();
11719    }
11720
11721    pub fn swap_selection_ends(
11722        &mut self,
11723        _: &actions::SwapSelectionEnds,
11724        window: &mut Window,
11725        cx: &mut Context<Self>,
11726    ) {
11727        self.change_selections(None, window, cx, |s| {
11728            s.move_with(|_, sel| {
11729                if sel.start != sel.end {
11730                    sel.reversed = !sel.reversed
11731                }
11732            });
11733        });
11734        self.request_autoscroll(Autoscroll::newest(), cx);
11735        cx.notify();
11736    }
11737
11738    pub fn toggle_fold(
11739        &mut self,
11740        _: &actions::ToggleFold,
11741        window: &mut Window,
11742        cx: &mut Context<Self>,
11743    ) {
11744        if self.is_singleton(cx) {
11745            let selection = self.selections.newest::<Point>(cx);
11746
11747            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11748            let range = if selection.is_empty() {
11749                let point = selection.head().to_display_point(&display_map);
11750                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11751                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11752                    .to_point(&display_map);
11753                start..end
11754            } else {
11755                selection.range()
11756            };
11757            if display_map.folds_in_range(range).next().is_some() {
11758                self.unfold_lines(&Default::default(), window, cx)
11759            } else {
11760                self.fold(&Default::default(), window, cx)
11761            }
11762        } else {
11763            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11764            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11765                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11766                .map(|(snapshot, _, _)| snapshot.remote_id())
11767                .collect();
11768
11769            for buffer_id in buffer_ids {
11770                if self.is_buffer_folded(buffer_id, cx) {
11771                    self.unfold_buffer(buffer_id, cx);
11772                } else {
11773                    self.fold_buffer(buffer_id, cx);
11774                }
11775            }
11776        }
11777    }
11778
11779    pub fn toggle_fold_recursive(
11780        &mut self,
11781        _: &actions::ToggleFoldRecursive,
11782        window: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        let selection = self.selections.newest::<Point>(cx);
11786
11787        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11788        let range = if selection.is_empty() {
11789            let point = selection.head().to_display_point(&display_map);
11790            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11791            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11792                .to_point(&display_map);
11793            start..end
11794        } else {
11795            selection.range()
11796        };
11797        if display_map.folds_in_range(range).next().is_some() {
11798            self.unfold_recursive(&Default::default(), window, cx)
11799        } else {
11800            self.fold_recursive(&Default::default(), window, cx)
11801        }
11802    }
11803
11804    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11805        if self.is_singleton(cx) {
11806            let mut to_fold = Vec::new();
11807            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11808            let selections = self.selections.all_adjusted(cx);
11809
11810            for selection in selections {
11811                let range = selection.range().sorted();
11812                let buffer_start_row = range.start.row;
11813
11814                if range.start.row != range.end.row {
11815                    let mut found = false;
11816                    let mut row = range.start.row;
11817                    while row <= range.end.row {
11818                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11819                        {
11820                            found = true;
11821                            row = crease.range().end.row + 1;
11822                            to_fold.push(crease);
11823                        } else {
11824                            row += 1
11825                        }
11826                    }
11827                    if found {
11828                        continue;
11829                    }
11830                }
11831
11832                for row in (0..=range.start.row).rev() {
11833                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11834                        if crease.range().end.row >= buffer_start_row {
11835                            to_fold.push(crease);
11836                            if row <= range.start.row {
11837                                break;
11838                            }
11839                        }
11840                    }
11841                }
11842            }
11843
11844            self.fold_creases(to_fold, true, window, cx);
11845        } else {
11846            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11847
11848            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11849                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11850                .map(|(snapshot, _, _)| snapshot.remote_id())
11851                .collect();
11852            for buffer_id in buffer_ids {
11853                self.fold_buffer(buffer_id, cx);
11854            }
11855        }
11856    }
11857
11858    fn fold_at_level(
11859        &mut self,
11860        fold_at: &FoldAtLevel,
11861        window: &mut Window,
11862        cx: &mut Context<Self>,
11863    ) {
11864        if !self.buffer.read(cx).is_singleton() {
11865            return;
11866        }
11867
11868        let fold_at_level = fold_at.0;
11869        let snapshot = self.buffer.read(cx).snapshot(cx);
11870        let mut to_fold = Vec::new();
11871        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11872
11873        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11874            while start_row < end_row {
11875                match self
11876                    .snapshot(window, cx)
11877                    .crease_for_buffer_row(MultiBufferRow(start_row))
11878                {
11879                    Some(crease) => {
11880                        let nested_start_row = crease.range().start.row + 1;
11881                        let nested_end_row = crease.range().end.row;
11882
11883                        if current_level < fold_at_level {
11884                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11885                        } else if current_level == fold_at_level {
11886                            to_fold.push(crease);
11887                        }
11888
11889                        start_row = nested_end_row + 1;
11890                    }
11891                    None => start_row += 1,
11892                }
11893            }
11894        }
11895
11896        self.fold_creases(to_fold, true, window, cx);
11897    }
11898
11899    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11900        if self.buffer.read(cx).is_singleton() {
11901            let mut fold_ranges = Vec::new();
11902            let snapshot = self.buffer.read(cx).snapshot(cx);
11903
11904            for row in 0..snapshot.max_row().0 {
11905                if let Some(foldable_range) = self
11906                    .snapshot(window, cx)
11907                    .crease_for_buffer_row(MultiBufferRow(row))
11908                {
11909                    fold_ranges.push(foldable_range);
11910                }
11911            }
11912
11913            self.fold_creases(fold_ranges, true, window, cx);
11914        } else {
11915            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11916                editor
11917                    .update_in(&mut cx, |editor, _, cx| {
11918                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11919                            editor.fold_buffer(buffer_id, cx);
11920                        }
11921                    })
11922                    .ok();
11923            });
11924        }
11925    }
11926
11927    pub fn fold_function_bodies(
11928        &mut self,
11929        _: &actions::FoldFunctionBodies,
11930        window: &mut Window,
11931        cx: &mut Context<Self>,
11932    ) {
11933        let snapshot = self.buffer.read(cx).snapshot(cx);
11934
11935        let ranges = snapshot
11936            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11937            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11938            .collect::<Vec<_>>();
11939
11940        let creases = ranges
11941            .into_iter()
11942            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11943            .collect();
11944
11945        self.fold_creases(creases, true, window, cx);
11946    }
11947
11948    pub fn fold_recursive(
11949        &mut self,
11950        _: &actions::FoldRecursive,
11951        window: &mut Window,
11952        cx: &mut Context<Self>,
11953    ) {
11954        let mut to_fold = Vec::new();
11955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11956        let selections = self.selections.all_adjusted(cx);
11957
11958        for selection in selections {
11959            let range = selection.range().sorted();
11960            let buffer_start_row = range.start.row;
11961
11962            if range.start.row != range.end.row {
11963                let mut found = false;
11964                for row in range.start.row..=range.end.row {
11965                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11966                        found = true;
11967                        to_fold.push(crease);
11968                    }
11969                }
11970                if found {
11971                    continue;
11972                }
11973            }
11974
11975            for row in (0..=range.start.row).rev() {
11976                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11977                    if crease.range().end.row >= buffer_start_row {
11978                        to_fold.push(crease);
11979                    } else {
11980                        break;
11981                    }
11982                }
11983            }
11984        }
11985
11986        self.fold_creases(to_fold, true, window, cx);
11987    }
11988
11989    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11990        let buffer_row = fold_at.buffer_row;
11991        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11992
11993        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11994            let autoscroll = self
11995                .selections
11996                .all::<Point>(cx)
11997                .iter()
11998                .any(|selection| crease.range().overlaps(&selection.range()));
11999
12000            self.fold_creases(vec![crease], autoscroll, window, cx);
12001        }
12002    }
12003
12004    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12005        if self.is_singleton(cx) {
12006            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12007            let buffer = &display_map.buffer_snapshot;
12008            let selections = self.selections.all::<Point>(cx);
12009            let ranges = selections
12010                .iter()
12011                .map(|s| {
12012                    let range = s.display_range(&display_map).sorted();
12013                    let mut start = range.start.to_point(&display_map);
12014                    let mut end = range.end.to_point(&display_map);
12015                    start.column = 0;
12016                    end.column = buffer.line_len(MultiBufferRow(end.row));
12017                    start..end
12018                })
12019                .collect::<Vec<_>>();
12020
12021            self.unfold_ranges(&ranges, true, true, cx);
12022        } else {
12023            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12024            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12025                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12026                .map(|(snapshot, _, _)| snapshot.remote_id())
12027                .collect();
12028            for buffer_id in buffer_ids {
12029                self.unfold_buffer(buffer_id, cx);
12030            }
12031        }
12032    }
12033
12034    pub fn unfold_recursive(
12035        &mut self,
12036        _: &UnfoldRecursive,
12037        _window: &mut Window,
12038        cx: &mut Context<Self>,
12039    ) {
12040        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12041        let selections = self.selections.all::<Point>(cx);
12042        let ranges = selections
12043            .iter()
12044            .map(|s| {
12045                let mut range = s.display_range(&display_map).sorted();
12046                *range.start.column_mut() = 0;
12047                *range.end.column_mut() = display_map.line_len(range.end.row());
12048                let start = range.start.to_point(&display_map);
12049                let end = range.end.to_point(&display_map);
12050                start..end
12051            })
12052            .collect::<Vec<_>>();
12053
12054        self.unfold_ranges(&ranges, true, true, cx);
12055    }
12056
12057    pub fn unfold_at(
12058        &mut self,
12059        unfold_at: &UnfoldAt,
12060        _window: &mut Window,
12061        cx: &mut Context<Self>,
12062    ) {
12063        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12064
12065        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12066            ..Point::new(
12067                unfold_at.buffer_row.0,
12068                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12069            );
12070
12071        let autoscroll = self
12072            .selections
12073            .all::<Point>(cx)
12074            .iter()
12075            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12076
12077        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12078    }
12079
12080    pub fn unfold_all(
12081        &mut self,
12082        _: &actions::UnfoldAll,
12083        _window: &mut Window,
12084        cx: &mut Context<Self>,
12085    ) {
12086        if self.buffer.read(cx).is_singleton() {
12087            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12088            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12089        } else {
12090            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12091                editor
12092                    .update(&mut cx, |editor, cx| {
12093                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12094                            editor.unfold_buffer(buffer_id, cx);
12095                        }
12096                    })
12097                    .ok();
12098            });
12099        }
12100    }
12101
12102    pub fn fold_selected_ranges(
12103        &mut self,
12104        _: &FoldSelectedRanges,
12105        window: &mut Window,
12106        cx: &mut Context<Self>,
12107    ) {
12108        let selections = self.selections.all::<Point>(cx);
12109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12110        let line_mode = self.selections.line_mode;
12111        let ranges = selections
12112            .into_iter()
12113            .map(|s| {
12114                if line_mode {
12115                    let start = Point::new(s.start.row, 0);
12116                    let end = Point::new(
12117                        s.end.row,
12118                        display_map
12119                            .buffer_snapshot
12120                            .line_len(MultiBufferRow(s.end.row)),
12121                    );
12122                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12123                } else {
12124                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12125                }
12126            })
12127            .collect::<Vec<_>>();
12128        self.fold_creases(ranges, true, window, cx);
12129    }
12130
12131    pub fn fold_ranges<T: ToOffset + Clone>(
12132        &mut self,
12133        ranges: Vec<Range<T>>,
12134        auto_scroll: bool,
12135        window: &mut Window,
12136        cx: &mut Context<Self>,
12137    ) {
12138        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12139        let ranges = ranges
12140            .into_iter()
12141            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12142            .collect::<Vec<_>>();
12143        self.fold_creases(ranges, auto_scroll, window, cx);
12144    }
12145
12146    pub fn fold_creases<T: ToOffset + Clone>(
12147        &mut self,
12148        creases: Vec<Crease<T>>,
12149        auto_scroll: bool,
12150        window: &mut Window,
12151        cx: &mut Context<Self>,
12152    ) {
12153        if creases.is_empty() {
12154            return;
12155        }
12156
12157        let mut buffers_affected = HashSet::default();
12158        let multi_buffer = self.buffer().read(cx);
12159        for crease in &creases {
12160            if let Some((_, buffer, _)) =
12161                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12162            {
12163                buffers_affected.insert(buffer.read(cx).remote_id());
12164            };
12165        }
12166
12167        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12168
12169        if auto_scroll {
12170            self.request_autoscroll(Autoscroll::fit(), cx);
12171        }
12172
12173        cx.notify();
12174
12175        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12176            // Clear diagnostics block when folding a range that contains it.
12177            let snapshot = self.snapshot(window, cx);
12178            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12179                drop(snapshot);
12180                self.active_diagnostics = Some(active_diagnostics);
12181                self.dismiss_diagnostics(cx);
12182            } else {
12183                self.active_diagnostics = Some(active_diagnostics);
12184            }
12185        }
12186
12187        self.scrollbar_marker_state.dirty = true;
12188    }
12189
12190    /// Removes any folds whose ranges intersect any of the given ranges.
12191    pub fn unfold_ranges<T: ToOffset + Clone>(
12192        &mut self,
12193        ranges: &[Range<T>],
12194        inclusive: bool,
12195        auto_scroll: bool,
12196        cx: &mut Context<Self>,
12197    ) {
12198        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12199            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12200        });
12201    }
12202
12203    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12204        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12205            return;
12206        }
12207        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12208        self.display_map
12209            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12210        cx.emit(EditorEvent::BufferFoldToggled {
12211            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12212            folded: true,
12213        });
12214        cx.notify();
12215    }
12216
12217    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12218        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12219            return;
12220        }
12221        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12222        self.display_map.update(cx, |display_map, cx| {
12223            display_map.unfold_buffer(buffer_id, cx);
12224        });
12225        cx.emit(EditorEvent::BufferFoldToggled {
12226            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12227            folded: false,
12228        });
12229        cx.notify();
12230    }
12231
12232    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12233        self.display_map.read(cx).is_buffer_folded(buffer)
12234    }
12235
12236    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12237        self.display_map.read(cx).folded_buffers()
12238    }
12239
12240    /// Removes any folds with the given ranges.
12241    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12242        &mut self,
12243        ranges: &[Range<T>],
12244        type_id: TypeId,
12245        auto_scroll: bool,
12246        cx: &mut Context<Self>,
12247    ) {
12248        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12249            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12250        });
12251    }
12252
12253    fn remove_folds_with<T: ToOffset + Clone>(
12254        &mut self,
12255        ranges: &[Range<T>],
12256        auto_scroll: bool,
12257        cx: &mut Context<Self>,
12258        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12259    ) {
12260        if ranges.is_empty() {
12261            return;
12262        }
12263
12264        let mut buffers_affected = HashSet::default();
12265        let multi_buffer = self.buffer().read(cx);
12266        for range in ranges {
12267            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12268                buffers_affected.insert(buffer.read(cx).remote_id());
12269            };
12270        }
12271
12272        self.display_map.update(cx, update);
12273
12274        if auto_scroll {
12275            self.request_autoscroll(Autoscroll::fit(), cx);
12276        }
12277
12278        cx.notify();
12279        self.scrollbar_marker_state.dirty = true;
12280        self.active_indent_guides_state.dirty = true;
12281    }
12282
12283    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12284        self.display_map.read(cx).fold_placeholder.clone()
12285    }
12286
12287    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12288        self.buffer.update(cx, |buffer, cx| {
12289            buffer.set_all_diff_hunks_expanded(cx);
12290        });
12291    }
12292
12293    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12294        self.distinguish_unstaged_diff_hunks = true;
12295    }
12296
12297    pub fn expand_all_diff_hunks(
12298        &mut self,
12299        _: &ExpandAllHunkDiffs,
12300        _window: &mut Window,
12301        cx: &mut Context<Self>,
12302    ) {
12303        self.buffer.update(cx, |buffer, cx| {
12304            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12305        });
12306    }
12307
12308    pub fn toggle_selected_diff_hunks(
12309        &mut self,
12310        _: &ToggleSelectedDiffHunks,
12311        _window: &mut Window,
12312        cx: &mut Context<Self>,
12313    ) {
12314        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12315        self.toggle_diff_hunks_in_ranges(ranges, cx);
12316    }
12317
12318    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12319        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12320        self.buffer
12321            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12322    }
12323
12324    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12325        self.buffer.update(cx, |buffer, cx| {
12326            let ranges = vec![Anchor::min()..Anchor::max()];
12327            if !buffer.all_diff_hunks_expanded()
12328                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12329            {
12330                buffer.collapse_diff_hunks(ranges, cx);
12331                true
12332            } else {
12333                false
12334            }
12335        })
12336    }
12337
12338    fn toggle_diff_hunks_in_ranges(
12339        &mut self,
12340        ranges: Vec<Range<Anchor>>,
12341        cx: &mut Context<'_, Editor>,
12342    ) {
12343        self.buffer.update(cx, |buffer, cx| {
12344            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12345            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12346        })
12347    }
12348
12349    fn toggle_diff_hunks_in_ranges_narrow(
12350        &mut self,
12351        ranges: Vec<Range<Anchor>>,
12352        cx: &mut Context<'_, Editor>,
12353    ) {
12354        self.buffer.update(cx, |buffer, cx| {
12355            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12356            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12357        })
12358    }
12359
12360    pub(crate) fn apply_all_diff_hunks(
12361        &mut self,
12362        _: &ApplyAllDiffHunks,
12363        window: &mut Window,
12364        cx: &mut Context<Self>,
12365    ) {
12366        let buffers = self.buffer.read(cx).all_buffers();
12367        for branch_buffer in buffers {
12368            branch_buffer.update(cx, |branch_buffer, cx| {
12369                branch_buffer.merge_into_base(Vec::new(), cx);
12370            });
12371        }
12372
12373        if let Some(project) = self.project.clone() {
12374            self.save(true, project, window, cx).detach_and_log_err(cx);
12375        }
12376    }
12377
12378    pub(crate) fn apply_selected_diff_hunks(
12379        &mut self,
12380        _: &ApplyDiffHunk,
12381        window: &mut Window,
12382        cx: &mut Context<Self>,
12383    ) {
12384        let snapshot = self.snapshot(window, cx);
12385        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12386        let mut ranges_by_buffer = HashMap::default();
12387        self.transact(window, cx, |editor, _window, cx| {
12388            for hunk in hunks {
12389                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12390                    ranges_by_buffer
12391                        .entry(buffer.clone())
12392                        .or_insert_with(Vec::new)
12393                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12394                }
12395            }
12396
12397            for (buffer, ranges) in ranges_by_buffer {
12398                buffer.update(cx, |buffer, cx| {
12399                    buffer.merge_into_base(ranges, cx);
12400                });
12401            }
12402        });
12403
12404        if let Some(project) = self.project.clone() {
12405            self.save(true, project, window, cx).detach_and_log_err(cx);
12406        }
12407    }
12408
12409    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12410        if hovered != self.gutter_hovered {
12411            self.gutter_hovered = hovered;
12412            cx.notify();
12413        }
12414    }
12415
12416    pub fn insert_blocks(
12417        &mut self,
12418        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12419        autoscroll: Option<Autoscroll>,
12420        cx: &mut Context<Self>,
12421    ) -> Vec<CustomBlockId> {
12422        let blocks = self
12423            .display_map
12424            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12425        if let Some(autoscroll) = autoscroll {
12426            self.request_autoscroll(autoscroll, cx);
12427        }
12428        cx.notify();
12429        blocks
12430    }
12431
12432    pub fn resize_blocks(
12433        &mut self,
12434        heights: HashMap<CustomBlockId, u32>,
12435        autoscroll: Option<Autoscroll>,
12436        cx: &mut Context<Self>,
12437    ) {
12438        self.display_map
12439            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12440        if let Some(autoscroll) = autoscroll {
12441            self.request_autoscroll(autoscroll, cx);
12442        }
12443        cx.notify();
12444    }
12445
12446    pub fn replace_blocks(
12447        &mut self,
12448        renderers: HashMap<CustomBlockId, RenderBlock>,
12449        autoscroll: Option<Autoscroll>,
12450        cx: &mut Context<Self>,
12451    ) {
12452        self.display_map
12453            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12454        if let Some(autoscroll) = autoscroll {
12455            self.request_autoscroll(autoscroll, cx);
12456        }
12457        cx.notify();
12458    }
12459
12460    pub fn remove_blocks(
12461        &mut self,
12462        block_ids: HashSet<CustomBlockId>,
12463        autoscroll: Option<Autoscroll>,
12464        cx: &mut Context<Self>,
12465    ) {
12466        self.display_map.update(cx, |display_map, cx| {
12467            display_map.remove_blocks(block_ids, cx)
12468        });
12469        if let Some(autoscroll) = autoscroll {
12470            self.request_autoscroll(autoscroll, cx);
12471        }
12472        cx.notify();
12473    }
12474
12475    pub fn row_for_block(
12476        &self,
12477        block_id: CustomBlockId,
12478        cx: &mut Context<Self>,
12479    ) -> Option<DisplayRow> {
12480        self.display_map
12481            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12482    }
12483
12484    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12485        self.focused_block = Some(focused_block);
12486    }
12487
12488    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12489        self.focused_block.take()
12490    }
12491
12492    pub fn insert_creases(
12493        &mut self,
12494        creases: impl IntoIterator<Item = Crease<Anchor>>,
12495        cx: &mut Context<Self>,
12496    ) -> Vec<CreaseId> {
12497        self.display_map
12498            .update(cx, |map, cx| map.insert_creases(creases, cx))
12499    }
12500
12501    pub fn remove_creases(
12502        &mut self,
12503        ids: impl IntoIterator<Item = CreaseId>,
12504        cx: &mut Context<Self>,
12505    ) {
12506        self.display_map
12507            .update(cx, |map, cx| map.remove_creases(ids, cx));
12508    }
12509
12510    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12511        self.display_map
12512            .update(cx, |map, cx| map.snapshot(cx))
12513            .longest_row()
12514    }
12515
12516    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12517        self.display_map
12518            .update(cx, |map, cx| map.snapshot(cx))
12519            .max_point()
12520    }
12521
12522    pub fn text(&self, cx: &App) -> String {
12523        self.buffer.read(cx).read(cx).text()
12524    }
12525
12526    pub fn is_empty(&self, cx: &App) -> bool {
12527        self.buffer.read(cx).read(cx).is_empty()
12528    }
12529
12530    pub fn text_option(&self, cx: &App) -> Option<String> {
12531        let text = self.text(cx);
12532        let text = text.trim();
12533
12534        if text.is_empty() {
12535            return None;
12536        }
12537
12538        Some(text.to_string())
12539    }
12540
12541    pub fn set_text(
12542        &mut self,
12543        text: impl Into<Arc<str>>,
12544        window: &mut Window,
12545        cx: &mut Context<Self>,
12546    ) {
12547        self.transact(window, cx, |this, _, cx| {
12548            this.buffer
12549                .read(cx)
12550                .as_singleton()
12551                .expect("you can only call set_text on editors for singleton buffers")
12552                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12553        });
12554    }
12555
12556    pub fn display_text(&self, cx: &mut App) -> String {
12557        self.display_map
12558            .update(cx, |map, cx| map.snapshot(cx))
12559            .text()
12560    }
12561
12562    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12563        let mut wrap_guides = smallvec::smallvec![];
12564
12565        if self.show_wrap_guides == Some(false) {
12566            return wrap_guides;
12567        }
12568
12569        let settings = self.buffer.read(cx).settings_at(0, cx);
12570        if settings.show_wrap_guides {
12571            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12572                wrap_guides.push((soft_wrap as usize, true));
12573            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12574                wrap_guides.push((soft_wrap as usize, true));
12575            }
12576            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12577        }
12578
12579        wrap_guides
12580    }
12581
12582    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12583        let settings = self.buffer.read(cx).settings_at(0, cx);
12584        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12585        match mode {
12586            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12587                SoftWrap::None
12588            }
12589            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12590            language_settings::SoftWrap::PreferredLineLength => {
12591                SoftWrap::Column(settings.preferred_line_length)
12592            }
12593            language_settings::SoftWrap::Bounded => {
12594                SoftWrap::Bounded(settings.preferred_line_length)
12595            }
12596        }
12597    }
12598
12599    pub fn set_soft_wrap_mode(
12600        &mut self,
12601        mode: language_settings::SoftWrap,
12602
12603        cx: &mut Context<Self>,
12604    ) {
12605        self.soft_wrap_mode_override = Some(mode);
12606        cx.notify();
12607    }
12608
12609    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12610        self.text_style_refinement = Some(style);
12611    }
12612
12613    /// called by the Element so we know what style we were most recently rendered with.
12614    pub(crate) fn set_style(
12615        &mut self,
12616        style: EditorStyle,
12617        window: &mut Window,
12618        cx: &mut Context<Self>,
12619    ) {
12620        let rem_size = window.rem_size();
12621        self.display_map.update(cx, |map, cx| {
12622            map.set_font(
12623                style.text.font(),
12624                style.text.font_size.to_pixels(rem_size),
12625                cx,
12626            )
12627        });
12628        self.style = Some(style);
12629    }
12630
12631    pub fn style(&self) -> Option<&EditorStyle> {
12632        self.style.as_ref()
12633    }
12634
12635    // Called by the element. This method is not designed to be called outside of the editor
12636    // element's layout code because it does not notify when rewrapping is computed synchronously.
12637    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12638        self.display_map
12639            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12640    }
12641
12642    pub fn set_soft_wrap(&mut self) {
12643        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12644    }
12645
12646    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12647        if self.soft_wrap_mode_override.is_some() {
12648            self.soft_wrap_mode_override.take();
12649        } else {
12650            let soft_wrap = match self.soft_wrap_mode(cx) {
12651                SoftWrap::GitDiff => return,
12652                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12653                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12654                    language_settings::SoftWrap::None
12655                }
12656            };
12657            self.soft_wrap_mode_override = Some(soft_wrap);
12658        }
12659        cx.notify();
12660    }
12661
12662    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12663        let Some(workspace) = self.workspace() else {
12664            return;
12665        };
12666        let fs = workspace.read(cx).app_state().fs.clone();
12667        let current_show = TabBarSettings::get_global(cx).show;
12668        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12669            setting.show = Some(!current_show);
12670        });
12671    }
12672
12673    pub fn toggle_indent_guides(
12674        &mut self,
12675        _: &ToggleIndentGuides,
12676        _: &mut Window,
12677        cx: &mut Context<Self>,
12678    ) {
12679        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12680            self.buffer
12681                .read(cx)
12682                .settings_at(0, cx)
12683                .indent_guides
12684                .enabled
12685        });
12686        self.show_indent_guides = Some(!currently_enabled);
12687        cx.notify();
12688    }
12689
12690    fn should_show_indent_guides(&self) -> Option<bool> {
12691        self.show_indent_guides
12692    }
12693
12694    pub fn toggle_line_numbers(
12695        &mut self,
12696        _: &ToggleLineNumbers,
12697        _: &mut Window,
12698        cx: &mut Context<Self>,
12699    ) {
12700        let mut editor_settings = EditorSettings::get_global(cx).clone();
12701        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12702        EditorSettings::override_global(editor_settings, cx);
12703    }
12704
12705    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12706        self.use_relative_line_numbers
12707            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12708    }
12709
12710    pub fn toggle_relative_line_numbers(
12711        &mut self,
12712        _: &ToggleRelativeLineNumbers,
12713        _: &mut Window,
12714        cx: &mut Context<Self>,
12715    ) {
12716        let is_relative = self.should_use_relative_line_numbers(cx);
12717        self.set_relative_line_number(Some(!is_relative), cx)
12718    }
12719
12720    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12721        self.use_relative_line_numbers = is_relative;
12722        cx.notify();
12723    }
12724
12725    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12726        self.show_gutter = show_gutter;
12727        cx.notify();
12728    }
12729
12730    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12731        self.show_scrollbars = show_scrollbars;
12732        cx.notify();
12733    }
12734
12735    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12736        self.show_line_numbers = Some(show_line_numbers);
12737        cx.notify();
12738    }
12739
12740    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12741        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12742        cx.notify();
12743    }
12744
12745    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12746        self.show_code_actions = Some(show_code_actions);
12747        cx.notify();
12748    }
12749
12750    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12751        self.show_runnables = Some(show_runnables);
12752        cx.notify();
12753    }
12754
12755    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12756        if self.display_map.read(cx).masked != masked {
12757            self.display_map.update(cx, |map, _| map.masked = masked);
12758        }
12759        cx.notify()
12760    }
12761
12762    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12763        self.show_wrap_guides = Some(show_wrap_guides);
12764        cx.notify();
12765    }
12766
12767    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12768        self.show_indent_guides = Some(show_indent_guides);
12769        cx.notify();
12770    }
12771
12772    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12773        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12774            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12775                if let Some(dir) = file.abs_path(cx).parent() {
12776                    return Some(dir.to_owned());
12777                }
12778            }
12779
12780            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12781                return Some(project_path.path.to_path_buf());
12782            }
12783        }
12784
12785        None
12786    }
12787
12788    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12789        self.active_excerpt(cx)?
12790            .1
12791            .read(cx)
12792            .file()
12793            .and_then(|f| f.as_local())
12794    }
12795
12796    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12797        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12798            let project_path = buffer.read(cx).project_path(cx)?;
12799            let project = self.project.as_ref()?.read(cx);
12800            project.absolute_path(&project_path, cx)
12801        })
12802    }
12803
12804    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12805        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12806            let project_path = buffer.read(cx).project_path(cx)?;
12807            let project = self.project.as_ref()?.read(cx);
12808            let entry = project.entry_for_path(&project_path, cx)?;
12809            let path = entry.path.to_path_buf();
12810            Some(path)
12811        })
12812    }
12813
12814    pub fn reveal_in_finder(
12815        &mut self,
12816        _: &RevealInFileManager,
12817        _window: &mut Window,
12818        cx: &mut Context<Self>,
12819    ) {
12820        if let Some(target) = self.target_file(cx) {
12821            cx.reveal_path(&target.abs_path(cx));
12822        }
12823    }
12824
12825    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12826        if let Some(path) = self.target_file_abs_path(cx) {
12827            if let Some(path) = path.to_str() {
12828                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12829            }
12830        }
12831    }
12832
12833    pub fn copy_relative_path(
12834        &mut self,
12835        _: &CopyRelativePath,
12836        _window: &mut Window,
12837        cx: &mut Context<Self>,
12838    ) {
12839        if let Some(path) = self.target_file_path(cx) {
12840            if let Some(path) = path.to_str() {
12841                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12842            }
12843        }
12844    }
12845
12846    pub fn toggle_git_blame(
12847        &mut self,
12848        _: &ToggleGitBlame,
12849        window: &mut Window,
12850        cx: &mut Context<Self>,
12851    ) {
12852        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12853
12854        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12855            self.start_git_blame(true, window, cx);
12856        }
12857
12858        cx.notify();
12859    }
12860
12861    pub fn toggle_git_blame_inline(
12862        &mut self,
12863        _: &ToggleGitBlameInline,
12864        window: &mut Window,
12865        cx: &mut Context<Self>,
12866    ) {
12867        self.toggle_git_blame_inline_internal(true, window, cx);
12868        cx.notify();
12869    }
12870
12871    pub fn git_blame_inline_enabled(&self) -> bool {
12872        self.git_blame_inline_enabled
12873    }
12874
12875    pub fn toggle_selection_menu(
12876        &mut self,
12877        _: &ToggleSelectionMenu,
12878        _: &mut Window,
12879        cx: &mut Context<Self>,
12880    ) {
12881        self.show_selection_menu = self
12882            .show_selection_menu
12883            .map(|show_selections_menu| !show_selections_menu)
12884            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12885
12886        cx.notify();
12887    }
12888
12889    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12890        self.show_selection_menu
12891            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12892    }
12893
12894    fn start_git_blame(
12895        &mut self,
12896        user_triggered: bool,
12897        window: &mut Window,
12898        cx: &mut Context<Self>,
12899    ) {
12900        if let Some(project) = self.project.as_ref() {
12901            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12902                return;
12903            };
12904
12905            if buffer.read(cx).file().is_none() {
12906                return;
12907            }
12908
12909            let focused = self.focus_handle(cx).contains_focused(window, cx);
12910
12911            let project = project.clone();
12912            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12913            self.blame_subscription =
12914                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12915            self.blame = Some(blame);
12916        }
12917    }
12918
12919    fn toggle_git_blame_inline_internal(
12920        &mut self,
12921        user_triggered: bool,
12922        window: &mut Window,
12923        cx: &mut Context<Self>,
12924    ) {
12925        if self.git_blame_inline_enabled {
12926            self.git_blame_inline_enabled = false;
12927            self.show_git_blame_inline = false;
12928            self.show_git_blame_inline_delay_task.take();
12929        } else {
12930            self.git_blame_inline_enabled = true;
12931            self.start_git_blame_inline(user_triggered, window, cx);
12932        }
12933
12934        cx.notify();
12935    }
12936
12937    fn start_git_blame_inline(
12938        &mut self,
12939        user_triggered: bool,
12940        window: &mut Window,
12941        cx: &mut Context<Self>,
12942    ) {
12943        self.start_git_blame(user_triggered, window, cx);
12944
12945        if ProjectSettings::get_global(cx)
12946            .git
12947            .inline_blame_delay()
12948            .is_some()
12949        {
12950            self.start_inline_blame_timer(window, cx);
12951        } else {
12952            self.show_git_blame_inline = true
12953        }
12954    }
12955
12956    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12957        self.blame.as_ref()
12958    }
12959
12960    pub fn show_git_blame_gutter(&self) -> bool {
12961        self.show_git_blame_gutter
12962    }
12963
12964    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12965        self.show_git_blame_gutter && self.has_blame_entries(cx)
12966    }
12967
12968    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12969        self.show_git_blame_inline
12970            && self.focus_handle.is_focused(window)
12971            && !self.newest_selection_head_on_empty_line(cx)
12972            && self.has_blame_entries(cx)
12973    }
12974
12975    fn has_blame_entries(&self, cx: &App) -> bool {
12976        self.blame()
12977            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12978    }
12979
12980    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12981        let cursor_anchor = self.selections.newest_anchor().head();
12982
12983        let snapshot = self.buffer.read(cx).snapshot(cx);
12984        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12985
12986        snapshot.line_len(buffer_row) == 0
12987    }
12988
12989    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12990        let buffer_and_selection = maybe!({
12991            let selection = self.selections.newest::<Point>(cx);
12992            let selection_range = selection.range();
12993
12994            let multi_buffer = self.buffer().read(cx);
12995            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12996            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12997
12998            let (buffer, range, _) = if selection.reversed {
12999                buffer_ranges.first()
13000            } else {
13001                buffer_ranges.last()
13002            }?;
13003
13004            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13005                ..text::ToPoint::to_point(&range.end, &buffer).row;
13006            Some((
13007                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13008                selection,
13009            ))
13010        });
13011
13012        let Some((buffer, selection)) = buffer_and_selection else {
13013            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13014        };
13015
13016        let Some(project) = self.project.as_ref() else {
13017            return Task::ready(Err(anyhow!("editor does not have project")));
13018        };
13019
13020        project.update(cx, |project, cx| {
13021            project.get_permalink_to_line(&buffer, selection, cx)
13022        })
13023    }
13024
13025    pub fn copy_permalink_to_line(
13026        &mut self,
13027        _: &CopyPermalinkToLine,
13028        window: &mut Window,
13029        cx: &mut Context<Self>,
13030    ) {
13031        let permalink_task = self.get_permalink_to_line(cx);
13032        let workspace = self.workspace();
13033
13034        cx.spawn_in(window, |_, mut cx| async move {
13035            match permalink_task.await {
13036                Ok(permalink) => {
13037                    cx.update(|_, cx| {
13038                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13039                    })
13040                    .ok();
13041                }
13042                Err(err) => {
13043                    let message = format!("Failed to copy permalink: {err}");
13044
13045                    Err::<(), anyhow::Error>(err).log_err();
13046
13047                    if let Some(workspace) = workspace {
13048                        workspace
13049                            .update_in(&mut cx, |workspace, _, cx| {
13050                                struct CopyPermalinkToLine;
13051
13052                                workspace.show_toast(
13053                                    Toast::new(
13054                                        NotificationId::unique::<CopyPermalinkToLine>(),
13055                                        message,
13056                                    ),
13057                                    cx,
13058                                )
13059                            })
13060                            .ok();
13061                    }
13062                }
13063            }
13064        })
13065        .detach();
13066    }
13067
13068    pub fn copy_file_location(
13069        &mut self,
13070        _: &CopyFileLocation,
13071        _: &mut Window,
13072        cx: &mut Context<Self>,
13073    ) {
13074        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13075        if let Some(file) = self.target_file(cx) {
13076            if let Some(path) = file.path().to_str() {
13077                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13078            }
13079        }
13080    }
13081
13082    pub fn open_permalink_to_line(
13083        &mut self,
13084        _: &OpenPermalinkToLine,
13085        window: &mut Window,
13086        cx: &mut Context<Self>,
13087    ) {
13088        let permalink_task = self.get_permalink_to_line(cx);
13089        let workspace = self.workspace();
13090
13091        cx.spawn_in(window, |_, mut cx| async move {
13092            match permalink_task.await {
13093                Ok(permalink) => {
13094                    cx.update(|_, cx| {
13095                        cx.open_url(permalink.as_ref());
13096                    })
13097                    .ok();
13098                }
13099                Err(err) => {
13100                    let message = format!("Failed to open permalink: {err}");
13101
13102                    Err::<(), anyhow::Error>(err).log_err();
13103
13104                    if let Some(workspace) = workspace {
13105                        workspace
13106                            .update(&mut cx, |workspace, cx| {
13107                                struct OpenPermalinkToLine;
13108
13109                                workspace.show_toast(
13110                                    Toast::new(
13111                                        NotificationId::unique::<OpenPermalinkToLine>(),
13112                                        message,
13113                                    ),
13114                                    cx,
13115                                )
13116                            })
13117                            .ok();
13118                    }
13119                }
13120            }
13121        })
13122        .detach();
13123    }
13124
13125    pub fn insert_uuid_v4(
13126        &mut self,
13127        _: &InsertUuidV4,
13128        window: &mut Window,
13129        cx: &mut Context<Self>,
13130    ) {
13131        self.insert_uuid(UuidVersion::V4, window, cx);
13132    }
13133
13134    pub fn insert_uuid_v7(
13135        &mut self,
13136        _: &InsertUuidV7,
13137        window: &mut Window,
13138        cx: &mut Context<Self>,
13139    ) {
13140        self.insert_uuid(UuidVersion::V7, window, cx);
13141    }
13142
13143    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13144        self.transact(window, cx, |this, window, cx| {
13145            let edits = this
13146                .selections
13147                .all::<Point>(cx)
13148                .into_iter()
13149                .map(|selection| {
13150                    let uuid = match version {
13151                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13152                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13153                    };
13154
13155                    (selection.range(), uuid.to_string())
13156                });
13157            this.edit(edits, cx);
13158            this.refresh_inline_completion(true, false, window, cx);
13159        });
13160    }
13161
13162    pub fn open_selections_in_multibuffer(
13163        &mut self,
13164        _: &OpenSelectionsInMultibuffer,
13165        window: &mut Window,
13166        cx: &mut Context<Self>,
13167    ) {
13168        let multibuffer = self.buffer.read(cx);
13169
13170        let Some(buffer) = multibuffer.as_singleton() else {
13171            return;
13172        };
13173
13174        let Some(workspace) = self.workspace() else {
13175            return;
13176        };
13177
13178        let locations = self
13179            .selections
13180            .disjoint_anchors()
13181            .iter()
13182            .map(|range| Location {
13183                buffer: buffer.clone(),
13184                range: range.start.text_anchor..range.end.text_anchor,
13185            })
13186            .collect::<Vec<_>>();
13187
13188        let title = multibuffer.title(cx).to_string();
13189
13190        cx.spawn_in(window, |_, mut cx| async move {
13191            workspace.update_in(&mut cx, |workspace, window, cx| {
13192                Self::open_locations_in_multibuffer(
13193                    workspace,
13194                    locations,
13195                    format!("Selections for '{title}'"),
13196                    false,
13197                    MultibufferSelectionMode::All,
13198                    window,
13199                    cx,
13200                );
13201            })
13202        })
13203        .detach();
13204    }
13205
13206    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13207    /// last highlight added will be used.
13208    ///
13209    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13210    pub fn highlight_rows<T: 'static>(
13211        &mut self,
13212        range: Range<Anchor>,
13213        color: Hsla,
13214        should_autoscroll: bool,
13215        cx: &mut Context<Self>,
13216    ) {
13217        let snapshot = self.buffer().read(cx).snapshot(cx);
13218        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13219        let ix = row_highlights.binary_search_by(|highlight| {
13220            Ordering::Equal
13221                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13222                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13223        });
13224
13225        if let Err(mut ix) = ix {
13226            let index = post_inc(&mut self.highlight_order);
13227
13228            // If this range intersects with the preceding highlight, then merge it with
13229            // the preceding highlight. Otherwise insert a new highlight.
13230            let mut merged = false;
13231            if ix > 0 {
13232                let prev_highlight = &mut row_highlights[ix - 1];
13233                if prev_highlight
13234                    .range
13235                    .end
13236                    .cmp(&range.start, &snapshot)
13237                    .is_ge()
13238                {
13239                    ix -= 1;
13240                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13241                        prev_highlight.range.end = range.end;
13242                    }
13243                    merged = true;
13244                    prev_highlight.index = index;
13245                    prev_highlight.color = color;
13246                    prev_highlight.should_autoscroll = should_autoscroll;
13247                }
13248            }
13249
13250            if !merged {
13251                row_highlights.insert(
13252                    ix,
13253                    RowHighlight {
13254                        range: range.clone(),
13255                        index,
13256                        color,
13257                        should_autoscroll,
13258                    },
13259                );
13260            }
13261
13262            // If any of the following highlights intersect with this one, merge them.
13263            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13264                let highlight = &row_highlights[ix];
13265                if next_highlight
13266                    .range
13267                    .start
13268                    .cmp(&highlight.range.end, &snapshot)
13269                    .is_le()
13270                {
13271                    if next_highlight
13272                        .range
13273                        .end
13274                        .cmp(&highlight.range.end, &snapshot)
13275                        .is_gt()
13276                    {
13277                        row_highlights[ix].range.end = next_highlight.range.end;
13278                    }
13279                    row_highlights.remove(ix + 1);
13280                } else {
13281                    break;
13282                }
13283            }
13284        }
13285    }
13286
13287    /// Remove any highlighted row ranges of the given type that intersect the
13288    /// given ranges.
13289    pub fn remove_highlighted_rows<T: 'static>(
13290        &mut self,
13291        ranges_to_remove: Vec<Range<Anchor>>,
13292        cx: &mut Context<Self>,
13293    ) {
13294        let snapshot = self.buffer().read(cx).snapshot(cx);
13295        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13296        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13297        row_highlights.retain(|highlight| {
13298            while let Some(range_to_remove) = ranges_to_remove.peek() {
13299                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13300                    Ordering::Less | Ordering::Equal => {
13301                        ranges_to_remove.next();
13302                    }
13303                    Ordering::Greater => {
13304                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13305                            Ordering::Less | Ordering::Equal => {
13306                                return false;
13307                            }
13308                            Ordering::Greater => break,
13309                        }
13310                    }
13311                }
13312            }
13313
13314            true
13315        })
13316    }
13317
13318    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13319    pub fn clear_row_highlights<T: 'static>(&mut self) {
13320        self.highlighted_rows.remove(&TypeId::of::<T>());
13321    }
13322
13323    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13324    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13325        self.highlighted_rows
13326            .get(&TypeId::of::<T>())
13327            .map_or(&[] as &[_], |vec| vec.as_slice())
13328            .iter()
13329            .map(|highlight| (highlight.range.clone(), highlight.color))
13330    }
13331
13332    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13333    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13334    /// Allows to ignore certain kinds of highlights.
13335    pub fn highlighted_display_rows(
13336        &self,
13337        window: &mut Window,
13338        cx: &mut App,
13339    ) -> BTreeMap<DisplayRow, Background> {
13340        let snapshot = self.snapshot(window, cx);
13341        let mut used_highlight_orders = HashMap::default();
13342        self.highlighted_rows
13343            .iter()
13344            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13345            .fold(
13346                BTreeMap::<DisplayRow, Background>::new(),
13347                |mut unique_rows, highlight| {
13348                    let start = highlight.range.start.to_display_point(&snapshot);
13349                    let end = highlight.range.end.to_display_point(&snapshot);
13350                    let start_row = start.row().0;
13351                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13352                        && end.column() == 0
13353                    {
13354                        end.row().0.saturating_sub(1)
13355                    } else {
13356                        end.row().0
13357                    };
13358                    for row in start_row..=end_row {
13359                        let used_index =
13360                            used_highlight_orders.entry(row).or_insert(highlight.index);
13361                        if highlight.index >= *used_index {
13362                            *used_index = highlight.index;
13363                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13364                        }
13365                    }
13366                    unique_rows
13367                },
13368            )
13369    }
13370
13371    pub fn highlighted_display_row_for_autoscroll(
13372        &self,
13373        snapshot: &DisplaySnapshot,
13374    ) -> Option<DisplayRow> {
13375        self.highlighted_rows
13376            .values()
13377            .flat_map(|highlighted_rows| highlighted_rows.iter())
13378            .filter_map(|highlight| {
13379                if highlight.should_autoscroll {
13380                    Some(highlight.range.start.to_display_point(snapshot).row())
13381                } else {
13382                    None
13383                }
13384            })
13385            .min()
13386    }
13387
13388    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13389        self.highlight_background::<SearchWithinRange>(
13390            ranges,
13391            |colors| colors.editor_document_highlight_read_background,
13392            cx,
13393        )
13394    }
13395
13396    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13397        self.breadcrumb_header = Some(new_header);
13398    }
13399
13400    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13401        self.clear_background_highlights::<SearchWithinRange>(cx);
13402    }
13403
13404    pub fn highlight_background<T: 'static>(
13405        &mut self,
13406        ranges: &[Range<Anchor>],
13407        color_fetcher: fn(&ThemeColors) -> Hsla,
13408        cx: &mut Context<Self>,
13409    ) {
13410        self.background_highlights
13411            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13412        self.scrollbar_marker_state.dirty = true;
13413        cx.notify();
13414    }
13415
13416    pub fn clear_background_highlights<T: 'static>(
13417        &mut self,
13418        cx: &mut Context<Self>,
13419    ) -> Option<BackgroundHighlight> {
13420        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13421        if !text_highlights.1.is_empty() {
13422            self.scrollbar_marker_state.dirty = true;
13423            cx.notify();
13424        }
13425        Some(text_highlights)
13426    }
13427
13428    pub fn highlight_gutter<T: 'static>(
13429        &mut self,
13430        ranges: &[Range<Anchor>],
13431        color_fetcher: fn(&App) -> Hsla,
13432        cx: &mut Context<Self>,
13433    ) {
13434        self.gutter_highlights
13435            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13436        cx.notify();
13437    }
13438
13439    pub fn clear_gutter_highlights<T: 'static>(
13440        &mut self,
13441        cx: &mut Context<Self>,
13442    ) -> Option<GutterHighlight> {
13443        cx.notify();
13444        self.gutter_highlights.remove(&TypeId::of::<T>())
13445    }
13446
13447    #[cfg(feature = "test-support")]
13448    pub fn all_text_background_highlights(
13449        &self,
13450        window: &mut Window,
13451        cx: &mut Context<Self>,
13452    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13453        let snapshot = self.snapshot(window, cx);
13454        let buffer = &snapshot.buffer_snapshot;
13455        let start = buffer.anchor_before(0);
13456        let end = buffer.anchor_after(buffer.len());
13457        let theme = cx.theme().colors();
13458        self.background_highlights_in_range(start..end, &snapshot, theme)
13459    }
13460
13461    #[cfg(feature = "test-support")]
13462    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13463        let snapshot = self.buffer().read(cx).snapshot(cx);
13464
13465        let highlights = self
13466            .background_highlights
13467            .get(&TypeId::of::<items::BufferSearchHighlights>());
13468
13469        if let Some((_color, ranges)) = highlights {
13470            ranges
13471                .iter()
13472                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13473                .collect_vec()
13474        } else {
13475            vec![]
13476        }
13477    }
13478
13479    fn document_highlights_for_position<'a>(
13480        &'a self,
13481        position: Anchor,
13482        buffer: &'a MultiBufferSnapshot,
13483    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13484        let read_highlights = self
13485            .background_highlights
13486            .get(&TypeId::of::<DocumentHighlightRead>())
13487            .map(|h| &h.1);
13488        let write_highlights = self
13489            .background_highlights
13490            .get(&TypeId::of::<DocumentHighlightWrite>())
13491            .map(|h| &h.1);
13492        let left_position = position.bias_left(buffer);
13493        let right_position = position.bias_right(buffer);
13494        read_highlights
13495            .into_iter()
13496            .chain(write_highlights)
13497            .flat_map(move |ranges| {
13498                let start_ix = match ranges.binary_search_by(|probe| {
13499                    let cmp = probe.end.cmp(&left_position, buffer);
13500                    if cmp.is_ge() {
13501                        Ordering::Greater
13502                    } else {
13503                        Ordering::Less
13504                    }
13505                }) {
13506                    Ok(i) | Err(i) => i,
13507                };
13508
13509                ranges[start_ix..]
13510                    .iter()
13511                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13512            })
13513    }
13514
13515    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13516        self.background_highlights
13517            .get(&TypeId::of::<T>())
13518            .map_or(false, |(_, highlights)| !highlights.is_empty())
13519    }
13520
13521    pub fn background_highlights_in_range(
13522        &self,
13523        search_range: Range<Anchor>,
13524        display_snapshot: &DisplaySnapshot,
13525        theme: &ThemeColors,
13526    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13527        let mut results = Vec::new();
13528        for (color_fetcher, ranges) in self.background_highlights.values() {
13529            let color = color_fetcher(theme);
13530            let start_ix = match ranges.binary_search_by(|probe| {
13531                let cmp = probe
13532                    .end
13533                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13534                if cmp.is_gt() {
13535                    Ordering::Greater
13536                } else {
13537                    Ordering::Less
13538                }
13539            }) {
13540                Ok(i) | Err(i) => i,
13541            };
13542            for range in &ranges[start_ix..] {
13543                if range
13544                    .start
13545                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13546                    .is_ge()
13547                {
13548                    break;
13549                }
13550
13551                let start = range.start.to_display_point(display_snapshot);
13552                let end = range.end.to_display_point(display_snapshot);
13553                results.push((start..end, color))
13554            }
13555        }
13556        results
13557    }
13558
13559    pub fn background_highlight_row_ranges<T: 'static>(
13560        &self,
13561        search_range: Range<Anchor>,
13562        display_snapshot: &DisplaySnapshot,
13563        count: usize,
13564    ) -> Vec<RangeInclusive<DisplayPoint>> {
13565        let mut results = Vec::new();
13566        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13567            return vec![];
13568        };
13569
13570        let start_ix = match ranges.binary_search_by(|probe| {
13571            let cmp = probe
13572                .end
13573                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13574            if cmp.is_gt() {
13575                Ordering::Greater
13576            } else {
13577                Ordering::Less
13578            }
13579        }) {
13580            Ok(i) | Err(i) => i,
13581        };
13582        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13583            if let (Some(start_display), Some(end_display)) = (start, end) {
13584                results.push(
13585                    start_display.to_display_point(display_snapshot)
13586                        ..=end_display.to_display_point(display_snapshot),
13587                );
13588            }
13589        };
13590        let mut start_row: Option<Point> = None;
13591        let mut end_row: Option<Point> = None;
13592        if ranges.len() > count {
13593            return Vec::new();
13594        }
13595        for range in &ranges[start_ix..] {
13596            if range
13597                .start
13598                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13599                .is_ge()
13600            {
13601                break;
13602            }
13603            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13604            if let Some(current_row) = &end_row {
13605                if end.row == current_row.row {
13606                    continue;
13607                }
13608            }
13609            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13610            if start_row.is_none() {
13611                assert_eq!(end_row, None);
13612                start_row = Some(start);
13613                end_row = Some(end);
13614                continue;
13615            }
13616            if let Some(current_end) = end_row.as_mut() {
13617                if start.row > current_end.row + 1 {
13618                    push_region(start_row, end_row);
13619                    start_row = Some(start);
13620                    end_row = Some(end);
13621                } else {
13622                    // Merge two hunks.
13623                    *current_end = end;
13624                }
13625            } else {
13626                unreachable!();
13627            }
13628        }
13629        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13630        push_region(start_row, end_row);
13631        results
13632    }
13633
13634    pub fn gutter_highlights_in_range(
13635        &self,
13636        search_range: Range<Anchor>,
13637        display_snapshot: &DisplaySnapshot,
13638        cx: &App,
13639    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13640        let mut results = Vec::new();
13641        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13642            let color = color_fetcher(cx);
13643            let start_ix = match ranges.binary_search_by(|probe| {
13644                let cmp = probe
13645                    .end
13646                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13647                if cmp.is_gt() {
13648                    Ordering::Greater
13649                } else {
13650                    Ordering::Less
13651                }
13652            }) {
13653                Ok(i) | Err(i) => i,
13654            };
13655            for range in &ranges[start_ix..] {
13656                if range
13657                    .start
13658                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13659                    .is_ge()
13660                {
13661                    break;
13662                }
13663
13664                let start = range.start.to_display_point(display_snapshot);
13665                let end = range.end.to_display_point(display_snapshot);
13666                results.push((start..end, color))
13667            }
13668        }
13669        results
13670    }
13671
13672    /// Get the text ranges corresponding to the redaction query
13673    pub fn redacted_ranges(
13674        &self,
13675        search_range: Range<Anchor>,
13676        display_snapshot: &DisplaySnapshot,
13677        cx: &App,
13678    ) -> Vec<Range<DisplayPoint>> {
13679        display_snapshot
13680            .buffer_snapshot
13681            .redacted_ranges(search_range, |file| {
13682                if let Some(file) = file {
13683                    file.is_private()
13684                        && EditorSettings::get(
13685                            Some(SettingsLocation {
13686                                worktree_id: file.worktree_id(cx),
13687                                path: file.path().as_ref(),
13688                            }),
13689                            cx,
13690                        )
13691                        .redact_private_values
13692                } else {
13693                    false
13694                }
13695            })
13696            .map(|range| {
13697                range.start.to_display_point(display_snapshot)
13698                    ..range.end.to_display_point(display_snapshot)
13699            })
13700            .collect()
13701    }
13702
13703    pub fn highlight_text<T: 'static>(
13704        &mut self,
13705        ranges: Vec<Range<Anchor>>,
13706        style: HighlightStyle,
13707        cx: &mut Context<Self>,
13708    ) {
13709        self.display_map.update(cx, |map, _| {
13710            map.highlight_text(TypeId::of::<T>(), ranges, style)
13711        });
13712        cx.notify();
13713    }
13714
13715    pub(crate) fn highlight_inlays<T: 'static>(
13716        &mut self,
13717        highlights: Vec<InlayHighlight>,
13718        style: HighlightStyle,
13719        cx: &mut Context<Self>,
13720    ) {
13721        self.display_map.update(cx, |map, _| {
13722            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13723        });
13724        cx.notify();
13725    }
13726
13727    pub fn text_highlights<'a, T: 'static>(
13728        &'a self,
13729        cx: &'a App,
13730    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13731        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13732    }
13733
13734    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13735        let cleared = self
13736            .display_map
13737            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13738        if cleared {
13739            cx.notify();
13740        }
13741    }
13742
13743    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13744        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13745            && self.focus_handle.is_focused(window)
13746    }
13747
13748    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13749        self.show_cursor_when_unfocused = is_enabled;
13750        cx.notify();
13751    }
13752
13753    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13754        self.project
13755            .as_ref()
13756            .map(|project| project.read(cx).lsp_store())
13757    }
13758
13759    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13760        cx.notify();
13761    }
13762
13763    fn on_buffer_event(
13764        &mut self,
13765        multibuffer: &Entity<MultiBuffer>,
13766        event: &multi_buffer::Event,
13767        window: &mut Window,
13768        cx: &mut Context<Self>,
13769    ) {
13770        match event {
13771            multi_buffer::Event::Edited {
13772                singleton_buffer_edited,
13773                edited_buffer: buffer_edited,
13774            } => {
13775                self.scrollbar_marker_state.dirty = true;
13776                self.active_indent_guides_state.dirty = true;
13777                self.refresh_active_diagnostics(cx);
13778                self.refresh_code_actions(window, cx);
13779                if self.has_active_inline_completion() {
13780                    self.update_visible_inline_completion(window, cx);
13781                }
13782                if let Some(buffer) = buffer_edited {
13783                    let buffer_id = buffer.read(cx).remote_id();
13784                    if !self.registered_buffers.contains_key(&buffer_id) {
13785                        if let Some(lsp_store) = self.lsp_store(cx) {
13786                            lsp_store.update(cx, |lsp_store, cx| {
13787                                self.registered_buffers.insert(
13788                                    buffer_id,
13789                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13790                                );
13791                            })
13792                        }
13793                    }
13794                }
13795                cx.emit(EditorEvent::BufferEdited);
13796                cx.emit(SearchEvent::MatchesInvalidated);
13797                if *singleton_buffer_edited {
13798                    if let Some(project) = &self.project {
13799                        let project = project.read(cx);
13800                        #[allow(clippy::mutable_key_type)]
13801                        let languages_affected = multibuffer
13802                            .read(cx)
13803                            .all_buffers()
13804                            .into_iter()
13805                            .filter_map(|buffer| {
13806                                let buffer = buffer.read(cx);
13807                                let language = buffer.language()?;
13808                                if project.is_local()
13809                                    && project
13810                                        .language_servers_for_local_buffer(buffer, cx)
13811                                        .count()
13812                                        == 0
13813                                {
13814                                    None
13815                                } else {
13816                                    Some(language)
13817                                }
13818                            })
13819                            .cloned()
13820                            .collect::<HashSet<_>>();
13821                        if !languages_affected.is_empty() {
13822                            self.refresh_inlay_hints(
13823                                InlayHintRefreshReason::BufferEdited(languages_affected),
13824                                cx,
13825                            );
13826                        }
13827                    }
13828                }
13829
13830                let Some(project) = &self.project else { return };
13831                let (telemetry, is_via_ssh) = {
13832                    let project = project.read(cx);
13833                    let telemetry = project.client().telemetry().clone();
13834                    let is_via_ssh = project.is_via_ssh();
13835                    (telemetry, is_via_ssh)
13836                };
13837                refresh_linked_ranges(self, window, cx);
13838                telemetry.log_edit_event("editor", is_via_ssh);
13839            }
13840            multi_buffer::Event::ExcerptsAdded {
13841                buffer,
13842                predecessor,
13843                excerpts,
13844            } => {
13845                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13846                let buffer_id = buffer.read(cx).remote_id();
13847                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13848                    if let Some(project) = &self.project {
13849                        get_uncommitted_diff_for_buffer(
13850                            project,
13851                            [buffer.clone()],
13852                            self.buffer.clone(),
13853                            cx,
13854                        );
13855                    }
13856                }
13857                cx.emit(EditorEvent::ExcerptsAdded {
13858                    buffer: buffer.clone(),
13859                    predecessor: *predecessor,
13860                    excerpts: excerpts.clone(),
13861                });
13862                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13863            }
13864            multi_buffer::Event::ExcerptsRemoved { ids } => {
13865                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13866                let buffer = self.buffer.read(cx);
13867                self.registered_buffers
13868                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13869                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13870            }
13871            multi_buffer::Event::ExcerptsEdited { ids } => {
13872                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13873            }
13874            multi_buffer::Event::ExcerptsExpanded { ids } => {
13875                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13876                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13877            }
13878            multi_buffer::Event::Reparsed(buffer_id) => {
13879                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13880
13881                cx.emit(EditorEvent::Reparsed(*buffer_id));
13882            }
13883            multi_buffer::Event::DiffHunksToggled => {
13884                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13885            }
13886            multi_buffer::Event::LanguageChanged(buffer_id) => {
13887                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13888                cx.emit(EditorEvent::Reparsed(*buffer_id));
13889                cx.notify();
13890            }
13891            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13892            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13893            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13894                cx.emit(EditorEvent::TitleChanged)
13895            }
13896            // multi_buffer::Event::DiffBaseChanged => {
13897            //     self.scrollbar_marker_state.dirty = true;
13898            //     cx.emit(EditorEvent::DiffBaseChanged);
13899            //     cx.notify();
13900            // }
13901            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13902            multi_buffer::Event::DiagnosticsUpdated => {
13903                self.refresh_active_diagnostics(cx);
13904                self.scrollbar_marker_state.dirty = true;
13905                cx.notify();
13906            }
13907            _ => {}
13908        };
13909    }
13910
13911    fn on_display_map_changed(
13912        &mut self,
13913        _: Entity<DisplayMap>,
13914        _: &mut Window,
13915        cx: &mut Context<Self>,
13916    ) {
13917        cx.notify();
13918    }
13919
13920    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13921        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13922        self.refresh_inline_completion(true, false, window, cx);
13923        self.refresh_inlay_hints(
13924            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13925                self.selections.newest_anchor().head(),
13926                &self.buffer.read(cx).snapshot(cx),
13927                cx,
13928            )),
13929            cx,
13930        );
13931
13932        let old_cursor_shape = self.cursor_shape;
13933
13934        {
13935            let editor_settings = EditorSettings::get_global(cx);
13936            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13937            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13938            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13939        }
13940
13941        if old_cursor_shape != self.cursor_shape {
13942            cx.emit(EditorEvent::CursorShapeChanged);
13943        }
13944
13945        let project_settings = ProjectSettings::get_global(cx);
13946        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13947
13948        if self.mode == EditorMode::Full {
13949            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13950            if self.git_blame_inline_enabled != inline_blame_enabled {
13951                self.toggle_git_blame_inline_internal(false, window, cx);
13952            }
13953        }
13954
13955        cx.notify();
13956    }
13957
13958    pub fn set_searchable(&mut self, searchable: bool) {
13959        self.searchable = searchable;
13960    }
13961
13962    pub fn searchable(&self) -> bool {
13963        self.searchable
13964    }
13965
13966    fn open_proposed_changes_editor(
13967        &mut self,
13968        _: &OpenProposedChangesEditor,
13969        window: &mut Window,
13970        cx: &mut Context<Self>,
13971    ) {
13972        let Some(workspace) = self.workspace() else {
13973            cx.propagate();
13974            return;
13975        };
13976
13977        let selections = self.selections.all::<usize>(cx);
13978        let multi_buffer = self.buffer.read(cx);
13979        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13980        let mut new_selections_by_buffer = HashMap::default();
13981        for selection in selections {
13982            for (buffer, range, _) in
13983                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13984            {
13985                let mut range = range.to_point(buffer);
13986                range.start.column = 0;
13987                range.end.column = buffer.line_len(range.end.row);
13988                new_selections_by_buffer
13989                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13990                    .or_insert(Vec::new())
13991                    .push(range)
13992            }
13993        }
13994
13995        let proposed_changes_buffers = new_selections_by_buffer
13996            .into_iter()
13997            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13998            .collect::<Vec<_>>();
13999        let proposed_changes_editor = cx.new(|cx| {
14000            ProposedChangesEditor::new(
14001                "Proposed changes",
14002                proposed_changes_buffers,
14003                self.project.clone(),
14004                window,
14005                cx,
14006            )
14007        });
14008
14009        window.defer(cx, move |window, cx| {
14010            workspace.update(cx, |workspace, cx| {
14011                workspace.active_pane().update(cx, |pane, cx| {
14012                    pane.add_item(
14013                        Box::new(proposed_changes_editor),
14014                        true,
14015                        true,
14016                        None,
14017                        window,
14018                        cx,
14019                    );
14020                });
14021            });
14022        });
14023    }
14024
14025    pub fn open_excerpts_in_split(
14026        &mut self,
14027        _: &OpenExcerptsSplit,
14028        window: &mut Window,
14029        cx: &mut Context<Self>,
14030    ) {
14031        self.open_excerpts_common(None, true, window, cx)
14032    }
14033
14034    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14035        self.open_excerpts_common(None, false, window, cx)
14036    }
14037
14038    fn open_excerpts_common(
14039        &mut self,
14040        jump_data: Option<JumpData>,
14041        split: bool,
14042        window: &mut Window,
14043        cx: &mut Context<Self>,
14044    ) {
14045        let Some(workspace) = self.workspace() else {
14046            cx.propagate();
14047            return;
14048        };
14049
14050        if self.buffer.read(cx).is_singleton() {
14051            cx.propagate();
14052            return;
14053        }
14054
14055        let mut new_selections_by_buffer = HashMap::default();
14056        match &jump_data {
14057            Some(JumpData::MultiBufferPoint {
14058                excerpt_id,
14059                position,
14060                anchor,
14061                line_offset_from_top,
14062            }) => {
14063                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14064                if let Some(buffer) = multi_buffer_snapshot
14065                    .buffer_id_for_excerpt(*excerpt_id)
14066                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14067                {
14068                    let buffer_snapshot = buffer.read(cx).snapshot();
14069                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14070                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14071                    } else {
14072                        buffer_snapshot.clip_point(*position, Bias::Left)
14073                    };
14074                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14075                    new_selections_by_buffer.insert(
14076                        buffer,
14077                        (
14078                            vec![jump_to_offset..jump_to_offset],
14079                            Some(*line_offset_from_top),
14080                        ),
14081                    );
14082                }
14083            }
14084            Some(JumpData::MultiBufferRow {
14085                row,
14086                line_offset_from_top,
14087            }) => {
14088                let point = MultiBufferPoint::new(row.0, 0);
14089                if let Some((buffer, buffer_point, _)) =
14090                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14091                {
14092                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14093                    new_selections_by_buffer
14094                        .entry(buffer)
14095                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14096                        .0
14097                        .push(buffer_offset..buffer_offset)
14098                }
14099            }
14100            None => {
14101                let selections = self.selections.all::<usize>(cx);
14102                let multi_buffer = self.buffer.read(cx);
14103                for selection in selections {
14104                    for (buffer, mut range, _) in multi_buffer
14105                        .snapshot(cx)
14106                        .range_to_buffer_ranges(selection.range())
14107                    {
14108                        // When editing branch buffers, jump to the corresponding location
14109                        // in their base buffer.
14110                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14111                        let buffer = buffer_handle.read(cx);
14112                        if let Some(base_buffer) = buffer.base_buffer() {
14113                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14114                            buffer_handle = base_buffer;
14115                        }
14116
14117                        if selection.reversed {
14118                            mem::swap(&mut range.start, &mut range.end);
14119                        }
14120                        new_selections_by_buffer
14121                            .entry(buffer_handle)
14122                            .or_insert((Vec::new(), None))
14123                            .0
14124                            .push(range)
14125                    }
14126                }
14127            }
14128        }
14129
14130        if new_selections_by_buffer.is_empty() {
14131            return;
14132        }
14133
14134        // We defer the pane interaction because we ourselves are a workspace item
14135        // and activating a new item causes the pane to call a method on us reentrantly,
14136        // which panics if we're on the stack.
14137        window.defer(cx, move |window, cx| {
14138            workspace.update(cx, |workspace, cx| {
14139                let pane = if split {
14140                    workspace.adjacent_pane(window, cx)
14141                } else {
14142                    workspace.active_pane().clone()
14143                };
14144
14145                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14146                    let editor = buffer
14147                        .read(cx)
14148                        .file()
14149                        .is_none()
14150                        .then(|| {
14151                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14152                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14153                            // Instead, we try to activate the existing editor in the pane first.
14154                            let (editor, pane_item_index) =
14155                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14156                                    let editor = item.downcast::<Editor>()?;
14157                                    let singleton_buffer =
14158                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14159                                    if singleton_buffer == buffer {
14160                                        Some((editor, i))
14161                                    } else {
14162                                        None
14163                                    }
14164                                })?;
14165                            pane.update(cx, |pane, cx| {
14166                                pane.activate_item(pane_item_index, true, true, window, cx)
14167                            });
14168                            Some(editor)
14169                        })
14170                        .flatten()
14171                        .unwrap_or_else(|| {
14172                            workspace.open_project_item::<Self>(
14173                                pane.clone(),
14174                                buffer,
14175                                true,
14176                                true,
14177                                window,
14178                                cx,
14179                            )
14180                        });
14181
14182                    editor.update(cx, |editor, cx| {
14183                        let autoscroll = match scroll_offset {
14184                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14185                            None => Autoscroll::newest(),
14186                        };
14187                        let nav_history = editor.nav_history.take();
14188                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14189                            s.select_ranges(ranges);
14190                        });
14191                        editor.nav_history = nav_history;
14192                    });
14193                }
14194            })
14195        });
14196    }
14197
14198    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14199        let snapshot = self.buffer.read(cx).read(cx);
14200        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14201        Some(
14202            ranges
14203                .iter()
14204                .map(move |range| {
14205                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14206                })
14207                .collect(),
14208        )
14209    }
14210
14211    fn selection_replacement_ranges(
14212        &self,
14213        range: Range<OffsetUtf16>,
14214        cx: &mut App,
14215    ) -> Vec<Range<OffsetUtf16>> {
14216        let selections = self.selections.all::<OffsetUtf16>(cx);
14217        let newest_selection = selections
14218            .iter()
14219            .max_by_key(|selection| selection.id)
14220            .unwrap();
14221        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14222        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14223        let snapshot = self.buffer.read(cx).read(cx);
14224        selections
14225            .into_iter()
14226            .map(|mut selection| {
14227                selection.start.0 =
14228                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14229                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14230                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14231                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14232            })
14233            .collect()
14234    }
14235
14236    fn report_editor_event(
14237        &self,
14238        event_type: &'static str,
14239        file_extension: Option<String>,
14240        cx: &App,
14241    ) {
14242        if cfg!(any(test, feature = "test-support")) {
14243            return;
14244        }
14245
14246        let Some(project) = &self.project else { return };
14247
14248        // If None, we are in a file without an extension
14249        let file = self
14250            .buffer
14251            .read(cx)
14252            .as_singleton()
14253            .and_then(|b| b.read(cx).file());
14254        let file_extension = file_extension.or(file
14255            .as_ref()
14256            .and_then(|file| Path::new(file.file_name(cx)).extension())
14257            .and_then(|e| e.to_str())
14258            .map(|a| a.to_string()));
14259
14260        let vim_mode = cx
14261            .global::<SettingsStore>()
14262            .raw_user_settings()
14263            .get("vim_mode")
14264            == Some(&serde_json::Value::Bool(true));
14265
14266        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14267        let copilot_enabled = edit_predictions_provider
14268            == language::language_settings::EditPredictionProvider::Copilot;
14269        let copilot_enabled_for_language = self
14270            .buffer
14271            .read(cx)
14272            .settings_at(0, cx)
14273            .show_edit_predictions;
14274
14275        let project = project.read(cx);
14276        telemetry::event!(
14277            event_type,
14278            file_extension,
14279            vim_mode,
14280            copilot_enabled,
14281            copilot_enabled_for_language,
14282            edit_predictions_provider,
14283            is_via_ssh = project.is_via_ssh(),
14284        );
14285    }
14286
14287    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14288    /// with each line being an array of {text, highlight} objects.
14289    fn copy_highlight_json(
14290        &mut self,
14291        _: &CopyHighlightJson,
14292        window: &mut Window,
14293        cx: &mut Context<Self>,
14294    ) {
14295        #[derive(Serialize)]
14296        struct Chunk<'a> {
14297            text: String,
14298            highlight: Option<&'a str>,
14299        }
14300
14301        let snapshot = self.buffer.read(cx).snapshot(cx);
14302        let range = self
14303            .selected_text_range(false, window, cx)
14304            .and_then(|selection| {
14305                if selection.range.is_empty() {
14306                    None
14307                } else {
14308                    Some(selection.range)
14309                }
14310            })
14311            .unwrap_or_else(|| 0..snapshot.len());
14312
14313        let chunks = snapshot.chunks(range, true);
14314        let mut lines = Vec::new();
14315        let mut line: VecDeque<Chunk> = VecDeque::new();
14316
14317        let Some(style) = self.style.as_ref() else {
14318            return;
14319        };
14320
14321        for chunk in chunks {
14322            let highlight = chunk
14323                .syntax_highlight_id
14324                .and_then(|id| id.name(&style.syntax));
14325            let mut chunk_lines = chunk.text.split('\n').peekable();
14326            while let Some(text) = chunk_lines.next() {
14327                let mut merged_with_last_token = false;
14328                if let Some(last_token) = line.back_mut() {
14329                    if last_token.highlight == highlight {
14330                        last_token.text.push_str(text);
14331                        merged_with_last_token = true;
14332                    }
14333                }
14334
14335                if !merged_with_last_token {
14336                    line.push_back(Chunk {
14337                        text: text.into(),
14338                        highlight,
14339                    });
14340                }
14341
14342                if chunk_lines.peek().is_some() {
14343                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14344                        line.pop_front();
14345                    }
14346                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14347                        line.pop_back();
14348                    }
14349
14350                    lines.push(mem::take(&mut line));
14351                }
14352            }
14353        }
14354
14355        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14356            return;
14357        };
14358        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14359    }
14360
14361    pub fn open_context_menu(
14362        &mut self,
14363        _: &OpenContextMenu,
14364        window: &mut Window,
14365        cx: &mut Context<Self>,
14366    ) {
14367        self.request_autoscroll(Autoscroll::newest(), cx);
14368        let position = self.selections.newest_display(cx).start;
14369        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14370    }
14371
14372    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14373        &self.inlay_hint_cache
14374    }
14375
14376    pub fn replay_insert_event(
14377        &mut self,
14378        text: &str,
14379        relative_utf16_range: Option<Range<isize>>,
14380        window: &mut Window,
14381        cx: &mut Context<Self>,
14382    ) {
14383        if !self.input_enabled {
14384            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14385            return;
14386        }
14387        if let Some(relative_utf16_range) = relative_utf16_range {
14388            let selections = self.selections.all::<OffsetUtf16>(cx);
14389            self.change_selections(None, window, cx, |s| {
14390                let new_ranges = selections.into_iter().map(|range| {
14391                    let start = OffsetUtf16(
14392                        range
14393                            .head()
14394                            .0
14395                            .saturating_add_signed(relative_utf16_range.start),
14396                    );
14397                    let end = OffsetUtf16(
14398                        range
14399                            .head()
14400                            .0
14401                            .saturating_add_signed(relative_utf16_range.end),
14402                    );
14403                    start..end
14404                });
14405                s.select_ranges(new_ranges);
14406            });
14407        }
14408
14409        self.handle_input(text, window, cx);
14410    }
14411
14412    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14413        let Some(provider) = self.semantics_provider.as_ref() else {
14414            return false;
14415        };
14416
14417        let mut supports = false;
14418        self.buffer().read(cx).for_each_buffer(|buffer| {
14419            supports |= provider.supports_inlay_hints(buffer, cx);
14420        });
14421        supports
14422    }
14423
14424    pub fn is_focused(&self, window: &Window) -> bool {
14425        self.focus_handle.is_focused(window)
14426    }
14427
14428    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14429        cx.emit(EditorEvent::Focused);
14430
14431        if let Some(descendant) = self
14432            .last_focused_descendant
14433            .take()
14434            .and_then(|descendant| descendant.upgrade())
14435        {
14436            window.focus(&descendant);
14437        } else {
14438            if let Some(blame) = self.blame.as_ref() {
14439                blame.update(cx, GitBlame::focus)
14440            }
14441
14442            self.blink_manager.update(cx, BlinkManager::enable);
14443            self.show_cursor_names(window, cx);
14444            self.buffer.update(cx, |buffer, cx| {
14445                buffer.finalize_last_transaction(cx);
14446                if self.leader_peer_id.is_none() {
14447                    buffer.set_active_selections(
14448                        &self.selections.disjoint_anchors(),
14449                        self.selections.line_mode,
14450                        self.cursor_shape,
14451                        cx,
14452                    );
14453                }
14454            });
14455        }
14456    }
14457
14458    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14459        cx.emit(EditorEvent::FocusedIn)
14460    }
14461
14462    fn handle_focus_out(
14463        &mut self,
14464        event: FocusOutEvent,
14465        _window: &mut Window,
14466        _cx: &mut Context<Self>,
14467    ) {
14468        if event.blurred != self.focus_handle {
14469            self.last_focused_descendant = Some(event.blurred);
14470        }
14471    }
14472
14473    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14474        self.blink_manager.update(cx, BlinkManager::disable);
14475        self.buffer
14476            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14477
14478        if let Some(blame) = self.blame.as_ref() {
14479            blame.update(cx, GitBlame::blur)
14480        }
14481        if !self.hover_state.focused(window, cx) {
14482            hide_hover(self, cx);
14483        }
14484
14485        self.hide_context_menu(window, cx);
14486        cx.emit(EditorEvent::Blurred);
14487        cx.notify();
14488    }
14489
14490    pub fn register_action<A: Action>(
14491        &mut self,
14492        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14493    ) -> Subscription {
14494        let id = self.next_editor_action_id.post_inc();
14495        let listener = Arc::new(listener);
14496        self.editor_actions.borrow_mut().insert(
14497            id,
14498            Box::new(move |window, _| {
14499                let listener = listener.clone();
14500                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14501                    let action = action.downcast_ref().unwrap();
14502                    if phase == DispatchPhase::Bubble {
14503                        listener(action, window, cx)
14504                    }
14505                })
14506            }),
14507        );
14508
14509        let editor_actions = self.editor_actions.clone();
14510        Subscription::new(move || {
14511            editor_actions.borrow_mut().remove(&id);
14512        })
14513    }
14514
14515    pub fn file_header_size(&self) -> u32 {
14516        FILE_HEADER_HEIGHT
14517    }
14518
14519    pub fn revert(
14520        &mut self,
14521        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14522        window: &mut Window,
14523        cx: &mut Context<Self>,
14524    ) {
14525        self.buffer().update(cx, |multi_buffer, cx| {
14526            for (buffer_id, changes) in revert_changes {
14527                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14528                    buffer.update(cx, |buffer, cx| {
14529                        buffer.edit(
14530                            changes.into_iter().map(|(range, text)| {
14531                                (range, text.to_string().map(Arc::<str>::from))
14532                            }),
14533                            None,
14534                            cx,
14535                        );
14536                    });
14537                }
14538            }
14539        });
14540        self.change_selections(None, window, cx, |selections| selections.refresh());
14541    }
14542
14543    pub fn to_pixel_point(
14544        &self,
14545        source: multi_buffer::Anchor,
14546        editor_snapshot: &EditorSnapshot,
14547        window: &mut Window,
14548    ) -> Option<gpui::Point<Pixels>> {
14549        let source_point = source.to_display_point(editor_snapshot);
14550        self.display_to_pixel_point(source_point, editor_snapshot, window)
14551    }
14552
14553    pub fn display_to_pixel_point(
14554        &self,
14555        source: DisplayPoint,
14556        editor_snapshot: &EditorSnapshot,
14557        window: &mut Window,
14558    ) -> Option<gpui::Point<Pixels>> {
14559        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14560        let text_layout_details = self.text_layout_details(window);
14561        let scroll_top = text_layout_details
14562            .scroll_anchor
14563            .scroll_position(editor_snapshot)
14564            .y;
14565
14566        if source.row().as_f32() < scroll_top.floor() {
14567            return None;
14568        }
14569        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14570        let source_y = line_height * (source.row().as_f32() - scroll_top);
14571        Some(gpui::Point::new(source_x, source_y))
14572    }
14573
14574    pub fn has_visible_completions_menu(&self) -> bool {
14575        !self.previewing_inline_completion
14576            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14577                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14578            })
14579    }
14580
14581    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14582        self.addons
14583            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14584    }
14585
14586    pub fn unregister_addon<T: Addon>(&mut self) {
14587        self.addons.remove(&std::any::TypeId::of::<T>());
14588    }
14589
14590    pub fn addon<T: Addon>(&self) -> Option<&T> {
14591        let type_id = std::any::TypeId::of::<T>();
14592        self.addons
14593            .get(&type_id)
14594            .and_then(|item| item.to_any().downcast_ref::<T>())
14595    }
14596
14597    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14598        let text_layout_details = self.text_layout_details(window);
14599        let style = &text_layout_details.editor_style;
14600        let font_id = window.text_system().resolve_font(&style.text.font());
14601        let font_size = style.text.font_size.to_pixels(window.rem_size());
14602        let line_height = style.text.line_height_in_pixels(window.rem_size());
14603        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14604
14605        gpui::Size::new(em_width, line_height)
14606    }
14607}
14608
14609fn get_uncommitted_diff_for_buffer(
14610    project: &Entity<Project>,
14611    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14612    buffer: Entity<MultiBuffer>,
14613    cx: &mut App,
14614) {
14615    let mut tasks = Vec::new();
14616    project.update(cx, |project, cx| {
14617        for buffer in buffers {
14618            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14619        }
14620    });
14621    cx.spawn(|mut cx| async move {
14622        let diffs = futures::future::join_all(tasks).await;
14623        buffer
14624            .update(&mut cx, |buffer, cx| {
14625                for diff in diffs.into_iter().flatten() {
14626                    buffer.add_diff(diff, cx);
14627                }
14628            })
14629            .ok();
14630    })
14631    .detach();
14632}
14633
14634fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14635    let tab_size = tab_size.get() as usize;
14636    let mut width = offset;
14637
14638    for ch in text.chars() {
14639        width += if ch == '\t' {
14640            tab_size - (width % tab_size)
14641        } else {
14642            1
14643        };
14644    }
14645
14646    width - offset
14647}
14648
14649#[cfg(test)]
14650mod tests {
14651    use super::*;
14652
14653    #[test]
14654    fn test_string_size_with_expanded_tabs() {
14655        let nz = |val| NonZeroU32::new(val).unwrap();
14656        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14657        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14658        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14659        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14660        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14661        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14662        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14663        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14664    }
14665}
14666
14667/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14668struct WordBreakingTokenizer<'a> {
14669    input: &'a str,
14670}
14671
14672impl<'a> WordBreakingTokenizer<'a> {
14673    fn new(input: &'a str) -> Self {
14674        Self { input }
14675    }
14676}
14677
14678fn is_char_ideographic(ch: char) -> bool {
14679    use unicode_script::Script::*;
14680    use unicode_script::UnicodeScript;
14681    matches!(ch.script(), Han | Tangut | Yi)
14682}
14683
14684fn is_grapheme_ideographic(text: &str) -> bool {
14685    text.chars().any(is_char_ideographic)
14686}
14687
14688fn is_grapheme_whitespace(text: &str) -> bool {
14689    text.chars().any(|x| x.is_whitespace())
14690}
14691
14692fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14693    text.chars().next().map_or(false, |ch| {
14694        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14695    })
14696}
14697
14698#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14699struct WordBreakToken<'a> {
14700    token: &'a str,
14701    grapheme_len: usize,
14702    is_whitespace: bool,
14703}
14704
14705impl<'a> Iterator for WordBreakingTokenizer<'a> {
14706    /// Yields a span, the count of graphemes in the token, and whether it was
14707    /// whitespace. Note that it also breaks at word boundaries.
14708    type Item = WordBreakToken<'a>;
14709
14710    fn next(&mut self) -> Option<Self::Item> {
14711        use unicode_segmentation::UnicodeSegmentation;
14712        if self.input.is_empty() {
14713            return None;
14714        }
14715
14716        let mut iter = self.input.graphemes(true).peekable();
14717        let mut offset = 0;
14718        let mut graphemes = 0;
14719        if let Some(first_grapheme) = iter.next() {
14720            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14721            offset += first_grapheme.len();
14722            graphemes += 1;
14723            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14724                if let Some(grapheme) = iter.peek().copied() {
14725                    if should_stay_with_preceding_ideograph(grapheme) {
14726                        offset += grapheme.len();
14727                        graphemes += 1;
14728                    }
14729                }
14730            } else {
14731                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14732                let mut next_word_bound = words.peek().copied();
14733                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14734                    next_word_bound = words.next();
14735                }
14736                while let Some(grapheme) = iter.peek().copied() {
14737                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14738                        break;
14739                    };
14740                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14741                        break;
14742                    };
14743                    offset += grapheme.len();
14744                    graphemes += 1;
14745                    iter.next();
14746                }
14747            }
14748            let token = &self.input[..offset];
14749            self.input = &self.input[offset..];
14750            if is_whitespace {
14751                Some(WordBreakToken {
14752                    token: " ",
14753                    grapheme_len: 1,
14754                    is_whitespace: true,
14755                })
14756            } else {
14757                Some(WordBreakToken {
14758                    token,
14759                    grapheme_len: graphemes,
14760                    is_whitespace: false,
14761                })
14762            }
14763        } else {
14764            None
14765        }
14766    }
14767}
14768
14769#[test]
14770fn test_word_breaking_tokenizer() {
14771    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14772        ("", &[]),
14773        ("  ", &[(" ", 1, true)]),
14774        ("Ʒ", &[("Ʒ", 1, false)]),
14775        ("Ǽ", &[("Ǽ", 1, false)]),
14776        ("", &[("", 1, false)]),
14777        ("⋑⋑", &[("⋑⋑", 2, false)]),
14778        (
14779            "原理,进而",
14780            &[
14781                ("", 1, false),
14782                ("理,", 2, false),
14783                ("", 1, false),
14784                ("", 1, false),
14785            ],
14786        ),
14787        (
14788            "hello world",
14789            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14790        ),
14791        (
14792            "hello, world",
14793            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14794        ),
14795        (
14796            "  hello world",
14797            &[
14798                (" ", 1, true),
14799                ("hello", 5, false),
14800                (" ", 1, true),
14801                ("world", 5, false),
14802            ],
14803        ),
14804        (
14805            "这是什么 \n 钢笔",
14806            &[
14807                ("", 1, false),
14808                ("", 1, false),
14809                ("", 1, false),
14810                ("", 1, false),
14811                (" ", 1, true),
14812                ("", 1, false),
14813                ("", 1, false),
14814            ],
14815        ),
14816        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14817    ];
14818
14819    for (input, result) in tests {
14820        assert_eq!(
14821            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14822            result
14823                .iter()
14824                .copied()
14825                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14826                    token,
14827                    grapheme_len,
14828                    is_whitespace,
14829                })
14830                .collect::<Vec<_>>()
14831        );
14832    }
14833}
14834
14835fn wrap_with_prefix(
14836    line_prefix: String,
14837    unwrapped_text: String,
14838    wrap_column: usize,
14839    tab_size: NonZeroU32,
14840) -> String {
14841    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14842    let mut wrapped_text = String::new();
14843    let mut current_line = line_prefix.clone();
14844
14845    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14846    let mut current_line_len = line_prefix_len;
14847    for WordBreakToken {
14848        token,
14849        grapheme_len,
14850        is_whitespace,
14851    } in tokenizer
14852    {
14853        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14854            wrapped_text.push_str(current_line.trim_end());
14855            wrapped_text.push('\n');
14856            current_line.truncate(line_prefix.len());
14857            current_line_len = line_prefix_len;
14858            if !is_whitespace {
14859                current_line.push_str(token);
14860                current_line_len += grapheme_len;
14861            }
14862        } else if !is_whitespace {
14863            current_line.push_str(token);
14864            current_line_len += grapheme_len;
14865        } else if current_line_len != line_prefix_len {
14866            current_line.push(' ');
14867            current_line_len += 1;
14868        }
14869    }
14870
14871    if !current_line.is_empty() {
14872        wrapped_text.push_str(&current_line);
14873    }
14874    wrapped_text
14875}
14876
14877#[test]
14878fn test_wrap_with_prefix() {
14879    assert_eq!(
14880        wrap_with_prefix(
14881            "# ".to_string(),
14882            "abcdefg".to_string(),
14883            4,
14884            NonZeroU32::new(4).unwrap()
14885        ),
14886        "# abcdefg"
14887    );
14888    assert_eq!(
14889        wrap_with_prefix(
14890            "".to_string(),
14891            "\thello world".to_string(),
14892            8,
14893            NonZeroU32::new(4).unwrap()
14894        ),
14895        "hello\nworld"
14896    );
14897    assert_eq!(
14898        wrap_with_prefix(
14899            "// ".to_string(),
14900            "xx \nyy zz aa bb cc".to_string(),
14901            12,
14902            NonZeroU32::new(4).unwrap()
14903        ),
14904        "// xx yy zz\n// aa bb cc"
14905    );
14906    assert_eq!(
14907        wrap_with_prefix(
14908            String::new(),
14909            "这是什么 \n 钢笔".to_string(),
14910            3,
14911            NonZeroU32::new(4).unwrap()
14912        ),
14913        "这是什\n么 钢\n"
14914    );
14915}
14916
14917pub trait CollaborationHub {
14918    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14919    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14920    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14921}
14922
14923impl CollaborationHub for Entity<Project> {
14924    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14925        self.read(cx).collaborators()
14926    }
14927
14928    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14929        self.read(cx).user_store().read(cx).participant_indices()
14930    }
14931
14932    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14933        let this = self.read(cx);
14934        let user_ids = this.collaborators().values().map(|c| c.user_id);
14935        this.user_store().read_with(cx, |user_store, cx| {
14936            user_store.participant_names(user_ids, cx)
14937        })
14938    }
14939}
14940
14941pub trait SemanticsProvider {
14942    fn hover(
14943        &self,
14944        buffer: &Entity<Buffer>,
14945        position: text::Anchor,
14946        cx: &mut App,
14947    ) -> Option<Task<Vec<project::Hover>>>;
14948
14949    fn inlay_hints(
14950        &self,
14951        buffer_handle: Entity<Buffer>,
14952        range: Range<text::Anchor>,
14953        cx: &mut App,
14954    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14955
14956    fn resolve_inlay_hint(
14957        &self,
14958        hint: InlayHint,
14959        buffer_handle: Entity<Buffer>,
14960        server_id: LanguageServerId,
14961        cx: &mut App,
14962    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14963
14964    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14965
14966    fn document_highlights(
14967        &self,
14968        buffer: &Entity<Buffer>,
14969        position: text::Anchor,
14970        cx: &mut App,
14971    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14972
14973    fn definitions(
14974        &self,
14975        buffer: &Entity<Buffer>,
14976        position: text::Anchor,
14977        kind: GotoDefinitionKind,
14978        cx: &mut App,
14979    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14980
14981    fn range_for_rename(
14982        &self,
14983        buffer: &Entity<Buffer>,
14984        position: text::Anchor,
14985        cx: &mut App,
14986    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14987
14988    fn perform_rename(
14989        &self,
14990        buffer: &Entity<Buffer>,
14991        position: text::Anchor,
14992        new_name: String,
14993        cx: &mut App,
14994    ) -> Option<Task<Result<ProjectTransaction>>>;
14995}
14996
14997pub trait CompletionProvider {
14998    fn completions(
14999        &self,
15000        buffer: &Entity<Buffer>,
15001        buffer_position: text::Anchor,
15002        trigger: CompletionContext,
15003        window: &mut Window,
15004        cx: &mut Context<Editor>,
15005    ) -> Task<Result<Vec<Completion>>>;
15006
15007    fn resolve_completions(
15008        &self,
15009        buffer: Entity<Buffer>,
15010        completion_indices: Vec<usize>,
15011        completions: Rc<RefCell<Box<[Completion]>>>,
15012        cx: &mut Context<Editor>,
15013    ) -> Task<Result<bool>>;
15014
15015    fn apply_additional_edits_for_completion(
15016        &self,
15017        _buffer: Entity<Buffer>,
15018        _completions: Rc<RefCell<Box<[Completion]>>>,
15019        _completion_index: usize,
15020        _push_to_history: bool,
15021        _cx: &mut Context<Editor>,
15022    ) -> Task<Result<Option<language::Transaction>>> {
15023        Task::ready(Ok(None))
15024    }
15025
15026    fn is_completion_trigger(
15027        &self,
15028        buffer: &Entity<Buffer>,
15029        position: language::Anchor,
15030        text: &str,
15031        trigger_in_words: bool,
15032        cx: &mut Context<Editor>,
15033    ) -> bool;
15034
15035    fn sort_completions(&self) -> bool {
15036        true
15037    }
15038}
15039
15040pub trait CodeActionProvider {
15041    fn id(&self) -> Arc<str>;
15042
15043    fn code_actions(
15044        &self,
15045        buffer: &Entity<Buffer>,
15046        range: Range<text::Anchor>,
15047        window: &mut Window,
15048        cx: &mut App,
15049    ) -> Task<Result<Vec<CodeAction>>>;
15050
15051    fn apply_code_action(
15052        &self,
15053        buffer_handle: Entity<Buffer>,
15054        action: CodeAction,
15055        excerpt_id: ExcerptId,
15056        push_to_history: bool,
15057        window: &mut Window,
15058        cx: &mut App,
15059    ) -> Task<Result<ProjectTransaction>>;
15060}
15061
15062impl CodeActionProvider for Entity<Project> {
15063    fn id(&self) -> Arc<str> {
15064        "project".into()
15065    }
15066
15067    fn code_actions(
15068        &self,
15069        buffer: &Entity<Buffer>,
15070        range: Range<text::Anchor>,
15071        _window: &mut Window,
15072        cx: &mut App,
15073    ) -> Task<Result<Vec<CodeAction>>> {
15074        self.update(cx, |project, cx| {
15075            project.code_actions(buffer, range, None, cx)
15076        })
15077    }
15078
15079    fn apply_code_action(
15080        &self,
15081        buffer_handle: Entity<Buffer>,
15082        action: CodeAction,
15083        _excerpt_id: ExcerptId,
15084        push_to_history: bool,
15085        _window: &mut Window,
15086        cx: &mut App,
15087    ) -> Task<Result<ProjectTransaction>> {
15088        self.update(cx, |project, cx| {
15089            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15090        })
15091    }
15092}
15093
15094fn snippet_completions(
15095    project: &Project,
15096    buffer: &Entity<Buffer>,
15097    buffer_position: text::Anchor,
15098    cx: &mut App,
15099) -> Task<Result<Vec<Completion>>> {
15100    let language = buffer.read(cx).language_at(buffer_position);
15101    let language_name = language.as_ref().map(|language| language.lsp_id());
15102    let snippet_store = project.snippets().read(cx);
15103    let snippets = snippet_store.snippets_for(language_name, cx);
15104
15105    if snippets.is_empty() {
15106        return Task::ready(Ok(vec![]));
15107    }
15108    let snapshot = buffer.read(cx).text_snapshot();
15109    let chars: String = snapshot
15110        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15111        .collect();
15112
15113    let scope = language.map(|language| language.default_scope());
15114    let executor = cx.background_executor().clone();
15115
15116    cx.background_executor().spawn(async move {
15117        let classifier = CharClassifier::new(scope).for_completion(true);
15118        let mut last_word = chars
15119            .chars()
15120            .take_while(|c| classifier.is_word(*c))
15121            .collect::<String>();
15122        last_word = last_word.chars().rev().collect();
15123
15124        if last_word.is_empty() {
15125            return Ok(vec![]);
15126        }
15127
15128        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15129        let to_lsp = |point: &text::Anchor| {
15130            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15131            point_to_lsp(end)
15132        };
15133        let lsp_end = to_lsp(&buffer_position);
15134
15135        let candidates = snippets
15136            .iter()
15137            .enumerate()
15138            .flat_map(|(ix, snippet)| {
15139                snippet
15140                    .prefix
15141                    .iter()
15142                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15143            })
15144            .collect::<Vec<StringMatchCandidate>>();
15145
15146        let mut matches = fuzzy::match_strings(
15147            &candidates,
15148            &last_word,
15149            last_word.chars().any(|c| c.is_uppercase()),
15150            100,
15151            &Default::default(),
15152            executor,
15153        )
15154        .await;
15155
15156        // Remove all candidates where the query's start does not match the start of any word in the candidate
15157        if let Some(query_start) = last_word.chars().next() {
15158            matches.retain(|string_match| {
15159                split_words(&string_match.string).any(|word| {
15160                    // Check that the first codepoint of the word as lowercase matches the first
15161                    // codepoint of the query as lowercase
15162                    word.chars()
15163                        .flat_map(|codepoint| codepoint.to_lowercase())
15164                        .zip(query_start.to_lowercase())
15165                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15166                })
15167            });
15168        }
15169
15170        let matched_strings = matches
15171            .into_iter()
15172            .map(|m| m.string)
15173            .collect::<HashSet<_>>();
15174
15175        let result: Vec<Completion> = snippets
15176            .into_iter()
15177            .filter_map(|snippet| {
15178                let matching_prefix = snippet
15179                    .prefix
15180                    .iter()
15181                    .find(|prefix| matched_strings.contains(*prefix))?;
15182                let start = as_offset - last_word.len();
15183                let start = snapshot.anchor_before(start);
15184                let range = start..buffer_position;
15185                let lsp_start = to_lsp(&start);
15186                let lsp_range = lsp::Range {
15187                    start: lsp_start,
15188                    end: lsp_end,
15189                };
15190                Some(Completion {
15191                    old_range: range,
15192                    new_text: snippet.body.clone(),
15193                    resolved: false,
15194                    label: CodeLabel {
15195                        text: matching_prefix.clone(),
15196                        runs: vec![],
15197                        filter_range: 0..matching_prefix.len(),
15198                    },
15199                    server_id: LanguageServerId(usize::MAX),
15200                    documentation: snippet
15201                        .description
15202                        .clone()
15203                        .map(CompletionDocumentation::SingleLine),
15204                    lsp_completion: lsp::CompletionItem {
15205                        label: snippet.prefix.first().unwrap().clone(),
15206                        kind: Some(CompletionItemKind::SNIPPET),
15207                        label_details: snippet.description.as_ref().map(|description| {
15208                            lsp::CompletionItemLabelDetails {
15209                                detail: Some(description.clone()),
15210                                description: None,
15211                            }
15212                        }),
15213                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15214                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15215                            lsp::InsertReplaceEdit {
15216                                new_text: snippet.body.clone(),
15217                                insert: lsp_range,
15218                                replace: lsp_range,
15219                            },
15220                        )),
15221                        filter_text: Some(snippet.body.clone()),
15222                        sort_text: Some(char::MAX.to_string()),
15223                        ..Default::default()
15224                    },
15225                    confirm: None,
15226                })
15227            })
15228            .collect();
15229
15230        Ok(result)
15231    })
15232}
15233
15234impl CompletionProvider for Entity<Project> {
15235    fn completions(
15236        &self,
15237        buffer: &Entity<Buffer>,
15238        buffer_position: text::Anchor,
15239        options: CompletionContext,
15240        _window: &mut Window,
15241        cx: &mut Context<Editor>,
15242    ) -> Task<Result<Vec<Completion>>> {
15243        self.update(cx, |project, cx| {
15244            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15245            let project_completions = project.completions(buffer, buffer_position, options, cx);
15246            cx.background_executor().spawn(async move {
15247                let mut completions = project_completions.await?;
15248                let snippets_completions = snippets.await?;
15249                completions.extend(snippets_completions);
15250                Ok(completions)
15251            })
15252        })
15253    }
15254
15255    fn resolve_completions(
15256        &self,
15257        buffer: Entity<Buffer>,
15258        completion_indices: Vec<usize>,
15259        completions: Rc<RefCell<Box<[Completion]>>>,
15260        cx: &mut Context<Editor>,
15261    ) -> Task<Result<bool>> {
15262        self.update(cx, |project, cx| {
15263            project.lsp_store().update(cx, |lsp_store, cx| {
15264                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15265            })
15266        })
15267    }
15268
15269    fn apply_additional_edits_for_completion(
15270        &self,
15271        buffer: Entity<Buffer>,
15272        completions: Rc<RefCell<Box<[Completion]>>>,
15273        completion_index: usize,
15274        push_to_history: bool,
15275        cx: &mut Context<Editor>,
15276    ) -> Task<Result<Option<language::Transaction>>> {
15277        self.update(cx, |project, cx| {
15278            project.lsp_store().update(cx, |lsp_store, cx| {
15279                lsp_store.apply_additional_edits_for_completion(
15280                    buffer,
15281                    completions,
15282                    completion_index,
15283                    push_to_history,
15284                    cx,
15285                )
15286            })
15287        })
15288    }
15289
15290    fn is_completion_trigger(
15291        &self,
15292        buffer: &Entity<Buffer>,
15293        position: language::Anchor,
15294        text: &str,
15295        trigger_in_words: bool,
15296        cx: &mut Context<Editor>,
15297    ) -> bool {
15298        let mut chars = text.chars();
15299        let char = if let Some(char) = chars.next() {
15300            char
15301        } else {
15302            return false;
15303        };
15304        if chars.next().is_some() {
15305            return false;
15306        }
15307
15308        let buffer = buffer.read(cx);
15309        let snapshot = buffer.snapshot();
15310        if !snapshot.settings_at(position, cx).show_completions_on_input {
15311            return false;
15312        }
15313        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15314        if trigger_in_words && classifier.is_word(char) {
15315            return true;
15316        }
15317
15318        buffer.completion_triggers().contains(text)
15319    }
15320}
15321
15322impl SemanticsProvider for Entity<Project> {
15323    fn hover(
15324        &self,
15325        buffer: &Entity<Buffer>,
15326        position: text::Anchor,
15327        cx: &mut App,
15328    ) -> Option<Task<Vec<project::Hover>>> {
15329        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15330    }
15331
15332    fn document_highlights(
15333        &self,
15334        buffer: &Entity<Buffer>,
15335        position: text::Anchor,
15336        cx: &mut App,
15337    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15338        Some(self.update(cx, |project, cx| {
15339            project.document_highlights(buffer, position, cx)
15340        }))
15341    }
15342
15343    fn definitions(
15344        &self,
15345        buffer: &Entity<Buffer>,
15346        position: text::Anchor,
15347        kind: GotoDefinitionKind,
15348        cx: &mut App,
15349    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15350        Some(self.update(cx, |project, cx| match kind {
15351            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15352            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15353            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15354            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15355        }))
15356    }
15357
15358    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15359        // TODO: make this work for remote projects
15360        self.read(cx)
15361            .language_servers_for_local_buffer(buffer.read(cx), cx)
15362            .any(
15363                |(_, server)| match server.capabilities().inlay_hint_provider {
15364                    Some(lsp::OneOf::Left(enabled)) => enabled,
15365                    Some(lsp::OneOf::Right(_)) => true,
15366                    None => false,
15367                },
15368            )
15369    }
15370
15371    fn inlay_hints(
15372        &self,
15373        buffer_handle: Entity<Buffer>,
15374        range: Range<text::Anchor>,
15375        cx: &mut App,
15376    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15377        Some(self.update(cx, |project, cx| {
15378            project.inlay_hints(buffer_handle, range, cx)
15379        }))
15380    }
15381
15382    fn resolve_inlay_hint(
15383        &self,
15384        hint: InlayHint,
15385        buffer_handle: Entity<Buffer>,
15386        server_id: LanguageServerId,
15387        cx: &mut App,
15388    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15389        Some(self.update(cx, |project, cx| {
15390            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15391        }))
15392    }
15393
15394    fn range_for_rename(
15395        &self,
15396        buffer: &Entity<Buffer>,
15397        position: text::Anchor,
15398        cx: &mut App,
15399    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15400        Some(self.update(cx, |project, cx| {
15401            let buffer = buffer.clone();
15402            let task = project.prepare_rename(buffer.clone(), position, cx);
15403            cx.spawn(|_, mut cx| async move {
15404                Ok(match task.await? {
15405                    PrepareRenameResponse::Success(range) => Some(range),
15406                    PrepareRenameResponse::InvalidPosition => None,
15407                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15408                        // Fallback on using TreeSitter info to determine identifier range
15409                        buffer.update(&mut cx, |buffer, _| {
15410                            let snapshot = buffer.snapshot();
15411                            let (range, kind) = snapshot.surrounding_word(position);
15412                            if kind != Some(CharKind::Word) {
15413                                return None;
15414                            }
15415                            Some(
15416                                snapshot.anchor_before(range.start)
15417                                    ..snapshot.anchor_after(range.end),
15418                            )
15419                        })?
15420                    }
15421                })
15422            })
15423        }))
15424    }
15425
15426    fn perform_rename(
15427        &self,
15428        buffer: &Entity<Buffer>,
15429        position: text::Anchor,
15430        new_name: String,
15431        cx: &mut App,
15432    ) -> Option<Task<Result<ProjectTransaction>>> {
15433        Some(self.update(cx, |project, cx| {
15434            project.perform_rename(buffer.clone(), position, new_name, cx)
15435        }))
15436    }
15437}
15438
15439fn inlay_hint_settings(
15440    location: Anchor,
15441    snapshot: &MultiBufferSnapshot,
15442    cx: &mut Context<Editor>,
15443) -> InlayHintSettings {
15444    let file = snapshot.file_at(location);
15445    let language = snapshot.language_at(location).map(|l| l.name());
15446    language_settings(language, file, cx).inlay_hints
15447}
15448
15449fn consume_contiguous_rows(
15450    contiguous_row_selections: &mut Vec<Selection<Point>>,
15451    selection: &Selection<Point>,
15452    display_map: &DisplaySnapshot,
15453    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15454) -> (MultiBufferRow, MultiBufferRow) {
15455    contiguous_row_selections.push(selection.clone());
15456    let start_row = MultiBufferRow(selection.start.row);
15457    let mut end_row = ending_row(selection, display_map);
15458
15459    while let Some(next_selection) = selections.peek() {
15460        if next_selection.start.row <= end_row.0 {
15461            end_row = ending_row(next_selection, display_map);
15462            contiguous_row_selections.push(selections.next().unwrap().clone());
15463        } else {
15464            break;
15465        }
15466    }
15467    (start_row, end_row)
15468}
15469
15470fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15471    if next_selection.end.column > 0 || next_selection.is_empty() {
15472        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15473    } else {
15474        MultiBufferRow(next_selection.end.row)
15475    }
15476}
15477
15478impl EditorSnapshot {
15479    pub fn remote_selections_in_range<'a>(
15480        &'a self,
15481        range: &'a Range<Anchor>,
15482        collaboration_hub: &dyn CollaborationHub,
15483        cx: &'a App,
15484    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15485        let participant_names = collaboration_hub.user_names(cx);
15486        let participant_indices = collaboration_hub.user_participant_indices(cx);
15487        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15488        let collaborators_by_replica_id = collaborators_by_peer_id
15489            .iter()
15490            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15491            .collect::<HashMap<_, _>>();
15492        self.buffer_snapshot
15493            .selections_in_range(range, false)
15494            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15495                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15496                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15497                let user_name = participant_names.get(&collaborator.user_id).cloned();
15498                Some(RemoteSelection {
15499                    replica_id,
15500                    selection,
15501                    cursor_shape,
15502                    line_mode,
15503                    participant_index,
15504                    peer_id: collaborator.peer_id,
15505                    user_name,
15506                })
15507            })
15508    }
15509
15510    pub fn hunks_for_ranges(
15511        &self,
15512        ranges: impl Iterator<Item = Range<Point>>,
15513    ) -> Vec<MultiBufferDiffHunk> {
15514        let mut hunks = Vec::new();
15515        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15516            HashMap::default();
15517        for query_range in ranges {
15518            let query_rows =
15519                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15520            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15521                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15522            ) {
15523                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15524                // when the caret is just above or just below the deleted hunk.
15525                let allow_adjacent = hunk.status().is_removed();
15526                let related_to_selection = if allow_adjacent {
15527                    hunk.row_range.overlaps(&query_rows)
15528                        || hunk.row_range.start == query_rows.end
15529                        || hunk.row_range.end == query_rows.start
15530                } else {
15531                    hunk.row_range.overlaps(&query_rows)
15532                };
15533                if related_to_selection {
15534                    if !processed_buffer_rows
15535                        .entry(hunk.buffer_id)
15536                        .or_default()
15537                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15538                    {
15539                        continue;
15540                    }
15541                    hunks.push(hunk);
15542                }
15543            }
15544        }
15545
15546        hunks
15547    }
15548
15549    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15550        self.display_snapshot.buffer_snapshot.language_at(position)
15551    }
15552
15553    pub fn is_focused(&self) -> bool {
15554        self.is_focused
15555    }
15556
15557    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15558        self.placeholder_text.as_ref()
15559    }
15560
15561    pub fn scroll_position(&self) -> gpui::Point<f32> {
15562        self.scroll_anchor.scroll_position(&self.display_snapshot)
15563    }
15564
15565    fn gutter_dimensions(
15566        &self,
15567        font_id: FontId,
15568        font_size: Pixels,
15569        max_line_number_width: Pixels,
15570        cx: &App,
15571    ) -> Option<GutterDimensions> {
15572        if !self.show_gutter {
15573            return None;
15574        }
15575
15576        let descent = cx.text_system().descent(font_id, font_size);
15577        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15578        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15579
15580        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15581            matches!(
15582                ProjectSettings::get_global(cx).git.git_gutter,
15583                Some(GitGutterSetting::TrackedFiles)
15584            )
15585        });
15586        let gutter_settings = EditorSettings::get_global(cx).gutter;
15587        let show_line_numbers = self
15588            .show_line_numbers
15589            .unwrap_or(gutter_settings.line_numbers);
15590        let line_gutter_width = if show_line_numbers {
15591            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15592            let min_width_for_number_on_gutter = em_advance * 4.0;
15593            max_line_number_width.max(min_width_for_number_on_gutter)
15594        } else {
15595            0.0.into()
15596        };
15597
15598        let show_code_actions = self
15599            .show_code_actions
15600            .unwrap_or(gutter_settings.code_actions);
15601
15602        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15603
15604        let git_blame_entries_width =
15605            self.git_blame_gutter_max_author_length
15606                .map(|max_author_length| {
15607                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15608
15609                    /// The number of characters to dedicate to gaps and margins.
15610                    const SPACING_WIDTH: usize = 4;
15611
15612                    let max_char_count = max_author_length
15613                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15614                        + ::git::SHORT_SHA_LENGTH
15615                        + MAX_RELATIVE_TIMESTAMP.len()
15616                        + SPACING_WIDTH;
15617
15618                    em_advance * max_char_count
15619                });
15620
15621        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15622        left_padding += if show_code_actions || show_runnables {
15623            em_width * 3.0
15624        } else if show_git_gutter && show_line_numbers {
15625            em_width * 2.0
15626        } else if show_git_gutter || show_line_numbers {
15627            em_width
15628        } else {
15629            px(0.)
15630        };
15631
15632        let right_padding = if gutter_settings.folds && show_line_numbers {
15633            em_width * 4.0
15634        } else if gutter_settings.folds {
15635            em_width * 3.0
15636        } else if show_line_numbers {
15637            em_width
15638        } else {
15639            px(0.)
15640        };
15641
15642        Some(GutterDimensions {
15643            left_padding,
15644            right_padding,
15645            width: line_gutter_width + left_padding + right_padding,
15646            margin: -descent,
15647            git_blame_entries_width,
15648        })
15649    }
15650
15651    pub fn render_crease_toggle(
15652        &self,
15653        buffer_row: MultiBufferRow,
15654        row_contains_cursor: bool,
15655        editor: Entity<Editor>,
15656        window: &mut Window,
15657        cx: &mut App,
15658    ) -> Option<AnyElement> {
15659        let folded = self.is_line_folded(buffer_row);
15660        let mut is_foldable = false;
15661
15662        if let Some(crease) = self
15663            .crease_snapshot
15664            .query_row(buffer_row, &self.buffer_snapshot)
15665        {
15666            is_foldable = true;
15667            match crease {
15668                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15669                    if let Some(render_toggle) = render_toggle {
15670                        let toggle_callback =
15671                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15672                                if folded {
15673                                    editor.update(cx, |editor, cx| {
15674                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15675                                    });
15676                                } else {
15677                                    editor.update(cx, |editor, cx| {
15678                                        editor.unfold_at(
15679                                            &crate::UnfoldAt { buffer_row },
15680                                            window,
15681                                            cx,
15682                                        )
15683                                    });
15684                                }
15685                            });
15686                        return Some((render_toggle)(
15687                            buffer_row,
15688                            folded,
15689                            toggle_callback,
15690                            window,
15691                            cx,
15692                        ));
15693                    }
15694                }
15695            }
15696        }
15697
15698        is_foldable |= self.starts_indent(buffer_row);
15699
15700        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15701            Some(
15702                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15703                    .toggle_state(folded)
15704                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15705                        if folded {
15706                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15707                        } else {
15708                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15709                        }
15710                    }))
15711                    .into_any_element(),
15712            )
15713        } else {
15714            None
15715        }
15716    }
15717
15718    pub fn render_crease_trailer(
15719        &self,
15720        buffer_row: MultiBufferRow,
15721        window: &mut Window,
15722        cx: &mut App,
15723    ) -> Option<AnyElement> {
15724        let folded = self.is_line_folded(buffer_row);
15725        if let Crease::Inline { render_trailer, .. } = self
15726            .crease_snapshot
15727            .query_row(buffer_row, &self.buffer_snapshot)?
15728        {
15729            let render_trailer = render_trailer.as_ref()?;
15730            Some(render_trailer(buffer_row, folded, window, cx))
15731        } else {
15732            None
15733        }
15734    }
15735}
15736
15737impl Deref for EditorSnapshot {
15738    type Target = DisplaySnapshot;
15739
15740    fn deref(&self) -> &Self::Target {
15741        &self.display_snapshot
15742    }
15743}
15744
15745#[derive(Clone, Debug, PartialEq, Eq)]
15746pub enum EditorEvent {
15747    InputIgnored {
15748        text: Arc<str>,
15749    },
15750    InputHandled {
15751        utf16_range_to_replace: Option<Range<isize>>,
15752        text: Arc<str>,
15753    },
15754    ExcerptsAdded {
15755        buffer: Entity<Buffer>,
15756        predecessor: ExcerptId,
15757        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15758    },
15759    ExcerptsRemoved {
15760        ids: Vec<ExcerptId>,
15761    },
15762    BufferFoldToggled {
15763        ids: Vec<ExcerptId>,
15764        folded: bool,
15765    },
15766    ExcerptsEdited {
15767        ids: Vec<ExcerptId>,
15768    },
15769    ExcerptsExpanded {
15770        ids: Vec<ExcerptId>,
15771    },
15772    BufferEdited,
15773    Edited {
15774        transaction_id: clock::Lamport,
15775    },
15776    Reparsed(BufferId),
15777    Focused,
15778    FocusedIn,
15779    Blurred,
15780    DirtyChanged,
15781    Saved,
15782    TitleChanged,
15783    DiffBaseChanged,
15784    SelectionsChanged {
15785        local: bool,
15786    },
15787    ScrollPositionChanged {
15788        local: bool,
15789        autoscroll: bool,
15790    },
15791    Closed,
15792    TransactionUndone {
15793        transaction_id: clock::Lamport,
15794    },
15795    TransactionBegun {
15796        transaction_id: clock::Lamport,
15797    },
15798    Reloaded,
15799    CursorShapeChanged,
15800}
15801
15802impl EventEmitter<EditorEvent> for Editor {}
15803
15804impl Focusable for Editor {
15805    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15806        self.focus_handle.clone()
15807    }
15808}
15809
15810impl Render for Editor {
15811    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15812        let settings = ThemeSettings::get_global(cx);
15813
15814        let mut text_style = match self.mode {
15815            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15816                color: cx.theme().colors().editor_foreground,
15817                font_family: settings.ui_font.family.clone(),
15818                font_features: settings.ui_font.features.clone(),
15819                font_fallbacks: settings.ui_font.fallbacks.clone(),
15820                font_size: rems(0.875).into(),
15821                font_weight: settings.ui_font.weight,
15822                line_height: relative(settings.buffer_line_height.value()),
15823                ..Default::default()
15824            },
15825            EditorMode::Full => TextStyle {
15826                color: cx.theme().colors().editor_foreground,
15827                font_family: settings.buffer_font.family.clone(),
15828                font_features: settings.buffer_font.features.clone(),
15829                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15830                font_size: settings.buffer_font_size().into(),
15831                font_weight: settings.buffer_font.weight,
15832                line_height: relative(settings.buffer_line_height.value()),
15833                ..Default::default()
15834            },
15835        };
15836        if let Some(text_style_refinement) = &self.text_style_refinement {
15837            text_style.refine(text_style_refinement)
15838        }
15839
15840        let background = match self.mode {
15841            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15842            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15843            EditorMode::Full => cx.theme().colors().editor_background,
15844        };
15845
15846        EditorElement::new(
15847            &cx.entity(),
15848            EditorStyle {
15849                background,
15850                local_player: cx.theme().players().local(),
15851                text: text_style,
15852                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15853                syntax: cx.theme().syntax().clone(),
15854                status: cx.theme().status().clone(),
15855                inlay_hints_style: make_inlay_hints_style(cx),
15856                inline_completion_styles: make_suggestion_styles(cx),
15857                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15858            },
15859        )
15860    }
15861}
15862
15863impl EntityInputHandler for Editor {
15864    fn text_for_range(
15865        &mut self,
15866        range_utf16: Range<usize>,
15867        adjusted_range: &mut Option<Range<usize>>,
15868        _: &mut Window,
15869        cx: &mut Context<Self>,
15870    ) -> Option<String> {
15871        let snapshot = self.buffer.read(cx).read(cx);
15872        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15873        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15874        if (start.0..end.0) != range_utf16 {
15875            adjusted_range.replace(start.0..end.0);
15876        }
15877        Some(snapshot.text_for_range(start..end).collect())
15878    }
15879
15880    fn selected_text_range(
15881        &mut self,
15882        ignore_disabled_input: bool,
15883        _: &mut Window,
15884        cx: &mut Context<Self>,
15885    ) -> Option<UTF16Selection> {
15886        // Prevent the IME menu from appearing when holding down an alphabetic key
15887        // while input is disabled.
15888        if !ignore_disabled_input && !self.input_enabled {
15889            return None;
15890        }
15891
15892        let selection = self.selections.newest::<OffsetUtf16>(cx);
15893        let range = selection.range();
15894
15895        Some(UTF16Selection {
15896            range: range.start.0..range.end.0,
15897            reversed: selection.reversed,
15898        })
15899    }
15900
15901    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15902        let snapshot = self.buffer.read(cx).read(cx);
15903        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15904        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15905    }
15906
15907    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15908        self.clear_highlights::<InputComposition>(cx);
15909        self.ime_transaction.take();
15910    }
15911
15912    fn replace_text_in_range(
15913        &mut self,
15914        range_utf16: Option<Range<usize>>,
15915        text: &str,
15916        window: &mut Window,
15917        cx: &mut Context<Self>,
15918    ) {
15919        if !self.input_enabled {
15920            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15921            return;
15922        }
15923
15924        self.transact(window, cx, |this, window, cx| {
15925            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15926                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15927                Some(this.selection_replacement_ranges(range_utf16, cx))
15928            } else {
15929                this.marked_text_ranges(cx)
15930            };
15931
15932            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15933                let newest_selection_id = this.selections.newest_anchor().id;
15934                this.selections
15935                    .all::<OffsetUtf16>(cx)
15936                    .iter()
15937                    .zip(ranges_to_replace.iter())
15938                    .find_map(|(selection, range)| {
15939                        if selection.id == newest_selection_id {
15940                            Some(
15941                                (range.start.0 as isize - selection.head().0 as isize)
15942                                    ..(range.end.0 as isize - selection.head().0 as isize),
15943                            )
15944                        } else {
15945                            None
15946                        }
15947                    })
15948            });
15949
15950            cx.emit(EditorEvent::InputHandled {
15951                utf16_range_to_replace: range_to_replace,
15952                text: text.into(),
15953            });
15954
15955            if let Some(new_selected_ranges) = new_selected_ranges {
15956                this.change_selections(None, window, cx, |selections| {
15957                    selections.select_ranges(new_selected_ranges)
15958                });
15959                this.backspace(&Default::default(), window, cx);
15960            }
15961
15962            this.handle_input(text, window, cx);
15963        });
15964
15965        if let Some(transaction) = self.ime_transaction {
15966            self.buffer.update(cx, |buffer, cx| {
15967                buffer.group_until_transaction(transaction, cx);
15968            });
15969        }
15970
15971        self.unmark_text(window, cx);
15972    }
15973
15974    fn replace_and_mark_text_in_range(
15975        &mut self,
15976        range_utf16: Option<Range<usize>>,
15977        text: &str,
15978        new_selected_range_utf16: Option<Range<usize>>,
15979        window: &mut Window,
15980        cx: &mut Context<Self>,
15981    ) {
15982        if !self.input_enabled {
15983            return;
15984        }
15985
15986        let transaction = self.transact(window, cx, |this, window, cx| {
15987            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15988                let snapshot = this.buffer.read(cx).read(cx);
15989                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15990                    for marked_range in &mut marked_ranges {
15991                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15992                        marked_range.start.0 += relative_range_utf16.start;
15993                        marked_range.start =
15994                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15995                        marked_range.end =
15996                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15997                    }
15998                }
15999                Some(marked_ranges)
16000            } else if let Some(range_utf16) = range_utf16 {
16001                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16002                Some(this.selection_replacement_ranges(range_utf16, cx))
16003            } else {
16004                None
16005            };
16006
16007            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16008                let newest_selection_id = this.selections.newest_anchor().id;
16009                this.selections
16010                    .all::<OffsetUtf16>(cx)
16011                    .iter()
16012                    .zip(ranges_to_replace.iter())
16013                    .find_map(|(selection, range)| {
16014                        if selection.id == newest_selection_id {
16015                            Some(
16016                                (range.start.0 as isize - selection.head().0 as isize)
16017                                    ..(range.end.0 as isize - selection.head().0 as isize),
16018                            )
16019                        } else {
16020                            None
16021                        }
16022                    })
16023            });
16024
16025            cx.emit(EditorEvent::InputHandled {
16026                utf16_range_to_replace: range_to_replace,
16027                text: text.into(),
16028            });
16029
16030            if let Some(ranges) = ranges_to_replace {
16031                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16032            }
16033
16034            let marked_ranges = {
16035                let snapshot = this.buffer.read(cx).read(cx);
16036                this.selections
16037                    .disjoint_anchors()
16038                    .iter()
16039                    .map(|selection| {
16040                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16041                    })
16042                    .collect::<Vec<_>>()
16043            };
16044
16045            if text.is_empty() {
16046                this.unmark_text(window, cx);
16047            } else {
16048                this.highlight_text::<InputComposition>(
16049                    marked_ranges.clone(),
16050                    HighlightStyle {
16051                        underline: Some(UnderlineStyle {
16052                            thickness: px(1.),
16053                            color: None,
16054                            wavy: false,
16055                        }),
16056                        ..Default::default()
16057                    },
16058                    cx,
16059                );
16060            }
16061
16062            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16063            let use_autoclose = this.use_autoclose;
16064            let use_auto_surround = this.use_auto_surround;
16065            this.set_use_autoclose(false);
16066            this.set_use_auto_surround(false);
16067            this.handle_input(text, window, cx);
16068            this.set_use_autoclose(use_autoclose);
16069            this.set_use_auto_surround(use_auto_surround);
16070
16071            if let Some(new_selected_range) = new_selected_range_utf16 {
16072                let snapshot = this.buffer.read(cx).read(cx);
16073                let new_selected_ranges = marked_ranges
16074                    .into_iter()
16075                    .map(|marked_range| {
16076                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16077                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16078                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16079                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16080                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16081                    })
16082                    .collect::<Vec<_>>();
16083
16084                drop(snapshot);
16085                this.change_selections(None, window, cx, |selections| {
16086                    selections.select_ranges(new_selected_ranges)
16087                });
16088            }
16089        });
16090
16091        self.ime_transaction = self.ime_transaction.or(transaction);
16092        if let Some(transaction) = self.ime_transaction {
16093            self.buffer.update(cx, |buffer, cx| {
16094                buffer.group_until_transaction(transaction, cx);
16095            });
16096        }
16097
16098        if self.text_highlights::<InputComposition>(cx).is_none() {
16099            self.ime_transaction.take();
16100        }
16101    }
16102
16103    fn bounds_for_range(
16104        &mut self,
16105        range_utf16: Range<usize>,
16106        element_bounds: gpui::Bounds<Pixels>,
16107        window: &mut Window,
16108        cx: &mut Context<Self>,
16109    ) -> Option<gpui::Bounds<Pixels>> {
16110        let text_layout_details = self.text_layout_details(window);
16111        let gpui::Size {
16112            width: em_width,
16113            height: line_height,
16114        } = self.character_size(window);
16115
16116        let snapshot = self.snapshot(window, cx);
16117        let scroll_position = snapshot.scroll_position();
16118        let scroll_left = scroll_position.x * em_width;
16119
16120        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16121        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16122            + self.gutter_dimensions.width
16123            + self.gutter_dimensions.margin;
16124        let y = line_height * (start.row().as_f32() - scroll_position.y);
16125
16126        Some(Bounds {
16127            origin: element_bounds.origin + point(x, y),
16128            size: size(em_width, line_height),
16129        })
16130    }
16131
16132    fn character_index_for_point(
16133        &mut self,
16134        point: gpui::Point<Pixels>,
16135        _window: &mut Window,
16136        _cx: &mut Context<Self>,
16137    ) -> Option<usize> {
16138        let position_map = self.last_position_map.as_ref()?;
16139        if !position_map.text_hitbox.contains(&point) {
16140            return None;
16141        }
16142        let display_point = position_map.point_for_position(point).previous_valid;
16143        let anchor = position_map
16144            .snapshot
16145            .display_point_to_anchor(display_point, Bias::Left);
16146        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16147        Some(utf16_offset.0)
16148    }
16149}
16150
16151trait SelectionExt {
16152    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16153    fn spanned_rows(
16154        &self,
16155        include_end_if_at_line_start: bool,
16156        map: &DisplaySnapshot,
16157    ) -> Range<MultiBufferRow>;
16158}
16159
16160impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16161    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16162        let start = self
16163            .start
16164            .to_point(&map.buffer_snapshot)
16165            .to_display_point(map);
16166        let end = self
16167            .end
16168            .to_point(&map.buffer_snapshot)
16169            .to_display_point(map);
16170        if self.reversed {
16171            end..start
16172        } else {
16173            start..end
16174        }
16175    }
16176
16177    fn spanned_rows(
16178        &self,
16179        include_end_if_at_line_start: bool,
16180        map: &DisplaySnapshot,
16181    ) -> Range<MultiBufferRow> {
16182        let start = self.start.to_point(&map.buffer_snapshot);
16183        let mut end = self.end.to_point(&map.buffer_snapshot);
16184        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16185            end.row -= 1;
16186        }
16187
16188        let buffer_start = map.prev_line_boundary(start).0;
16189        let buffer_end = map.next_line_boundary(end).0;
16190        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16191    }
16192}
16193
16194impl<T: InvalidationRegion> InvalidationStack<T> {
16195    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16196    where
16197        S: Clone + ToOffset,
16198    {
16199        while let Some(region) = self.last() {
16200            let all_selections_inside_invalidation_ranges =
16201                if selections.len() == region.ranges().len() {
16202                    selections
16203                        .iter()
16204                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16205                        .all(|(selection, invalidation_range)| {
16206                            let head = selection.head().to_offset(buffer);
16207                            invalidation_range.start <= head && invalidation_range.end >= head
16208                        })
16209                } else {
16210                    false
16211                };
16212
16213            if all_selections_inside_invalidation_ranges {
16214                break;
16215            } else {
16216                self.pop();
16217            }
16218        }
16219    }
16220}
16221
16222impl<T> Default for InvalidationStack<T> {
16223    fn default() -> Self {
16224        Self(Default::default())
16225    }
16226}
16227
16228impl<T> Deref for InvalidationStack<T> {
16229    type Target = Vec<T>;
16230
16231    fn deref(&self) -> &Self::Target {
16232        &self.0
16233    }
16234}
16235
16236impl<T> DerefMut for InvalidationStack<T> {
16237    fn deref_mut(&mut self) -> &mut Self::Target {
16238        &mut self.0
16239    }
16240}
16241
16242impl InvalidationRegion for SnippetState {
16243    fn ranges(&self) -> &[Range<Anchor>] {
16244        &self.ranges[self.active_index]
16245    }
16246}
16247
16248pub fn diagnostic_block_renderer(
16249    diagnostic: Diagnostic,
16250    max_message_rows: Option<u8>,
16251    allow_closing: bool,
16252    _is_valid: bool,
16253) -> RenderBlock {
16254    let (text_without_backticks, code_ranges) =
16255        highlight_diagnostic_message(&diagnostic, max_message_rows);
16256
16257    Arc::new(move |cx: &mut BlockContext| {
16258        let group_id: SharedString = cx.block_id.to_string().into();
16259
16260        let mut text_style = cx.window.text_style().clone();
16261        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16262        let theme_settings = ThemeSettings::get_global(cx);
16263        text_style.font_family = theme_settings.buffer_font.family.clone();
16264        text_style.font_style = theme_settings.buffer_font.style;
16265        text_style.font_features = theme_settings.buffer_font.features.clone();
16266        text_style.font_weight = theme_settings.buffer_font.weight;
16267
16268        let multi_line_diagnostic = diagnostic.message.contains('\n');
16269
16270        let buttons = |diagnostic: &Diagnostic| {
16271            if multi_line_diagnostic {
16272                v_flex()
16273            } else {
16274                h_flex()
16275            }
16276            .when(allow_closing, |div| {
16277                div.children(diagnostic.is_primary.then(|| {
16278                    IconButton::new("close-block", IconName::XCircle)
16279                        .icon_color(Color::Muted)
16280                        .size(ButtonSize::Compact)
16281                        .style(ButtonStyle::Transparent)
16282                        .visible_on_hover(group_id.clone())
16283                        .on_click(move |_click, window, cx| {
16284                            window.dispatch_action(Box::new(Cancel), cx)
16285                        })
16286                        .tooltip(|window, cx| {
16287                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16288                        })
16289                }))
16290            })
16291            .child(
16292                IconButton::new("copy-block", IconName::Copy)
16293                    .icon_color(Color::Muted)
16294                    .size(ButtonSize::Compact)
16295                    .style(ButtonStyle::Transparent)
16296                    .visible_on_hover(group_id.clone())
16297                    .on_click({
16298                        let message = diagnostic.message.clone();
16299                        move |_click, _, cx| {
16300                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16301                        }
16302                    })
16303                    .tooltip(Tooltip::text("Copy diagnostic message")),
16304            )
16305        };
16306
16307        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16308            AvailableSpace::min_size(),
16309            cx.window,
16310            cx.app,
16311        );
16312
16313        h_flex()
16314            .id(cx.block_id)
16315            .group(group_id.clone())
16316            .relative()
16317            .size_full()
16318            .block_mouse_down()
16319            .pl(cx.gutter_dimensions.width)
16320            .w(cx.max_width - cx.gutter_dimensions.full_width())
16321            .child(
16322                div()
16323                    .flex()
16324                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16325                    .flex_shrink(),
16326            )
16327            .child(buttons(&diagnostic))
16328            .child(div().flex().flex_shrink_0().child(
16329                StyledText::new(text_without_backticks.clone()).with_highlights(
16330                    &text_style,
16331                    code_ranges.iter().map(|range| {
16332                        (
16333                            range.clone(),
16334                            HighlightStyle {
16335                                font_weight: Some(FontWeight::BOLD),
16336                                ..Default::default()
16337                            },
16338                        )
16339                    }),
16340                ),
16341            ))
16342            .into_any_element()
16343    })
16344}
16345
16346fn inline_completion_edit_text(
16347    current_snapshot: &BufferSnapshot,
16348    edits: &[(Range<Anchor>, String)],
16349    edit_preview: &EditPreview,
16350    include_deletions: bool,
16351    cx: &App,
16352) -> HighlightedText {
16353    let edits = edits
16354        .iter()
16355        .map(|(anchor, text)| {
16356            (
16357                anchor.start.text_anchor..anchor.end.text_anchor,
16358                text.clone(),
16359            )
16360        })
16361        .collect::<Vec<_>>();
16362
16363    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16364}
16365
16366pub fn highlight_diagnostic_message(
16367    diagnostic: &Diagnostic,
16368    mut max_message_rows: Option<u8>,
16369) -> (SharedString, Vec<Range<usize>>) {
16370    let mut text_without_backticks = String::new();
16371    let mut code_ranges = Vec::new();
16372
16373    if let Some(source) = &diagnostic.source {
16374        text_without_backticks.push_str(source);
16375        code_ranges.push(0..source.len());
16376        text_without_backticks.push_str(": ");
16377    }
16378
16379    let mut prev_offset = 0;
16380    let mut in_code_block = false;
16381    let has_row_limit = max_message_rows.is_some();
16382    let mut newline_indices = diagnostic
16383        .message
16384        .match_indices('\n')
16385        .filter(|_| has_row_limit)
16386        .map(|(ix, _)| ix)
16387        .fuse()
16388        .peekable();
16389
16390    for (quote_ix, _) in diagnostic
16391        .message
16392        .match_indices('`')
16393        .chain([(diagnostic.message.len(), "")])
16394    {
16395        let mut first_newline_ix = None;
16396        let mut last_newline_ix = None;
16397        while let Some(newline_ix) = newline_indices.peek() {
16398            if *newline_ix < quote_ix {
16399                if first_newline_ix.is_none() {
16400                    first_newline_ix = Some(*newline_ix);
16401                }
16402                last_newline_ix = Some(*newline_ix);
16403
16404                if let Some(rows_left) = &mut max_message_rows {
16405                    if *rows_left == 0 {
16406                        break;
16407                    } else {
16408                        *rows_left -= 1;
16409                    }
16410                }
16411                let _ = newline_indices.next();
16412            } else {
16413                break;
16414            }
16415        }
16416        let prev_len = text_without_backticks.len();
16417        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16418        text_without_backticks.push_str(new_text);
16419        if in_code_block {
16420            code_ranges.push(prev_len..text_without_backticks.len());
16421        }
16422        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16423        in_code_block = !in_code_block;
16424        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16425            text_without_backticks.push_str("...");
16426            break;
16427        }
16428    }
16429
16430    (text_without_backticks.into(), code_ranges)
16431}
16432
16433fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16434    match severity {
16435        DiagnosticSeverity::ERROR => colors.error,
16436        DiagnosticSeverity::WARNING => colors.warning,
16437        DiagnosticSeverity::INFORMATION => colors.info,
16438        DiagnosticSeverity::HINT => colors.info,
16439        _ => colors.ignored,
16440    }
16441}
16442
16443pub fn styled_runs_for_code_label<'a>(
16444    label: &'a CodeLabel,
16445    syntax_theme: &'a theme::SyntaxTheme,
16446) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16447    let fade_out = HighlightStyle {
16448        fade_out: Some(0.35),
16449        ..Default::default()
16450    };
16451
16452    let mut prev_end = label.filter_range.end;
16453    label
16454        .runs
16455        .iter()
16456        .enumerate()
16457        .flat_map(move |(ix, (range, highlight_id))| {
16458            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16459                style
16460            } else {
16461                return Default::default();
16462            };
16463            let mut muted_style = style;
16464            muted_style.highlight(fade_out);
16465
16466            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16467            if range.start >= label.filter_range.end {
16468                if range.start > prev_end {
16469                    runs.push((prev_end..range.start, fade_out));
16470                }
16471                runs.push((range.clone(), muted_style));
16472            } else if range.end <= label.filter_range.end {
16473                runs.push((range.clone(), style));
16474            } else {
16475                runs.push((range.start..label.filter_range.end, style));
16476                runs.push((label.filter_range.end..range.end, muted_style));
16477            }
16478            prev_end = cmp::max(prev_end, range.end);
16479
16480            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16481                runs.push((prev_end..label.text.len(), fade_out));
16482            }
16483
16484            runs
16485        })
16486}
16487
16488pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16489    let mut prev_index = 0;
16490    let mut prev_codepoint: Option<char> = None;
16491    text.char_indices()
16492        .chain([(text.len(), '\0')])
16493        .filter_map(move |(index, codepoint)| {
16494            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16495            let is_boundary = index == text.len()
16496                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16497                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16498            if is_boundary {
16499                let chunk = &text[prev_index..index];
16500                prev_index = index;
16501                Some(chunk)
16502            } else {
16503                None
16504            }
16505        })
16506}
16507
16508pub trait RangeToAnchorExt: Sized {
16509    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16510
16511    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16512        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16513        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16514    }
16515}
16516
16517impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16518    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16519        let start_offset = self.start.to_offset(snapshot);
16520        let end_offset = self.end.to_offset(snapshot);
16521        if start_offset == end_offset {
16522            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16523        } else {
16524            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16525        }
16526    }
16527}
16528
16529pub trait RowExt {
16530    fn as_f32(&self) -> f32;
16531
16532    fn next_row(&self) -> Self;
16533
16534    fn previous_row(&self) -> Self;
16535
16536    fn minus(&self, other: Self) -> u32;
16537}
16538
16539impl RowExt for DisplayRow {
16540    fn as_f32(&self) -> f32 {
16541        self.0 as f32
16542    }
16543
16544    fn next_row(&self) -> Self {
16545        Self(self.0 + 1)
16546    }
16547
16548    fn previous_row(&self) -> Self {
16549        Self(self.0.saturating_sub(1))
16550    }
16551
16552    fn minus(&self, other: Self) -> u32 {
16553        self.0 - other.0
16554    }
16555}
16556
16557impl RowExt for MultiBufferRow {
16558    fn as_f32(&self) -> f32 {
16559        self.0 as f32
16560    }
16561
16562    fn next_row(&self) -> Self {
16563        Self(self.0 + 1)
16564    }
16565
16566    fn previous_row(&self) -> Self {
16567        Self(self.0.saturating_sub(1))
16568    }
16569
16570    fn minus(&self, other: Self) -> u32 {
16571        self.0 - other.0
16572    }
16573}
16574
16575trait RowRangeExt {
16576    type Row;
16577
16578    fn len(&self) -> usize;
16579
16580    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16581}
16582
16583impl RowRangeExt for Range<MultiBufferRow> {
16584    type Row = MultiBufferRow;
16585
16586    fn len(&self) -> usize {
16587        (self.end.0 - self.start.0) as usize
16588    }
16589
16590    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16591        (self.start.0..self.end.0).map(MultiBufferRow)
16592    }
16593}
16594
16595impl RowRangeExt for Range<DisplayRow> {
16596    type Row = DisplayRow;
16597
16598    fn len(&self) -> usize {
16599        (self.end.0 - self.start.0) as usize
16600    }
16601
16602    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16603        (self.start.0..self.end.0).map(DisplayRow)
16604    }
16605}
16606
16607/// If select range has more than one line, we
16608/// just point the cursor to range.start.
16609fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16610    if range.start.row == range.end.row {
16611        range
16612    } else {
16613        range.start..range.start
16614    }
16615}
16616pub struct KillRing(ClipboardItem);
16617impl Global for KillRing {}
16618
16619const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16620
16621fn all_edits_insertions_or_deletions(
16622    edits: &Vec<(Range<Anchor>, String)>,
16623    snapshot: &MultiBufferSnapshot,
16624) -> bool {
16625    let mut all_insertions = true;
16626    let mut all_deletions = true;
16627
16628    for (range, new_text) in edits.iter() {
16629        let range_is_empty = range.to_offset(&snapshot).is_empty();
16630        let text_is_empty = new_text.is_empty();
16631
16632        if range_is_empty != text_is_empty {
16633            if range_is_empty {
16634                all_deletions = false;
16635            } else {
16636                all_insertions = false;
16637            }
16638        } else {
16639            return false;
16640        }
16641
16642        if !all_insertions && !all_deletions {
16643            return false;
16644        }
16645    }
16646    all_insertions || all_deletions
16647}