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, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   79    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   80    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   81    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   82    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   83    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   84    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   85    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, EditPredictionsMode, EditPreview,
   99    HighlightedText, IndentKind, IndentSize, 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        snapshot: BufferSnapshot,
  489    },
  490}
  491
  492struct InlineCompletionState {
  493    inlay_ids: Vec<InlayId>,
  494    completion: InlineCompletion,
  495    completion_id: Option<SharedString>,
  496    invalidation_range: Range<Anchor>,
  497}
  498
  499enum EditPredictionSettings {
  500    Disabled,
  501    Enabled {
  502        show_in_menu: bool,
  503        preview_requires_modifier: bool,
  504    },
  505}
  506
  507impl EditPredictionSettings {
  508    pub fn is_enabled(&self) -> bool {
  509        match self {
  510            EditPredictionSettings::Disabled => false,
  511            EditPredictionSettings::Enabled { .. } => true,
  512        }
  513    }
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518pub enum MenuInlineCompletionsPolicy {
  519    Never,
  520    ByProvider,
  521}
  522
  523pub enum EditPredictionPreview {
  524    /// Modifier is not pressed
  525    Inactive,
  526    /// Modifier pressed
  527    Active {
  528        previous_scroll_position: Option<ScrollAnchor>,
  529    },
  530}
  531
  532#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  533struct EditorActionId(usize);
  534
  535impl EditorActionId {
  536    pub fn post_inc(&mut self) -> Self {
  537        let answer = self.0;
  538
  539        *self = Self(answer + 1);
  540
  541        Self(answer)
  542    }
  543}
  544
  545// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  546// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  547
  548type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  549type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  550
  551#[derive(Default)]
  552struct ScrollbarMarkerState {
  553    scrollbar_size: Size<Pixels>,
  554    dirty: bool,
  555    markers: Arc<[PaintQuad]>,
  556    pending_refresh: Option<Task<Result<()>>>,
  557}
  558
  559impl ScrollbarMarkerState {
  560    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  561        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  562    }
  563}
  564
  565#[derive(Clone, Debug)]
  566struct RunnableTasks {
  567    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  568    offset: MultiBufferOffset,
  569    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  570    column: u32,
  571    // Values of all named captures, including those starting with '_'
  572    extra_variables: HashMap<String, String>,
  573    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  574    context_range: Range<BufferOffset>,
  575}
  576
  577impl RunnableTasks {
  578    fn resolve<'a>(
  579        &'a self,
  580        cx: &'a task::TaskContext,
  581    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  582        self.templates.iter().filter_map(|(kind, template)| {
  583            template
  584                .resolve_task(&kind.to_id_base(), cx)
  585                .map(|task| (kind.clone(), task))
  586        })
  587    }
  588}
  589
  590#[derive(Clone)]
  591struct ResolvedTasks {
  592    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  593    position: Anchor,
  594}
  595#[derive(Copy, Clone, Debug)]
  596struct MultiBufferOffset(usize);
  597#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  598struct BufferOffset(usize);
  599
  600// Addons allow storing per-editor state in other crates (e.g. Vim)
  601pub trait Addon: 'static {
  602    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  603
  604    fn render_buffer_header_controls(
  605        &self,
  606        _: &ExcerptInfo,
  607        _: &Window,
  608        _: &App,
  609    ) -> Option<AnyElement> {
  610        None
  611    }
  612
  613    fn to_any(&self) -> &dyn std::any::Any;
  614}
  615
  616#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  617pub enum IsVimMode {
  618    Yes,
  619    No,
  620}
  621
  622/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  623///
  624/// See the [module level documentation](self) for more information.
  625pub struct Editor {
  626    focus_handle: FocusHandle,
  627    last_focused_descendant: Option<WeakFocusHandle>,
  628    /// The text buffer being edited
  629    buffer: Entity<MultiBuffer>,
  630    /// Map of how text in the buffer should be displayed.
  631    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  632    pub display_map: Entity<DisplayMap>,
  633    pub selections: SelectionsCollection,
  634    pub scroll_manager: ScrollManager,
  635    /// When inline assist editors are linked, they all render cursors because
  636    /// typing enters text into each of them, even the ones that aren't focused.
  637    pub(crate) show_cursor_when_unfocused: bool,
  638    columnar_selection_tail: Option<Anchor>,
  639    add_selections_state: Option<AddSelectionsState>,
  640    select_next_state: Option<SelectNextState>,
  641    select_prev_state: Option<SelectNextState>,
  642    selection_history: SelectionHistory,
  643    autoclose_regions: Vec<AutocloseRegion>,
  644    snippet_stack: InvalidationStack<SnippetState>,
  645    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  646    ime_transaction: Option<TransactionId>,
  647    active_diagnostics: Option<ActiveDiagnosticGroup>,
  648    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  649
  650    // TODO: make this a access method
  651    pub project: Option<Entity<Project>>,
  652    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  653    completion_provider: Option<Box<dyn CompletionProvider>>,
  654    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  655    blink_manager: Entity<BlinkManager>,
  656    show_cursor_names: bool,
  657    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  658    pub show_local_selections: bool,
  659    mode: EditorMode,
  660    show_breadcrumbs: bool,
  661    show_gutter: bool,
  662    show_scrollbars: bool,
  663    show_line_numbers: Option<bool>,
  664    use_relative_line_numbers: Option<bool>,
  665    show_git_diff_gutter: Option<bool>,
  666    show_code_actions: Option<bool>,
  667    show_runnables: Option<bool>,
  668    show_wrap_guides: Option<bool>,
  669    show_indent_guides: Option<bool>,
  670    placeholder_text: Option<Arc<str>>,
  671    highlight_order: usize,
  672    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  673    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  674    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  675    scrollbar_marker_state: ScrollbarMarkerState,
  676    active_indent_guides_state: ActiveIndentGuidesState,
  677    nav_history: Option<ItemNavHistory>,
  678    context_menu: RefCell<Option<CodeContextMenu>>,
  679    mouse_context_menu: Option<MouseContextMenu>,
  680    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  681    signature_help_state: SignatureHelpState,
  682    auto_signature_help: Option<bool>,
  683    find_all_references_task_sources: Vec<Anchor>,
  684    next_completion_id: CompletionId,
  685    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  686    code_actions_task: Option<Task<Result<()>>>,
  687    document_highlights_task: Option<Task<()>>,
  688    linked_editing_range_task: Option<Task<Option<()>>>,
  689    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  690    pending_rename: Option<RenameState>,
  691    searchable: bool,
  692    cursor_shape: CursorShape,
  693    current_line_highlight: Option<CurrentLineHighlight>,
  694    collapse_matches: bool,
  695    autoindent_mode: Option<AutoindentMode>,
  696    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  697    input_enabled: bool,
  698    use_modal_editing: bool,
  699    read_only: bool,
  700    leader_peer_id: Option<PeerId>,
  701    remote_id: Option<ViewId>,
  702    hover_state: HoverState,
  703    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  704    gutter_hovered: bool,
  705    hovered_link_state: Option<HoveredLinkState>,
  706    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  707    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  708    active_inline_completion: Option<InlineCompletionState>,
  709    /// Used to prevent flickering as the user types while the menu is open
  710    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  711    edit_prediction_settings: EditPredictionSettings,
  712    inline_completions_hidden_for_vim_mode: bool,
  713    show_inline_completions_override: Option<bool>,
  714    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  715    edit_prediction_preview: EditPredictionPreview,
  716    edit_prediction_cursor_on_leading_whitespace: bool,
  717    edit_prediction_requires_modifier_in_leading_space: bool,
  718    inlay_hint_cache: InlayHintCache,
  719    next_inlay_id: usize,
  720    _subscriptions: Vec<Subscription>,
  721    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  722    gutter_dimensions: GutterDimensions,
  723    style: Option<EditorStyle>,
  724    text_style_refinement: Option<TextStyleRefinement>,
  725    next_editor_action_id: EditorActionId,
  726    editor_actions:
  727        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  728    use_autoclose: bool,
  729    use_auto_surround: bool,
  730    auto_replace_emoji_shortcode: bool,
  731    show_git_blame_gutter: bool,
  732    show_git_blame_inline: bool,
  733    show_git_blame_inline_delay_task: Option<Task<()>>,
  734    distinguish_unstaged_diff_hunks: bool,
  735    git_blame_inline_enabled: bool,
  736    serialize_dirty_buffers: bool,
  737    show_selection_menu: Option<bool>,
  738    blame: Option<Entity<GitBlame>>,
  739    blame_subscription: Option<Subscription>,
  740    custom_context_menu: Option<
  741        Box<
  742            dyn 'static
  743                + Fn(
  744                    &mut Self,
  745                    DisplayPoint,
  746                    &mut Window,
  747                    &mut Context<Self>,
  748                ) -> Option<Entity<ui::ContextMenu>>,
  749        >,
  750    >,
  751    last_bounds: Option<Bounds<Pixels>>,
  752    last_position_map: Option<Rc<PositionMap>>,
  753    expect_bounds_change: Option<Bounds<Pixels>>,
  754    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  755    tasks_update_task: Option<Task<()>>,
  756    in_project_search: bool,
  757    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  758    breadcrumb_header: Option<String>,
  759    focused_block: Option<FocusedBlock>,
  760    next_scroll_position: NextScrollCursorCenterTopBottom,
  761    addons: HashMap<TypeId, Box<dyn Addon>>,
  762    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  763    selection_mark_mode: bool,
  764    toggle_fold_multiple_buffers: Task<()>,
  765    _scroll_cursor_center_top_bottom_task: Task<()>,
  766}
  767
  768#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  769enum NextScrollCursorCenterTopBottom {
  770    #[default]
  771    Center,
  772    Top,
  773    Bottom,
  774}
  775
  776impl NextScrollCursorCenterTopBottom {
  777    fn next(&self) -> Self {
  778        match self {
  779            Self::Center => Self::Top,
  780            Self::Top => Self::Bottom,
  781            Self::Bottom => Self::Center,
  782        }
  783    }
  784}
  785
  786#[derive(Clone)]
  787pub struct EditorSnapshot {
  788    pub mode: EditorMode,
  789    show_gutter: bool,
  790    show_line_numbers: Option<bool>,
  791    show_git_diff_gutter: Option<bool>,
  792    show_code_actions: Option<bool>,
  793    show_runnables: Option<bool>,
  794    git_blame_gutter_max_author_length: Option<usize>,
  795    pub display_snapshot: DisplaySnapshot,
  796    pub placeholder_text: Option<Arc<str>>,
  797    is_focused: bool,
  798    scroll_anchor: ScrollAnchor,
  799    ongoing_scroll: OngoingScroll,
  800    current_line_highlight: CurrentLineHighlight,
  801    gutter_hovered: bool,
  802}
  803
  804const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  805
  806#[derive(Default, Debug, Clone, Copy)]
  807pub struct GutterDimensions {
  808    pub left_padding: Pixels,
  809    pub right_padding: Pixels,
  810    pub width: Pixels,
  811    pub margin: Pixels,
  812    pub git_blame_entries_width: Option<Pixels>,
  813}
  814
  815impl GutterDimensions {
  816    /// The full width of the space taken up by the gutter.
  817    pub fn full_width(&self) -> Pixels {
  818        self.margin + self.width
  819    }
  820
  821    /// The width of the space reserved for the fold indicators,
  822    /// use alongside 'justify_end' and `gutter_width` to
  823    /// right align content with the line numbers
  824    pub fn fold_area_width(&self) -> Pixels {
  825        self.margin + self.right_padding
  826    }
  827}
  828
  829#[derive(Debug)]
  830pub struct RemoteSelection {
  831    pub replica_id: ReplicaId,
  832    pub selection: Selection<Anchor>,
  833    pub cursor_shape: CursorShape,
  834    pub peer_id: PeerId,
  835    pub line_mode: bool,
  836    pub participant_index: Option<ParticipantIndex>,
  837    pub user_name: Option<SharedString>,
  838}
  839
  840#[derive(Clone, Debug)]
  841struct SelectionHistoryEntry {
  842    selections: Arc<[Selection<Anchor>]>,
  843    select_next_state: Option<SelectNextState>,
  844    select_prev_state: Option<SelectNextState>,
  845    add_selections_state: Option<AddSelectionsState>,
  846}
  847
  848enum SelectionHistoryMode {
  849    Normal,
  850    Undoing,
  851    Redoing,
  852}
  853
  854#[derive(Clone, PartialEq, Eq, Hash)]
  855struct HoveredCursor {
  856    replica_id: u16,
  857    selection_id: usize,
  858}
  859
  860impl Default for SelectionHistoryMode {
  861    fn default() -> Self {
  862        Self::Normal
  863    }
  864}
  865
  866#[derive(Default)]
  867struct SelectionHistory {
  868    #[allow(clippy::type_complexity)]
  869    selections_by_transaction:
  870        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  871    mode: SelectionHistoryMode,
  872    undo_stack: VecDeque<SelectionHistoryEntry>,
  873    redo_stack: VecDeque<SelectionHistoryEntry>,
  874}
  875
  876impl SelectionHistory {
  877    fn insert_transaction(
  878        &mut self,
  879        transaction_id: TransactionId,
  880        selections: Arc<[Selection<Anchor>]>,
  881    ) {
  882        self.selections_by_transaction
  883            .insert(transaction_id, (selections, None));
  884    }
  885
  886    #[allow(clippy::type_complexity)]
  887    fn transaction(
  888        &self,
  889        transaction_id: TransactionId,
  890    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  891        self.selections_by_transaction.get(&transaction_id)
  892    }
  893
  894    #[allow(clippy::type_complexity)]
  895    fn transaction_mut(
  896        &mut self,
  897        transaction_id: TransactionId,
  898    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  899        self.selections_by_transaction.get_mut(&transaction_id)
  900    }
  901
  902    fn push(&mut self, entry: SelectionHistoryEntry) {
  903        if !entry.selections.is_empty() {
  904            match self.mode {
  905                SelectionHistoryMode::Normal => {
  906                    self.push_undo(entry);
  907                    self.redo_stack.clear();
  908                }
  909                SelectionHistoryMode::Undoing => self.push_redo(entry),
  910                SelectionHistoryMode::Redoing => self.push_undo(entry),
  911            }
  912        }
  913    }
  914
  915    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  916        if self
  917            .undo_stack
  918            .back()
  919            .map_or(true, |e| e.selections != entry.selections)
  920        {
  921            self.undo_stack.push_back(entry);
  922            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  923                self.undo_stack.pop_front();
  924            }
  925        }
  926    }
  927
  928    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  929        if self
  930            .redo_stack
  931            .back()
  932            .map_or(true, |e| e.selections != entry.selections)
  933        {
  934            self.redo_stack.push_back(entry);
  935            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  936                self.redo_stack.pop_front();
  937            }
  938        }
  939    }
  940}
  941
  942struct RowHighlight {
  943    index: usize,
  944    range: Range<Anchor>,
  945    color: Hsla,
  946    should_autoscroll: bool,
  947}
  948
  949#[derive(Clone, Debug)]
  950struct AddSelectionsState {
  951    above: bool,
  952    stack: Vec<usize>,
  953}
  954
  955#[derive(Clone)]
  956struct SelectNextState {
  957    query: AhoCorasick,
  958    wordwise: bool,
  959    done: bool,
  960}
  961
  962impl std::fmt::Debug for SelectNextState {
  963    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  964        f.debug_struct(std::any::type_name::<Self>())
  965            .field("wordwise", &self.wordwise)
  966            .field("done", &self.done)
  967            .finish()
  968    }
  969}
  970
  971#[derive(Debug)]
  972struct AutocloseRegion {
  973    selection_id: usize,
  974    range: Range<Anchor>,
  975    pair: BracketPair,
  976}
  977
  978#[derive(Debug)]
  979struct SnippetState {
  980    ranges: Vec<Vec<Range<Anchor>>>,
  981    active_index: usize,
  982    choices: Vec<Option<Vec<String>>>,
  983}
  984
  985#[doc(hidden)]
  986pub struct RenameState {
  987    pub range: Range<Anchor>,
  988    pub old_name: Arc<str>,
  989    pub editor: Entity<Editor>,
  990    block_id: CustomBlockId,
  991}
  992
  993struct InvalidationStack<T>(Vec<T>);
  994
  995struct RegisteredInlineCompletionProvider {
  996    provider: Arc<dyn InlineCompletionProviderHandle>,
  997    _subscription: Subscription,
  998}
  999
 1000#[derive(Debug)]
 1001struct ActiveDiagnosticGroup {
 1002    primary_range: Range<Anchor>,
 1003    primary_message: String,
 1004    group_id: usize,
 1005    blocks: HashMap<CustomBlockId, Diagnostic>,
 1006    is_valid: bool,
 1007}
 1008
 1009#[derive(Serialize, Deserialize, Clone, Debug)]
 1010pub struct ClipboardSelection {
 1011    pub len: usize,
 1012    pub is_entire_line: bool,
 1013    pub first_line_indent: u32,
 1014}
 1015
 1016#[derive(Debug)]
 1017pub(crate) struct NavigationData {
 1018    cursor_anchor: Anchor,
 1019    cursor_position: Point,
 1020    scroll_anchor: ScrollAnchor,
 1021    scroll_top_row: u32,
 1022}
 1023
 1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1025pub enum GotoDefinitionKind {
 1026    Symbol,
 1027    Declaration,
 1028    Type,
 1029    Implementation,
 1030}
 1031
 1032#[derive(Debug, Clone)]
 1033enum InlayHintRefreshReason {
 1034    Toggle(bool),
 1035    SettingsChange(InlayHintSettings),
 1036    NewLinesShown,
 1037    BufferEdited(HashSet<Arc<Language>>),
 1038    RefreshRequested,
 1039    ExcerptsRemoved(Vec<ExcerptId>),
 1040}
 1041
 1042impl InlayHintRefreshReason {
 1043    fn description(&self) -> &'static str {
 1044        match self {
 1045            Self::Toggle(_) => "toggle",
 1046            Self::SettingsChange(_) => "settings change",
 1047            Self::NewLinesShown => "new lines shown",
 1048            Self::BufferEdited(_) => "buffer edited",
 1049            Self::RefreshRequested => "refresh requested",
 1050            Self::ExcerptsRemoved(_) => "excerpts removed",
 1051        }
 1052    }
 1053}
 1054
 1055pub enum FormatTarget {
 1056    Buffers,
 1057    Ranges(Vec<Range<MultiBufferPoint>>),
 1058}
 1059
 1060pub(crate) struct FocusedBlock {
 1061    id: BlockId,
 1062    focus_handle: WeakFocusHandle,
 1063}
 1064
 1065#[derive(Clone)]
 1066enum JumpData {
 1067    MultiBufferRow {
 1068        row: MultiBufferRow,
 1069        line_offset_from_top: u32,
 1070    },
 1071    MultiBufferPoint {
 1072        excerpt_id: ExcerptId,
 1073        position: Point,
 1074        anchor: text::Anchor,
 1075        line_offset_from_top: u32,
 1076    },
 1077}
 1078
 1079pub enum MultibufferSelectionMode {
 1080    First,
 1081    All,
 1082}
 1083
 1084impl Editor {
 1085    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1086        let buffer = cx.new(|cx| Buffer::local("", cx));
 1087        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1088        Self::new(
 1089            EditorMode::SingleLine { auto_width: false },
 1090            buffer,
 1091            None,
 1092            false,
 1093            window,
 1094            cx,
 1095        )
 1096    }
 1097
 1098    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1099        let buffer = cx.new(|cx| Buffer::local("", cx));
 1100        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1101        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1102    }
 1103
 1104    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1105        let buffer = cx.new(|cx| Buffer::local("", cx));
 1106        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1107        Self::new(
 1108            EditorMode::SingleLine { auto_width: true },
 1109            buffer,
 1110            None,
 1111            false,
 1112            window,
 1113            cx,
 1114        )
 1115    }
 1116
 1117    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1118        let buffer = cx.new(|cx| Buffer::local("", cx));
 1119        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1120        Self::new(
 1121            EditorMode::AutoHeight { max_lines },
 1122            buffer,
 1123            None,
 1124            false,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn for_buffer(
 1131        buffer: Entity<Buffer>,
 1132        project: Option<Entity<Project>>,
 1133        window: &mut Window,
 1134        cx: &mut Context<Self>,
 1135    ) -> Self {
 1136        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1137        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1138    }
 1139
 1140    pub fn for_multibuffer(
 1141        buffer: Entity<MultiBuffer>,
 1142        project: Option<Entity<Project>>,
 1143        show_excerpt_controls: bool,
 1144        window: &mut Window,
 1145        cx: &mut Context<Self>,
 1146    ) -> Self {
 1147        Self::new(
 1148            EditorMode::Full,
 1149            buffer,
 1150            project,
 1151            show_excerpt_controls,
 1152            window,
 1153            cx,
 1154        )
 1155    }
 1156
 1157    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1158        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1159        let mut clone = Self::new(
 1160            self.mode,
 1161            self.buffer.clone(),
 1162            self.project.clone(),
 1163            show_excerpt_controls,
 1164            window,
 1165            cx,
 1166        );
 1167        self.display_map.update(cx, |display_map, cx| {
 1168            let snapshot = display_map.snapshot(cx);
 1169            clone.display_map.update(cx, |display_map, cx| {
 1170                display_map.set_state(&snapshot, cx);
 1171            });
 1172        });
 1173        clone.selections.clone_state(&self.selections);
 1174        clone.scroll_manager.clone_state(&self.scroll_manager);
 1175        clone.searchable = self.searchable;
 1176        clone
 1177    }
 1178
 1179    pub fn new(
 1180        mode: EditorMode,
 1181        buffer: Entity<MultiBuffer>,
 1182        project: Option<Entity<Project>>,
 1183        show_excerpt_controls: bool,
 1184        window: &mut Window,
 1185        cx: &mut Context<Self>,
 1186    ) -> Self {
 1187        let style = window.text_style();
 1188        let font_size = style.font_size.to_pixels(window.rem_size());
 1189        let editor = cx.entity().downgrade();
 1190        let fold_placeholder = FoldPlaceholder {
 1191            constrain_width: true,
 1192            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1193                let editor = editor.clone();
 1194                div()
 1195                    .id(fold_id)
 1196                    .bg(cx.theme().colors().ghost_element_background)
 1197                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1198                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1199                    .rounded_sm()
 1200                    .size_full()
 1201                    .cursor_pointer()
 1202                    .child("")
 1203                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1204                    .on_click(move |_, _window, cx| {
 1205                        editor
 1206                            .update(cx, |editor, cx| {
 1207                                editor.unfold_ranges(
 1208                                    &[fold_range.start..fold_range.end],
 1209                                    true,
 1210                                    false,
 1211                                    cx,
 1212                                );
 1213                                cx.stop_propagation();
 1214                            })
 1215                            .ok();
 1216                    })
 1217                    .into_any()
 1218            }),
 1219            merge_adjacent: true,
 1220            ..Default::default()
 1221        };
 1222        let display_map = cx.new(|cx| {
 1223            DisplayMap::new(
 1224                buffer.clone(),
 1225                style.font(),
 1226                font_size,
 1227                None,
 1228                show_excerpt_controls,
 1229                FILE_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1231                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1232                fold_placeholder,
 1233                cx,
 1234            )
 1235        });
 1236
 1237        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1238
 1239        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1240
 1241        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1242            .then(|| language_settings::SoftWrap::None);
 1243
 1244        let mut project_subscriptions = Vec::new();
 1245        if mode == EditorMode::Full {
 1246            if let Some(project) = project.as_ref() {
 1247                if buffer.read(cx).is_singleton() {
 1248                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1249                        cx.emit(EditorEvent::TitleChanged);
 1250                    }));
 1251                }
 1252                project_subscriptions.push(cx.subscribe_in(
 1253                    project,
 1254                    window,
 1255                    |editor, _, event, window, cx| {
 1256                        if let project::Event::RefreshInlayHints = event {
 1257                            editor
 1258                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1259                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1260                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1261                                let focus_handle = editor.focus_handle(cx);
 1262                                if focus_handle.is_focused(window) {
 1263                                    let snapshot = buffer.read(cx).snapshot();
 1264                                    for (range, snippet) in snippet_edits {
 1265                                        let editor_range =
 1266                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1267                                        editor
 1268                                            .insert_snippet(
 1269                                                &[editor_range],
 1270                                                snippet.clone(),
 1271                                                window,
 1272                                                cx,
 1273                                            )
 1274                                            .ok();
 1275                                    }
 1276                                }
 1277                            }
 1278                        }
 1279                    },
 1280                ));
 1281                if let Some(task_inventory) = project
 1282                    .read(cx)
 1283                    .task_store()
 1284                    .read(cx)
 1285                    .task_inventory()
 1286                    .cloned()
 1287                {
 1288                    project_subscriptions.push(cx.observe_in(
 1289                        &task_inventory,
 1290                        window,
 1291                        |editor, _, window, cx| {
 1292                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1293                        },
 1294                    ));
 1295                }
 1296            }
 1297        }
 1298
 1299        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1300
 1301        let inlay_hint_settings =
 1302            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1303        let focus_handle = cx.focus_handle();
 1304        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1305            .detach();
 1306        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1307            .detach();
 1308        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1309            .detach();
 1310        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1311            .detach();
 1312
 1313        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1314            Some(false)
 1315        } else {
 1316            None
 1317        };
 1318
 1319        let mut code_action_providers = Vec::new();
 1320        if let Some(project) = project.clone() {
 1321            get_uncommitted_diff_for_buffer(
 1322                &project,
 1323                buffer.read(cx).all_buffers(),
 1324                buffer.clone(),
 1325                cx,
 1326            );
 1327            code_action_providers.push(Rc::new(project) as Rc<_>);
 1328        }
 1329
 1330        let mut this = Self {
 1331            focus_handle,
 1332            show_cursor_when_unfocused: false,
 1333            last_focused_descendant: None,
 1334            buffer: buffer.clone(),
 1335            display_map: display_map.clone(),
 1336            selections,
 1337            scroll_manager: ScrollManager::new(cx),
 1338            columnar_selection_tail: None,
 1339            add_selections_state: None,
 1340            select_next_state: None,
 1341            select_prev_state: None,
 1342            selection_history: Default::default(),
 1343            autoclose_regions: Default::default(),
 1344            snippet_stack: Default::default(),
 1345            select_larger_syntax_node_stack: Vec::new(),
 1346            ime_transaction: Default::default(),
 1347            active_diagnostics: None,
 1348            soft_wrap_mode_override,
 1349            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1350            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1351            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1352            project,
 1353            blink_manager: blink_manager.clone(),
 1354            show_local_selections: true,
 1355            show_scrollbars: true,
 1356            mode,
 1357            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1358            show_gutter: mode == EditorMode::Full,
 1359            show_line_numbers: None,
 1360            use_relative_line_numbers: None,
 1361            show_git_diff_gutter: None,
 1362            show_code_actions: None,
 1363            show_runnables: None,
 1364            show_wrap_guides: None,
 1365            show_indent_guides,
 1366            placeholder_text: None,
 1367            highlight_order: 0,
 1368            highlighted_rows: HashMap::default(),
 1369            background_highlights: Default::default(),
 1370            gutter_highlights: TreeMap::default(),
 1371            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1372            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1373            nav_history: None,
 1374            context_menu: RefCell::new(None),
 1375            mouse_context_menu: None,
 1376            completion_tasks: Default::default(),
 1377            signature_help_state: SignatureHelpState::default(),
 1378            auto_signature_help: None,
 1379            find_all_references_task_sources: Vec::new(),
 1380            next_completion_id: 0,
 1381            next_inlay_id: 0,
 1382            code_action_providers,
 1383            available_code_actions: Default::default(),
 1384            code_actions_task: Default::default(),
 1385            document_highlights_task: Default::default(),
 1386            linked_editing_range_task: Default::default(),
 1387            pending_rename: Default::default(),
 1388            searchable: true,
 1389            cursor_shape: EditorSettings::get_global(cx)
 1390                .cursor_shape
 1391                .unwrap_or_default(),
 1392            current_line_highlight: None,
 1393            autoindent_mode: Some(AutoindentMode::EachLine),
 1394            collapse_matches: false,
 1395            workspace: None,
 1396            input_enabled: true,
 1397            use_modal_editing: mode == EditorMode::Full,
 1398            read_only: false,
 1399            use_autoclose: true,
 1400            use_auto_surround: true,
 1401            auto_replace_emoji_shortcode: false,
 1402            leader_peer_id: None,
 1403            remote_id: None,
 1404            hover_state: Default::default(),
 1405            pending_mouse_down: None,
 1406            hovered_link_state: Default::default(),
 1407            edit_prediction_provider: None,
 1408            active_inline_completion: None,
 1409            stale_inline_completion_in_menu: None,
 1410            edit_prediction_preview: EditPredictionPreview::Inactive,
 1411            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1412
 1413            gutter_hovered: false,
 1414            pixel_position_of_newest_cursor: None,
 1415            last_bounds: None,
 1416            last_position_map: None,
 1417            expect_bounds_change: None,
 1418            gutter_dimensions: GutterDimensions::default(),
 1419            style: None,
 1420            show_cursor_names: false,
 1421            hovered_cursors: Default::default(),
 1422            next_editor_action_id: EditorActionId::default(),
 1423            editor_actions: Rc::default(),
 1424            inline_completions_hidden_for_vim_mode: false,
 1425            show_inline_completions_override: None,
 1426            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1427            edit_prediction_settings: EditPredictionSettings::Disabled,
 1428            edit_prediction_cursor_on_leading_whitespace: false,
 1429            edit_prediction_requires_modifier_in_leading_space: true,
 1430            custom_context_menu: None,
 1431            show_git_blame_gutter: false,
 1432            show_git_blame_inline: false,
 1433            distinguish_unstaged_diff_hunks: false,
 1434            show_selection_menu: None,
 1435            show_git_blame_inline_delay_task: None,
 1436            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1437            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1438                .session
 1439                .restore_unsaved_buffers,
 1440            blame: None,
 1441            blame_subscription: None,
 1442            tasks: Default::default(),
 1443            _subscriptions: vec![
 1444                cx.observe(&buffer, Self::on_buffer_changed),
 1445                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1446                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1447                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1448                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1449                cx.observe_window_activation(window, |editor, window, cx| {
 1450                    let active = window.is_window_active();
 1451                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1452                        if active {
 1453                            blink_manager.enable(cx);
 1454                        } else {
 1455                            blink_manager.disable(cx);
 1456                        }
 1457                    });
 1458                }),
 1459            ],
 1460            tasks_update_task: None,
 1461            linked_edit_ranges: Default::default(),
 1462            in_project_search: false,
 1463            previous_search_ranges: None,
 1464            breadcrumb_header: None,
 1465            focused_block: None,
 1466            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1467            addons: HashMap::default(),
 1468            registered_buffers: HashMap::default(),
 1469            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1470            selection_mark_mode: false,
 1471            toggle_fold_multiple_buffers: Task::ready(()),
 1472            text_style_refinement: None,
 1473        };
 1474        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1475        this._subscriptions.extend(project_subscriptions);
 1476
 1477        this.end_selection(window, cx);
 1478        this.scroll_manager.show_scrollbar(window, cx);
 1479
 1480        if mode == EditorMode::Full {
 1481            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1482            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1483
 1484            if this.git_blame_inline_enabled {
 1485                this.git_blame_inline_enabled = true;
 1486                this.start_git_blame_inline(false, window, cx);
 1487            }
 1488
 1489            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1490                if let Some(project) = this.project.as_ref() {
 1491                    let lsp_store = project.read(cx).lsp_store();
 1492                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1493                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1494                    });
 1495                    this.registered_buffers
 1496                        .insert(buffer.read(cx).remote_id(), handle);
 1497                }
 1498            }
 1499        }
 1500
 1501        this.report_editor_event("Editor Opened", None, cx);
 1502        this
 1503    }
 1504
 1505    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1506        self.mouse_context_menu
 1507            .as_ref()
 1508            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1509    }
 1510
 1511    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1512        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1513    }
 1514
 1515    fn key_context_internal(
 1516        &self,
 1517        has_active_edit_prediction: bool,
 1518        window: &Window,
 1519        cx: &App,
 1520    ) -> KeyContext {
 1521        let mut key_context = KeyContext::new_with_defaults();
 1522        key_context.add("Editor");
 1523        let mode = match self.mode {
 1524            EditorMode::SingleLine { .. } => "single_line",
 1525            EditorMode::AutoHeight { .. } => "auto_height",
 1526            EditorMode::Full => "full",
 1527        };
 1528
 1529        if EditorSettings::jupyter_enabled(cx) {
 1530            key_context.add("jupyter");
 1531        }
 1532
 1533        key_context.set("mode", mode);
 1534        if self.pending_rename.is_some() {
 1535            key_context.add("renaming");
 1536        }
 1537
 1538        let mut showing_completions = false;
 1539
 1540        match self.context_menu.borrow().as_ref() {
 1541            Some(CodeContextMenu::Completions(_)) => {
 1542                key_context.add("menu");
 1543                key_context.add("showing_completions");
 1544                showing_completions = true;
 1545            }
 1546            Some(CodeContextMenu::CodeActions(_)) => {
 1547                key_context.add("menu");
 1548                key_context.add("showing_code_actions")
 1549            }
 1550            None => {}
 1551        }
 1552
 1553        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1554        if !self.focus_handle(cx).contains_focused(window, cx)
 1555            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1556        {
 1557            for addon in self.addons.values() {
 1558                addon.extend_key_context(&mut key_context, cx)
 1559            }
 1560        }
 1561
 1562        if let Some(extension) = self
 1563            .buffer
 1564            .read(cx)
 1565            .as_singleton()
 1566            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1567        {
 1568            key_context.set("extension", extension.to_string());
 1569        }
 1570
 1571        if has_active_edit_prediction {
 1572            key_context.add("copilot_suggestion");
 1573            key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1574            if showing_completions
 1575                || self.edit_prediction_requires_modifier()
 1576                // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1577                // bindings to insert tab characters.
 1578                || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1579            {
 1580                key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
 1581            }
 1582        }
 1583
 1584        if self.selection_mark_mode {
 1585            key_context.add("selection_mode");
 1586        }
 1587
 1588        key_context
 1589    }
 1590
 1591    pub fn accept_edit_prediction_keybind(
 1592        &self,
 1593        window: &Window,
 1594        cx: &App,
 1595    ) -> AcceptEditPredictionBinding {
 1596        let key_context = self.key_context_internal(true, window, cx);
 1597        AcceptEditPredictionBinding(
 1598            window
 1599                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1600                .into_iter()
 1601                .rev()
 1602                .next(),
 1603        )
 1604    }
 1605
 1606    pub fn new_file(
 1607        workspace: &mut Workspace,
 1608        _: &workspace::NewFile,
 1609        window: &mut Window,
 1610        cx: &mut Context<Workspace>,
 1611    ) {
 1612        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1613            "Failed to create buffer",
 1614            window,
 1615            cx,
 1616            |e, _, _| match e.error_code() {
 1617                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1618                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1619                e.error_tag("required").unwrap_or("the latest version")
 1620            )),
 1621                _ => None,
 1622            },
 1623        );
 1624    }
 1625
 1626    pub fn new_in_workspace(
 1627        workspace: &mut Workspace,
 1628        window: &mut Window,
 1629        cx: &mut Context<Workspace>,
 1630    ) -> Task<Result<Entity<Editor>>> {
 1631        let project = workspace.project().clone();
 1632        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1633
 1634        cx.spawn_in(window, |workspace, mut cx| async move {
 1635            let buffer = create.await?;
 1636            workspace.update_in(&mut cx, |workspace, window, cx| {
 1637                let editor =
 1638                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1639                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1640                editor
 1641            })
 1642        })
 1643    }
 1644
 1645    fn new_file_vertical(
 1646        workspace: &mut Workspace,
 1647        _: &workspace::NewFileSplitVertical,
 1648        window: &mut Window,
 1649        cx: &mut Context<Workspace>,
 1650    ) {
 1651        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1652    }
 1653
 1654    fn new_file_horizontal(
 1655        workspace: &mut Workspace,
 1656        _: &workspace::NewFileSplitHorizontal,
 1657        window: &mut Window,
 1658        cx: &mut Context<Workspace>,
 1659    ) {
 1660        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1661    }
 1662
 1663    fn new_file_in_direction(
 1664        workspace: &mut Workspace,
 1665        direction: SplitDirection,
 1666        window: &mut Window,
 1667        cx: &mut Context<Workspace>,
 1668    ) {
 1669        let project = workspace.project().clone();
 1670        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1671
 1672        cx.spawn_in(window, |workspace, mut cx| async move {
 1673            let buffer = create.await?;
 1674            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1675                workspace.split_item(
 1676                    direction,
 1677                    Box::new(
 1678                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1679                    ),
 1680                    window,
 1681                    cx,
 1682                )
 1683            })?;
 1684            anyhow::Ok(())
 1685        })
 1686        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1687            match e.error_code() {
 1688                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1689                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1690                e.error_tag("required").unwrap_or("the latest version")
 1691            )),
 1692                _ => None,
 1693            }
 1694        });
 1695    }
 1696
 1697    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1698        self.leader_peer_id
 1699    }
 1700
 1701    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1702        &self.buffer
 1703    }
 1704
 1705    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1706        self.workspace.as_ref()?.0.upgrade()
 1707    }
 1708
 1709    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1710        self.buffer().read(cx).title(cx)
 1711    }
 1712
 1713    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1714        let git_blame_gutter_max_author_length = self
 1715            .render_git_blame_gutter(cx)
 1716            .then(|| {
 1717                if let Some(blame) = self.blame.as_ref() {
 1718                    let max_author_length =
 1719                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1720                    Some(max_author_length)
 1721                } else {
 1722                    None
 1723                }
 1724            })
 1725            .flatten();
 1726
 1727        EditorSnapshot {
 1728            mode: self.mode,
 1729            show_gutter: self.show_gutter,
 1730            show_line_numbers: self.show_line_numbers,
 1731            show_git_diff_gutter: self.show_git_diff_gutter,
 1732            show_code_actions: self.show_code_actions,
 1733            show_runnables: self.show_runnables,
 1734            git_blame_gutter_max_author_length,
 1735            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1736            scroll_anchor: self.scroll_manager.anchor(),
 1737            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1738            placeholder_text: self.placeholder_text.clone(),
 1739            is_focused: self.focus_handle.is_focused(window),
 1740            current_line_highlight: self
 1741                .current_line_highlight
 1742                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1743            gutter_hovered: self.gutter_hovered,
 1744        }
 1745    }
 1746
 1747    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1748        self.buffer.read(cx).language_at(point, cx)
 1749    }
 1750
 1751    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1752        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1753    }
 1754
 1755    pub fn active_excerpt(
 1756        &self,
 1757        cx: &App,
 1758    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1759        self.buffer
 1760            .read(cx)
 1761            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1762    }
 1763
 1764    pub fn mode(&self) -> EditorMode {
 1765        self.mode
 1766    }
 1767
 1768    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1769        self.collaboration_hub.as_deref()
 1770    }
 1771
 1772    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1773        self.collaboration_hub = Some(hub);
 1774    }
 1775
 1776    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1777        self.in_project_search = in_project_search;
 1778    }
 1779
 1780    pub fn set_custom_context_menu(
 1781        &mut self,
 1782        f: impl 'static
 1783            + Fn(
 1784                &mut Self,
 1785                DisplayPoint,
 1786                &mut Window,
 1787                &mut Context<Self>,
 1788            ) -> Option<Entity<ui::ContextMenu>>,
 1789    ) {
 1790        self.custom_context_menu = Some(Box::new(f))
 1791    }
 1792
 1793    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1794        self.completion_provider = provider;
 1795    }
 1796
 1797    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1798        self.semantics_provider.clone()
 1799    }
 1800
 1801    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1802        self.semantics_provider = provider;
 1803    }
 1804
 1805    pub fn set_edit_prediction_provider<T>(
 1806        &mut self,
 1807        provider: Option<Entity<T>>,
 1808        window: &mut Window,
 1809        cx: &mut Context<Self>,
 1810    ) where
 1811        T: EditPredictionProvider,
 1812    {
 1813        self.edit_prediction_provider =
 1814            provider.map(|provider| RegisteredInlineCompletionProvider {
 1815                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1816                    if this.focus_handle.is_focused(window) {
 1817                        this.update_visible_inline_completion(window, cx);
 1818                    }
 1819                }),
 1820                provider: Arc::new(provider),
 1821            });
 1822        self.refresh_inline_completion(false, false, window, cx);
 1823    }
 1824
 1825    pub fn placeholder_text(&self) -> Option<&str> {
 1826        self.placeholder_text.as_deref()
 1827    }
 1828
 1829    pub fn set_placeholder_text(
 1830        &mut self,
 1831        placeholder_text: impl Into<Arc<str>>,
 1832        cx: &mut Context<Self>,
 1833    ) {
 1834        let placeholder_text = Some(placeholder_text.into());
 1835        if self.placeholder_text != placeholder_text {
 1836            self.placeholder_text = placeholder_text;
 1837            cx.notify();
 1838        }
 1839    }
 1840
 1841    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1842        self.cursor_shape = cursor_shape;
 1843
 1844        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1845        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1846
 1847        cx.notify();
 1848    }
 1849
 1850    pub fn set_current_line_highlight(
 1851        &mut self,
 1852        current_line_highlight: Option<CurrentLineHighlight>,
 1853    ) {
 1854        self.current_line_highlight = current_line_highlight;
 1855    }
 1856
 1857    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1858        self.collapse_matches = collapse_matches;
 1859    }
 1860
 1861    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1862        let buffers = self.buffer.read(cx).all_buffers();
 1863        let Some(lsp_store) = self.lsp_store(cx) else {
 1864            return;
 1865        };
 1866        lsp_store.update(cx, |lsp_store, cx| {
 1867            for buffer in buffers {
 1868                self.registered_buffers
 1869                    .entry(buffer.read(cx).remote_id())
 1870                    .or_insert_with(|| {
 1871                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1872                    });
 1873            }
 1874        })
 1875    }
 1876
 1877    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1878        if self.collapse_matches {
 1879            return range.start..range.start;
 1880        }
 1881        range.clone()
 1882    }
 1883
 1884    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1885        if self.display_map.read(cx).clip_at_line_ends != clip {
 1886            self.display_map
 1887                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1888        }
 1889    }
 1890
 1891    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1892        self.input_enabled = input_enabled;
 1893    }
 1894
 1895    pub fn set_inline_completions_hidden_for_vim_mode(
 1896        &mut self,
 1897        hidden: bool,
 1898        window: &mut Window,
 1899        cx: &mut Context<Self>,
 1900    ) {
 1901        if hidden != self.inline_completions_hidden_for_vim_mode {
 1902            self.inline_completions_hidden_for_vim_mode = hidden;
 1903            if hidden {
 1904                self.update_visible_inline_completion(window, cx);
 1905            } else {
 1906                self.refresh_inline_completion(true, false, window, cx);
 1907            }
 1908        }
 1909    }
 1910
 1911    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1912        self.menu_inline_completions_policy = value;
 1913    }
 1914
 1915    pub fn set_autoindent(&mut self, autoindent: bool) {
 1916        if autoindent {
 1917            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1918        } else {
 1919            self.autoindent_mode = None;
 1920        }
 1921    }
 1922
 1923    pub fn read_only(&self, cx: &App) -> bool {
 1924        self.read_only || self.buffer.read(cx).read_only()
 1925    }
 1926
 1927    pub fn set_read_only(&mut self, read_only: bool) {
 1928        self.read_only = read_only;
 1929    }
 1930
 1931    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1932        self.use_autoclose = autoclose;
 1933    }
 1934
 1935    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1936        self.use_auto_surround = auto_surround;
 1937    }
 1938
 1939    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1940        self.auto_replace_emoji_shortcode = auto_replace;
 1941    }
 1942
 1943    pub fn toggle_inline_completions(
 1944        &mut self,
 1945        _: &ToggleEditPrediction,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        if self.show_inline_completions_override.is_some() {
 1950            self.set_show_edit_predictions(None, window, cx);
 1951        } else {
 1952            let show_edit_predictions = !self.edit_predictions_enabled();
 1953            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1954        }
 1955    }
 1956
 1957    pub fn set_show_edit_predictions(
 1958        &mut self,
 1959        show_edit_predictions: Option<bool>,
 1960        window: &mut Window,
 1961        cx: &mut Context<Self>,
 1962    ) {
 1963        self.show_inline_completions_override = show_edit_predictions;
 1964        self.refresh_inline_completion(false, true, window, cx);
 1965    }
 1966
 1967    fn inline_completions_disabled_in_scope(
 1968        &self,
 1969        buffer: &Entity<Buffer>,
 1970        buffer_position: language::Anchor,
 1971        cx: &App,
 1972    ) -> bool {
 1973        let snapshot = buffer.read(cx).snapshot();
 1974        let settings = snapshot.settings_at(buffer_position, cx);
 1975
 1976        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1977            return false;
 1978        };
 1979
 1980        scope.override_name().map_or(false, |scope_name| {
 1981            settings
 1982                .edit_predictions_disabled_in
 1983                .iter()
 1984                .any(|s| s == scope_name)
 1985        })
 1986    }
 1987
 1988    pub fn set_use_modal_editing(&mut self, to: bool) {
 1989        self.use_modal_editing = to;
 1990    }
 1991
 1992    pub fn use_modal_editing(&self) -> bool {
 1993        self.use_modal_editing
 1994    }
 1995
 1996    fn selections_did_change(
 1997        &mut self,
 1998        local: bool,
 1999        old_cursor_position: &Anchor,
 2000        show_completions: bool,
 2001        window: &mut Window,
 2002        cx: &mut Context<Self>,
 2003    ) {
 2004        window.invalidate_character_coordinates();
 2005
 2006        // Copy selections to primary selection buffer
 2007        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2008        if local {
 2009            let selections = self.selections.all::<usize>(cx);
 2010            let buffer_handle = self.buffer.read(cx).read(cx);
 2011
 2012            let mut text = String::new();
 2013            for (index, selection) in selections.iter().enumerate() {
 2014                let text_for_selection = buffer_handle
 2015                    .text_for_range(selection.start..selection.end)
 2016                    .collect::<String>();
 2017
 2018                text.push_str(&text_for_selection);
 2019                if index != selections.len() - 1 {
 2020                    text.push('\n');
 2021                }
 2022            }
 2023
 2024            if !text.is_empty() {
 2025                cx.write_to_primary(ClipboardItem::new_string(text));
 2026            }
 2027        }
 2028
 2029        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2030            self.buffer.update(cx, |buffer, cx| {
 2031                buffer.set_active_selections(
 2032                    &self.selections.disjoint_anchors(),
 2033                    self.selections.line_mode,
 2034                    self.cursor_shape,
 2035                    cx,
 2036                )
 2037            });
 2038        }
 2039        let display_map = self
 2040            .display_map
 2041            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2042        let buffer = &display_map.buffer_snapshot;
 2043        self.add_selections_state = None;
 2044        self.select_next_state = None;
 2045        self.select_prev_state = None;
 2046        self.select_larger_syntax_node_stack.clear();
 2047        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2048        self.snippet_stack
 2049            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2050        self.take_rename(false, window, cx);
 2051
 2052        let new_cursor_position = self.selections.newest_anchor().head();
 2053
 2054        self.push_to_nav_history(
 2055            *old_cursor_position,
 2056            Some(new_cursor_position.to_point(buffer)),
 2057            cx,
 2058        );
 2059
 2060        if local {
 2061            let new_cursor_position = self.selections.newest_anchor().head();
 2062            let mut context_menu = self.context_menu.borrow_mut();
 2063            let completion_menu = match context_menu.as_ref() {
 2064                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2065                _ => {
 2066                    *context_menu = None;
 2067                    None
 2068                }
 2069            };
 2070            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2071                if !self.registered_buffers.contains_key(&buffer_id) {
 2072                    if let Some(lsp_store) = self.lsp_store(cx) {
 2073                        lsp_store.update(cx, |lsp_store, cx| {
 2074                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2075                                return;
 2076                            };
 2077                            self.registered_buffers.insert(
 2078                                buffer_id,
 2079                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2080                            );
 2081                        })
 2082                    }
 2083                }
 2084            }
 2085
 2086            if let Some(completion_menu) = completion_menu {
 2087                let cursor_position = new_cursor_position.to_offset(buffer);
 2088                let (word_range, kind) =
 2089                    buffer.surrounding_word(completion_menu.initial_position, true);
 2090                if kind == Some(CharKind::Word)
 2091                    && word_range.to_inclusive().contains(&cursor_position)
 2092                {
 2093                    let mut completion_menu = completion_menu.clone();
 2094                    drop(context_menu);
 2095
 2096                    let query = Self::completion_query(buffer, cursor_position);
 2097                    cx.spawn(move |this, mut cx| async move {
 2098                        completion_menu
 2099                            .filter(query.as_deref(), cx.background_executor().clone())
 2100                            .await;
 2101
 2102                        this.update(&mut cx, |this, cx| {
 2103                            let mut context_menu = this.context_menu.borrow_mut();
 2104                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2105                            else {
 2106                                return;
 2107                            };
 2108
 2109                            if menu.id > completion_menu.id {
 2110                                return;
 2111                            }
 2112
 2113                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2114                            drop(context_menu);
 2115                            cx.notify();
 2116                        })
 2117                    })
 2118                    .detach();
 2119
 2120                    if show_completions {
 2121                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2122                    }
 2123                } else {
 2124                    drop(context_menu);
 2125                    self.hide_context_menu(window, cx);
 2126                }
 2127            } else {
 2128                drop(context_menu);
 2129            }
 2130
 2131            hide_hover(self, cx);
 2132
 2133            if old_cursor_position.to_display_point(&display_map).row()
 2134                != new_cursor_position.to_display_point(&display_map).row()
 2135            {
 2136                self.available_code_actions.take();
 2137            }
 2138            self.refresh_code_actions(window, cx);
 2139            self.refresh_document_highlights(cx);
 2140            refresh_matching_bracket_highlights(self, window, cx);
 2141            self.update_visible_inline_completion(window, cx);
 2142            self.edit_prediction_requires_modifier_in_leading_space = true;
 2143            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2144            if self.git_blame_inline_enabled {
 2145                self.start_inline_blame_timer(window, cx);
 2146            }
 2147        }
 2148
 2149        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2150        cx.emit(EditorEvent::SelectionsChanged { local });
 2151
 2152        if self.selections.disjoint_anchors().len() == 1 {
 2153            cx.emit(SearchEvent::ActiveMatchChanged)
 2154        }
 2155        cx.notify();
 2156    }
 2157
 2158    pub fn change_selections<R>(
 2159        &mut self,
 2160        autoscroll: Option<Autoscroll>,
 2161        window: &mut Window,
 2162        cx: &mut Context<Self>,
 2163        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2164    ) -> R {
 2165        self.change_selections_inner(autoscroll, true, window, cx, change)
 2166    }
 2167
 2168    pub fn change_selections_inner<R>(
 2169        &mut self,
 2170        autoscroll: Option<Autoscroll>,
 2171        request_completions: bool,
 2172        window: &mut Window,
 2173        cx: &mut Context<Self>,
 2174        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2175    ) -> R {
 2176        let old_cursor_position = self.selections.newest_anchor().head();
 2177        self.push_to_selection_history();
 2178
 2179        let (changed, result) = self.selections.change_with(cx, change);
 2180
 2181        if changed {
 2182            if let Some(autoscroll) = autoscroll {
 2183                self.request_autoscroll(autoscroll, cx);
 2184            }
 2185            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2186
 2187            if self.should_open_signature_help_automatically(
 2188                &old_cursor_position,
 2189                self.signature_help_state.backspace_pressed(),
 2190                cx,
 2191            ) {
 2192                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2193            }
 2194            self.signature_help_state.set_backspace_pressed(false);
 2195        }
 2196
 2197        result
 2198    }
 2199
 2200    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2201    where
 2202        I: IntoIterator<Item = (Range<S>, T)>,
 2203        S: ToOffset,
 2204        T: Into<Arc<str>>,
 2205    {
 2206        if self.read_only(cx) {
 2207            return;
 2208        }
 2209
 2210        self.buffer
 2211            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2212    }
 2213
 2214    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2215    where
 2216        I: IntoIterator<Item = (Range<S>, T)>,
 2217        S: ToOffset,
 2218        T: Into<Arc<str>>,
 2219    {
 2220        if self.read_only(cx) {
 2221            return;
 2222        }
 2223
 2224        self.buffer.update(cx, |buffer, cx| {
 2225            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2226        });
 2227    }
 2228
 2229    pub fn edit_with_block_indent<I, S, T>(
 2230        &mut self,
 2231        edits: I,
 2232        original_indent_columns: Vec<u32>,
 2233        cx: &mut Context<Self>,
 2234    ) where
 2235        I: IntoIterator<Item = (Range<S>, T)>,
 2236        S: ToOffset,
 2237        T: Into<Arc<str>>,
 2238    {
 2239        if self.read_only(cx) {
 2240            return;
 2241        }
 2242
 2243        self.buffer.update(cx, |buffer, cx| {
 2244            buffer.edit(
 2245                edits,
 2246                Some(AutoindentMode::Block {
 2247                    original_indent_columns,
 2248                }),
 2249                cx,
 2250            )
 2251        });
 2252    }
 2253
 2254    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2255        self.hide_context_menu(window, cx);
 2256
 2257        match phase {
 2258            SelectPhase::Begin {
 2259                position,
 2260                add,
 2261                click_count,
 2262            } => self.begin_selection(position, add, click_count, window, cx),
 2263            SelectPhase::BeginColumnar {
 2264                position,
 2265                goal_column,
 2266                reset,
 2267            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2268            SelectPhase::Extend {
 2269                position,
 2270                click_count,
 2271            } => self.extend_selection(position, click_count, window, cx),
 2272            SelectPhase::Update {
 2273                position,
 2274                goal_column,
 2275                scroll_delta,
 2276            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2277            SelectPhase::End => self.end_selection(window, cx),
 2278        }
 2279    }
 2280
 2281    fn extend_selection(
 2282        &mut self,
 2283        position: DisplayPoint,
 2284        click_count: usize,
 2285        window: &mut Window,
 2286        cx: &mut Context<Self>,
 2287    ) {
 2288        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2289        let tail = self.selections.newest::<usize>(cx).tail();
 2290        self.begin_selection(position, false, click_count, window, cx);
 2291
 2292        let position = position.to_offset(&display_map, Bias::Left);
 2293        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2294
 2295        let mut pending_selection = self
 2296            .selections
 2297            .pending_anchor()
 2298            .expect("extend_selection not called with pending selection");
 2299        if position >= tail {
 2300            pending_selection.start = tail_anchor;
 2301        } else {
 2302            pending_selection.end = tail_anchor;
 2303            pending_selection.reversed = true;
 2304        }
 2305
 2306        let mut pending_mode = self.selections.pending_mode().unwrap();
 2307        match &mut pending_mode {
 2308            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2309            _ => {}
 2310        }
 2311
 2312        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2313            s.set_pending(pending_selection, pending_mode)
 2314        });
 2315    }
 2316
 2317    fn begin_selection(
 2318        &mut self,
 2319        position: DisplayPoint,
 2320        add: bool,
 2321        click_count: usize,
 2322        window: &mut Window,
 2323        cx: &mut Context<Self>,
 2324    ) {
 2325        if !self.focus_handle.is_focused(window) {
 2326            self.last_focused_descendant = None;
 2327            window.focus(&self.focus_handle);
 2328        }
 2329
 2330        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2331        let buffer = &display_map.buffer_snapshot;
 2332        let newest_selection = self.selections.newest_anchor().clone();
 2333        let position = display_map.clip_point(position, Bias::Left);
 2334
 2335        let start;
 2336        let end;
 2337        let mode;
 2338        let mut auto_scroll;
 2339        match click_count {
 2340            1 => {
 2341                start = buffer.anchor_before(position.to_point(&display_map));
 2342                end = start;
 2343                mode = SelectMode::Character;
 2344                auto_scroll = true;
 2345            }
 2346            2 => {
 2347                let range = movement::surrounding_word(&display_map, position);
 2348                start = buffer.anchor_before(range.start.to_point(&display_map));
 2349                end = buffer.anchor_before(range.end.to_point(&display_map));
 2350                mode = SelectMode::Word(start..end);
 2351                auto_scroll = true;
 2352            }
 2353            3 => {
 2354                let position = display_map
 2355                    .clip_point(position, Bias::Left)
 2356                    .to_point(&display_map);
 2357                let line_start = display_map.prev_line_boundary(position).0;
 2358                let next_line_start = buffer.clip_point(
 2359                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2360                    Bias::Left,
 2361                );
 2362                start = buffer.anchor_before(line_start);
 2363                end = buffer.anchor_before(next_line_start);
 2364                mode = SelectMode::Line(start..end);
 2365                auto_scroll = true;
 2366            }
 2367            _ => {
 2368                start = buffer.anchor_before(0);
 2369                end = buffer.anchor_before(buffer.len());
 2370                mode = SelectMode::All;
 2371                auto_scroll = false;
 2372            }
 2373        }
 2374        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2375
 2376        let point_to_delete: Option<usize> = {
 2377            let selected_points: Vec<Selection<Point>> =
 2378                self.selections.disjoint_in_range(start..end, cx);
 2379
 2380            if !add || click_count > 1 {
 2381                None
 2382            } else if !selected_points.is_empty() {
 2383                Some(selected_points[0].id)
 2384            } else {
 2385                let clicked_point_already_selected =
 2386                    self.selections.disjoint.iter().find(|selection| {
 2387                        selection.start.to_point(buffer) == start.to_point(buffer)
 2388                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2389                    });
 2390
 2391                clicked_point_already_selected.map(|selection| selection.id)
 2392            }
 2393        };
 2394
 2395        let selections_count = self.selections.count();
 2396
 2397        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2398            if let Some(point_to_delete) = point_to_delete {
 2399                s.delete(point_to_delete);
 2400
 2401                if selections_count == 1 {
 2402                    s.set_pending_anchor_range(start..end, mode);
 2403                }
 2404            } else {
 2405                if !add {
 2406                    s.clear_disjoint();
 2407                } else if click_count > 1 {
 2408                    s.delete(newest_selection.id)
 2409                }
 2410
 2411                s.set_pending_anchor_range(start..end, mode);
 2412            }
 2413        });
 2414    }
 2415
 2416    fn begin_columnar_selection(
 2417        &mut self,
 2418        position: DisplayPoint,
 2419        goal_column: u32,
 2420        reset: bool,
 2421        window: &mut Window,
 2422        cx: &mut Context<Self>,
 2423    ) {
 2424        if !self.focus_handle.is_focused(window) {
 2425            self.last_focused_descendant = None;
 2426            window.focus(&self.focus_handle);
 2427        }
 2428
 2429        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2430
 2431        if reset {
 2432            let pointer_position = display_map
 2433                .buffer_snapshot
 2434                .anchor_before(position.to_point(&display_map));
 2435
 2436            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2437                s.clear_disjoint();
 2438                s.set_pending_anchor_range(
 2439                    pointer_position..pointer_position,
 2440                    SelectMode::Character,
 2441                );
 2442            });
 2443        }
 2444
 2445        let tail = self.selections.newest::<Point>(cx).tail();
 2446        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2447
 2448        if !reset {
 2449            self.select_columns(
 2450                tail.to_display_point(&display_map),
 2451                position,
 2452                goal_column,
 2453                &display_map,
 2454                window,
 2455                cx,
 2456            );
 2457        }
 2458    }
 2459
 2460    fn update_selection(
 2461        &mut self,
 2462        position: DisplayPoint,
 2463        goal_column: u32,
 2464        scroll_delta: gpui::Point<f32>,
 2465        window: &mut Window,
 2466        cx: &mut Context<Self>,
 2467    ) {
 2468        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2469
 2470        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2471            let tail = tail.to_display_point(&display_map);
 2472            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2473        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2474            let buffer = self.buffer.read(cx).snapshot(cx);
 2475            let head;
 2476            let tail;
 2477            let mode = self.selections.pending_mode().unwrap();
 2478            match &mode {
 2479                SelectMode::Character => {
 2480                    head = position.to_point(&display_map);
 2481                    tail = pending.tail().to_point(&buffer);
 2482                }
 2483                SelectMode::Word(original_range) => {
 2484                    let original_display_range = original_range.start.to_display_point(&display_map)
 2485                        ..original_range.end.to_display_point(&display_map);
 2486                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2487                        ..original_display_range.end.to_point(&display_map);
 2488                    if movement::is_inside_word(&display_map, position)
 2489                        || original_display_range.contains(&position)
 2490                    {
 2491                        let word_range = movement::surrounding_word(&display_map, position);
 2492                        if word_range.start < original_display_range.start {
 2493                            head = word_range.start.to_point(&display_map);
 2494                        } else {
 2495                            head = word_range.end.to_point(&display_map);
 2496                        }
 2497                    } else {
 2498                        head = position.to_point(&display_map);
 2499                    }
 2500
 2501                    if head <= original_buffer_range.start {
 2502                        tail = original_buffer_range.end;
 2503                    } else {
 2504                        tail = original_buffer_range.start;
 2505                    }
 2506                }
 2507                SelectMode::Line(original_range) => {
 2508                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2509
 2510                    let position = display_map
 2511                        .clip_point(position, Bias::Left)
 2512                        .to_point(&display_map);
 2513                    let line_start = display_map.prev_line_boundary(position).0;
 2514                    let next_line_start = buffer.clip_point(
 2515                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2516                        Bias::Left,
 2517                    );
 2518
 2519                    if line_start < original_range.start {
 2520                        head = line_start
 2521                    } else {
 2522                        head = next_line_start
 2523                    }
 2524
 2525                    if head <= original_range.start {
 2526                        tail = original_range.end;
 2527                    } else {
 2528                        tail = original_range.start;
 2529                    }
 2530                }
 2531                SelectMode::All => {
 2532                    return;
 2533                }
 2534            };
 2535
 2536            if head < tail {
 2537                pending.start = buffer.anchor_before(head);
 2538                pending.end = buffer.anchor_before(tail);
 2539                pending.reversed = true;
 2540            } else {
 2541                pending.start = buffer.anchor_before(tail);
 2542                pending.end = buffer.anchor_before(head);
 2543                pending.reversed = false;
 2544            }
 2545
 2546            self.change_selections(None, window, cx, |s| {
 2547                s.set_pending(pending, mode);
 2548            });
 2549        } else {
 2550            log::error!("update_selection dispatched with no pending selection");
 2551            return;
 2552        }
 2553
 2554        self.apply_scroll_delta(scroll_delta, window, cx);
 2555        cx.notify();
 2556    }
 2557
 2558    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2559        self.columnar_selection_tail.take();
 2560        if self.selections.pending_anchor().is_some() {
 2561            let selections = self.selections.all::<usize>(cx);
 2562            self.change_selections(None, window, cx, |s| {
 2563                s.select(selections);
 2564                s.clear_pending();
 2565            });
 2566        }
 2567    }
 2568
 2569    fn select_columns(
 2570        &mut self,
 2571        tail: DisplayPoint,
 2572        head: DisplayPoint,
 2573        goal_column: u32,
 2574        display_map: &DisplaySnapshot,
 2575        window: &mut Window,
 2576        cx: &mut Context<Self>,
 2577    ) {
 2578        let start_row = cmp::min(tail.row(), head.row());
 2579        let end_row = cmp::max(tail.row(), head.row());
 2580        let start_column = cmp::min(tail.column(), goal_column);
 2581        let end_column = cmp::max(tail.column(), goal_column);
 2582        let reversed = start_column < tail.column();
 2583
 2584        let selection_ranges = (start_row.0..=end_row.0)
 2585            .map(DisplayRow)
 2586            .filter_map(|row| {
 2587                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2588                    let start = display_map
 2589                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2590                        .to_point(display_map);
 2591                    let end = display_map
 2592                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2593                        .to_point(display_map);
 2594                    if reversed {
 2595                        Some(end..start)
 2596                    } else {
 2597                        Some(start..end)
 2598                    }
 2599                } else {
 2600                    None
 2601                }
 2602            })
 2603            .collect::<Vec<_>>();
 2604
 2605        self.change_selections(None, window, cx, |s| {
 2606            s.select_ranges(selection_ranges);
 2607        });
 2608        cx.notify();
 2609    }
 2610
 2611    pub fn has_pending_nonempty_selection(&self) -> bool {
 2612        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2613            Some(Selection { start, end, .. }) => start != end,
 2614            None => false,
 2615        };
 2616
 2617        pending_nonempty_selection
 2618            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2619    }
 2620
 2621    pub fn has_pending_selection(&self) -> bool {
 2622        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2623    }
 2624
 2625    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2626        self.selection_mark_mode = false;
 2627
 2628        if self.clear_expanded_diff_hunks(cx) {
 2629            cx.notify();
 2630            return;
 2631        }
 2632        if self.dismiss_menus_and_popups(true, window, cx) {
 2633            return;
 2634        }
 2635
 2636        if self.mode == EditorMode::Full
 2637            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2638        {
 2639            return;
 2640        }
 2641
 2642        cx.propagate();
 2643    }
 2644
 2645    pub fn dismiss_menus_and_popups(
 2646        &mut self,
 2647        is_user_requested: bool,
 2648        window: &mut Window,
 2649        cx: &mut Context<Self>,
 2650    ) -> bool {
 2651        if self.take_rename(false, window, cx).is_some() {
 2652            return true;
 2653        }
 2654
 2655        if hide_hover(self, cx) {
 2656            return true;
 2657        }
 2658
 2659        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2660            return true;
 2661        }
 2662
 2663        if self.hide_context_menu(window, cx).is_some() {
 2664            return true;
 2665        }
 2666
 2667        if self.mouse_context_menu.take().is_some() {
 2668            return true;
 2669        }
 2670
 2671        if is_user_requested && self.discard_inline_completion(true, cx) {
 2672            return true;
 2673        }
 2674
 2675        if self.snippet_stack.pop().is_some() {
 2676            return true;
 2677        }
 2678
 2679        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2680            self.dismiss_diagnostics(cx);
 2681            return true;
 2682        }
 2683
 2684        false
 2685    }
 2686
 2687    fn linked_editing_ranges_for(
 2688        &self,
 2689        selection: Range<text::Anchor>,
 2690        cx: &App,
 2691    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2692        if self.linked_edit_ranges.is_empty() {
 2693            return None;
 2694        }
 2695        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2696            selection.end.buffer_id.and_then(|end_buffer_id| {
 2697                if selection.start.buffer_id != Some(end_buffer_id) {
 2698                    return None;
 2699                }
 2700                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2701                let snapshot = buffer.read(cx).snapshot();
 2702                self.linked_edit_ranges
 2703                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2704                    .map(|ranges| (ranges, snapshot, buffer))
 2705            })?;
 2706        use text::ToOffset as TO;
 2707        // find offset from the start of current range to current cursor position
 2708        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2709
 2710        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2711        let start_difference = start_offset - start_byte_offset;
 2712        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2713        let end_difference = end_offset - start_byte_offset;
 2714        // Current range has associated linked ranges.
 2715        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2716        for range in linked_ranges.iter() {
 2717            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2718            let end_offset = start_offset + end_difference;
 2719            let start_offset = start_offset + start_difference;
 2720            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2721                continue;
 2722            }
 2723            if self.selections.disjoint_anchor_ranges().any(|s| {
 2724                if s.start.buffer_id != selection.start.buffer_id
 2725                    || s.end.buffer_id != selection.end.buffer_id
 2726                {
 2727                    return false;
 2728                }
 2729                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2730                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2731            }) {
 2732                continue;
 2733            }
 2734            let start = buffer_snapshot.anchor_after(start_offset);
 2735            let end = buffer_snapshot.anchor_after(end_offset);
 2736            linked_edits
 2737                .entry(buffer.clone())
 2738                .or_default()
 2739                .push(start..end);
 2740        }
 2741        Some(linked_edits)
 2742    }
 2743
 2744    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2745        let text: Arc<str> = text.into();
 2746
 2747        if self.read_only(cx) {
 2748            return;
 2749        }
 2750
 2751        let selections = self.selections.all_adjusted(cx);
 2752        let mut bracket_inserted = false;
 2753        let mut edits = Vec::new();
 2754        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2755        let mut new_selections = Vec::with_capacity(selections.len());
 2756        let mut new_autoclose_regions = Vec::new();
 2757        let snapshot = self.buffer.read(cx).read(cx);
 2758
 2759        for (selection, autoclose_region) in
 2760            self.selections_with_autoclose_regions(selections, &snapshot)
 2761        {
 2762            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2763                // Determine if the inserted text matches the opening or closing
 2764                // bracket of any of this language's bracket pairs.
 2765                let mut bracket_pair = None;
 2766                let mut is_bracket_pair_start = false;
 2767                let mut is_bracket_pair_end = false;
 2768                if !text.is_empty() {
 2769                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2770                    //  and they are removing the character that triggered IME popup.
 2771                    for (pair, enabled) in scope.brackets() {
 2772                        if !pair.close && !pair.surround {
 2773                            continue;
 2774                        }
 2775
 2776                        if enabled && pair.start.ends_with(text.as_ref()) {
 2777                            let prefix_len = pair.start.len() - text.len();
 2778                            let preceding_text_matches_prefix = prefix_len == 0
 2779                                || (selection.start.column >= (prefix_len as u32)
 2780                                    && snapshot.contains_str_at(
 2781                                        Point::new(
 2782                                            selection.start.row,
 2783                                            selection.start.column - (prefix_len as u32),
 2784                                        ),
 2785                                        &pair.start[..prefix_len],
 2786                                    ));
 2787                            if preceding_text_matches_prefix {
 2788                                bracket_pair = Some(pair.clone());
 2789                                is_bracket_pair_start = true;
 2790                                break;
 2791                            }
 2792                        }
 2793                        if pair.end.as_str() == text.as_ref() {
 2794                            bracket_pair = Some(pair.clone());
 2795                            is_bracket_pair_end = true;
 2796                            break;
 2797                        }
 2798                    }
 2799                }
 2800
 2801                if let Some(bracket_pair) = bracket_pair {
 2802                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2803                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2804                    let auto_surround =
 2805                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2806                    if selection.is_empty() {
 2807                        if is_bracket_pair_start {
 2808                            // If the inserted text is a suffix of an opening bracket and the
 2809                            // selection is preceded by the rest of the opening bracket, then
 2810                            // insert the closing bracket.
 2811                            let following_text_allows_autoclose = snapshot
 2812                                .chars_at(selection.start)
 2813                                .next()
 2814                                .map_or(true, |c| scope.should_autoclose_before(c));
 2815
 2816                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2817                                && bracket_pair.start.len() == 1
 2818                            {
 2819                                let target = bracket_pair.start.chars().next().unwrap();
 2820                                let current_line_count = snapshot
 2821                                    .reversed_chars_at(selection.start)
 2822                                    .take_while(|&c| c != '\n')
 2823                                    .filter(|&c| c == target)
 2824                                    .count();
 2825                                current_line_count % 2 == 1
 2826                            } else {
 2827                                false
 2828                            };
 2829
 2830                            if autoclose
 2831                                && bracket_pair.close
 2832                                && following_text_allows_autoclose
 2833                                && !is_closing_quote
 2834                            {
 2835                                let anchor = snapshot.anchor_before(selection.end);
 2836                                new_selections.push((selection.map(|_| anchor), text.len()));
 2837                                new_autoclose_regions.push((
 2838                                    anchor,
 2839                                    text.len(),
 2840                                    selection.id,
 2841                                    bracket_pair.clone(),
 2842                                ));
 2843                                edits.push((
 2844                                    selection.range(),
 2845                                    format!("{}{}", text, bracket_pair.end).into(),
 2846                                ));
 2847                                bracket_inserted = true;
 2848                                continue;
 2849                            }
 2850                        }
 2851
 2852                        if let Some(region) = autoclose_region {
 2853                            // If the selection is followed by an auto-inserted closing bracket,
 2854                            // then don't insert that closing bracket again; just move the selection
 2855                            // past the closing bracket.
 2856                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2857                                && text.as_ref() == region.pair.end.as_str();
 2858                            if should_skip {
 2859                                let anchor = snapshot.anchor_after(selection.end);
 2860                                new_selections
 2861                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2862                                continue;
 2863                            }
 2864                        }
 2865
 2866                        let always_treat_brackets_as_autoclosed = snapshot
 2867                            .settings_at(selection.start, cx)
 2868                            .always_treat_brackets_as_autoclosed;
 2869                        if always_treat_brackets_as_autoclosed
 2870                            && is_bracket_pair_end
 2871                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2872                        {
 2873                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2874                            // and the inserted text is a closing bracket and the selection is followed
 2875                            // by the closing bracket then move the selection past the closing bracket.
 2876                            let anchor = snapshot.anchor_after(selection.end);
 2877                            new_selections.push((selection.map(|_| anchor), text.len()));
 2878                            continue;
 2879                        }
 2880                    }
 2881                    // If an opening bracket is 1 character long and is typed while
 2882                    // text is selected, then surround that text with the bracket pair.
 2883                    else if auto_surround
 2884                        && bracket_pair.surround
 2885                        && is_bracket_pair_start
 2886                        && bracket_pair.start.chars().count() == 1
 2887                    {
 2888                        edits.push((selection.start..selection.start, text.clone()));
 2889                        edits.push((
 2890                            selection.end..selection.end,
 2891                            bracket_pair.end.as_str().into(),
 2892                        ));
 2893                        bracket_inserted = true;
 2894                        new_selections.push((
 2895                            Selection {
 2896                                id: selection.id,
 2897                                start: snapshot.anchor_after(selection.start),
 2898                                end: snapshot.anchor_before(selection.end),
 2899                                reversed: selection.reversed,
 2900                                goal: selection.goal,
 2901                            },
 2902                            0,
 2903                        ));
 2904                        continue;
 2905                    }
 2906                }
 2907            }
 2908
 2909            if self.auto_replace_emoji_shortcode
 2910                && selection.is_empty()
 2911                && text.as_ref().ends_with(':')
 2912            {
 2913                if let Some(possible_emoji_short_code) =
 2914                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2915                {
 2916                    if !possible_emoji_short_code.is_empty() {
 2917                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2918                            let emoji_shortcode_start = Point::new(
 2919                                selection.start.row,
 2920                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2921                            );
 2922
 2923                            // Remove shortcode from buffer
 2924                            edits.push((
 2925                                emoji_shortcode_start..selection.start,
 2926                                "".to_string().into(),
 2927                            ));
 2928                            new_selections.push((
 2929                                Selection {
 2930                                    id: selection.id,
 2931                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2932                                    end: snapshot.anchor_before(selection.start),
 2933                                    reversed: selection.reversed,
 2934                                    goal: selection.goal,
 2935                                },
 2936                                0,
 2937                            ));
 2938
 2939                            // Insert emoji
 2940                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2941                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2942                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2943
 2944                            continue;
 2945                        }
 2946                    }
 2947                }
 2948            }
 2949
 2950            // If not handling any auto-close operation, then just replace the selected
 2951            // text with the given input and move the selection to the end of the
 2952            // newly inserted text.
 2953            let anchor = snapshot.anchor_after(selection.end);
 2954            if !self.linked_edit_ranges.is_empty() {
 2955                let start_anchor = snapshot.anchor_before(selection.start);
 2956
 2957                let is_word_char = text.chars().next().map_or(true, |char| {
 2958                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2959                    classifier.is_word(char)
 2960                });
 2961
 2962                if is_word_char {
 2963                    if let Some(ranges) = self
 2964                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2965                    {
 2966                        for (buffer, edits) in ranges {
 2967                            linked_edits
 2968                                .entry(buffer.clone())
 2969                                .or_default()
 2970                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2971                        }
 2972                    }
 2973                }
 2974            }
 2975
 2976            new_selections.push((selection.map(|_| anchor), 0));
 2977            edits.push((selection.start..selection.end, text.clone()));
 2978        }
 2979
 2980        drop(snapshot);
 2981
 2982        self.transact(window, cx, |this, window, cx| {
 2983            this.buffer.update(cx, |buffer, cx| {
 2984                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2985            });
 2986            for (buffer, edits) in linked_edits {
 2987                buffer.update(cx, |buffer, cx| {
 2988                    let snapshot = buffer.snapshot();
 2989                    let edits = edits
 2990                        .into_iter()
 2991                        .map(|(range, text)| {
 2992                            use text::ToPoint as TP;
 2993                            let end_point = TP::to_point(&range.end, &snapshot);
 2994                            let start_point = TP::to_point(&range.start, &snapshot);
 2995                            (start_point..end_point, text)
 2996                        })
 2997                        .sorted_by_key(|(range, _)| range.start)
 2998                        .collect::<Vec<_>>();
 2999                    buffer.edit(edits, None, cx);
 3000                })
 3001            }
 3002            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3003            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3004            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3005            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3006                .zip(new_selection_deltas)
 3007                .map(|(selection, delta)| Selection {
 3008                    id: selection.id,
 3009                    start: selection.start + delta,
 3010                    end: selection.end + delta,
 3011                    reversed: selection.reversed,
 3012                    goal: SelectionGoal::None,
 3013                })
 3014                .collect::<Vec<_>>();
 3015
 3016            let mut i = 0;
 3017            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3018                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3019                let start = map.buffer_snapshot.anchor_before(position);
 3020                let end = map.buffer_snapshot.anchor_after(position);
 3021                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3022                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3023                        Ordering::Less => i += 1,
 3024                        Ordering::Greater => break,
 3025                        Ordering::Equal => {
 3026                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3027                                Ordering::Less => i += 1,
 3028                                Ordering::Equal => break,
 3029                                Ordering::Greater => break,
 3030                            }
 3031                        }
 3032                    }
 3033                }
 3034                this.autoclose_regions.insert(
 3035                    i,
 3036                    AutocloseRegion {
 3037                        selection_id,
 3038                        range: start..end,
 3039                        pair,
 3040                    },
 3041                );
 3042            }
 3043
 3044            let had_active_inline_completion = this.has_active_inline_completion();
 3045            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3046                s.select(new_selections)
 3047            });
 3048
 3049            if !bracket_inserted {
 3050                if let Some(on_type_format_task) =
 3051                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3052                {
 3053                    on_type_format_task.detach_and_log_err(cx);
 3054                }
 3055            }
 3056
 3057            let editor_settings = EditorSettings::get_global(cx);
 3058            if bracket_inserted
 3059                && (editor_settings.auto_signature_help
 3060                    || editor_settings.show_signature_help_after_edits)
 3061            {
 3062                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3063            }
 3064
 3065            let trigger_in_words =
 3066                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3067            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3068            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3069            this.refresh_inline_completion(true, false, window, cx);
 3070        });
 3071    }
 3072
 3073    fn find_possible_emoji_shortcode_at_position(
 3074        snapshot: &MultiBufferSnapshot,
 3075        position: Point,
 3076    ) -> Option<String> {
 3077        let mut chars = Vec::new();
 3078        let mut found_colon = false;
 3079        for char in snapshot.reversed_chars_at(position).take(100) {
 3080            // Found a possible emoji shortcode in the middle of the buffer
 3081            if found_colon {
 3082                if char.is_whitespace() {
 3083                    chars.reverse();
 3084                    return Some(chars.iter().collect());
 3085                }
 3086                // If the previous character is not a whitespace, we are in the middle of a word
 3087                // and we only want to complete the shortcode if the word is made up of other emojis
 3088                let mut containing_word = String::new();
 3089                for ch in snapshot
 3090                    .reversed_chars_at(position)
 3091                    .skip(chars.len() + 1)
 3092                    .take(100)
 3093                {
 3094                    if ch.is_whitespace() {
 3095                        break;
 3096                    }
 3097                    containing_word.push(ch);
 3098                }
 3099                let containing_word = containing_word.chars().rev().collect::<String>();
 3100                if util::word_consists_of_emojis(containing_word.as_str()) {
 3101                    chars.reverse();
 3102                    return Some(chars.iter().collect());
 3103                }
 3104            }
 3105
 3106            if char.is_whitespace() || !char.is_ascii() {
 3107                return None;
 3108            }
 3109            if char == ':' {
 3110                found_colon = true;
 3111            } else {
 3112                chars.push(char);
 3113            }
 3114        }
 3115        // Found a possible emoji shortcode at the beginning of the buffer
 3116        chars.reverse();
 3117        Some(chars.iter().collect())
 3118    }
 3119
 3120    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3121        self.transact(window, cx, |this, window, cx| {
 3122            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3123                let selections = this.selections.all::<usize>(cx);
 3124                let multi_buffer = this.buffer.read(cx);
 3125                let buffer = multi_buffer.snapshot(cx);
 3126                selections
 3127                    .iter()
 3128                    .map(|selection| {
 3129                        let start_point = selection.start.to_point(&buffer);
 3130                        let mut indent =
 3131                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3132                        indent.len = cmp::min(indent.len, start_point.column);
 3133                        let start = selection.start;
 3134                        let end = selection.end;
 3135                        let selection_is_empty = start == end;
 3136                        let language_scope = buffer.language_scope_at(start);
 3137                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3138                            &language_scope
 3139                        {
 3140                            let leading_whitespace_len = buffer
 3141                                .reversed_chars_at(start)
 3142                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3143                                .map(|c| c.len_utf8())
 3144                                .sum::<usize>();
 3145
 3146                            let trailing_whitespace_len = buffer
 3147                                .chars_at(end)
 3148                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3149                                .map(|c| c.len_utf8())
 3150                                .sum::<usize>();
 3151
 3152                            let insert_extra_newline =
 3153                                language.brackets().any(|(pair, enabled)| {
 3154                                    let pair_start = pair.start.trim_end();
 3155                                    let pair_end = pair.end.trim_start();
 3156
 3157                                    enabled
 3158                                        && pair.newline
 3159                                        && buffer.contains_str_at(
 3160                                            end + trailing_whitespace_len,
 3161                                            pair_end,
 3162                                        )
 3163                                        && buffer.contains_str_at(
 3164                                            (start - leading_whitespace_len)
 3165                                                .saturating_sub(pair_start.len()),
 3166                                            pair_start,
 3167                                        )
 3168                                });
 3169
 3170                            // Comment extension on newline is allowed only for cursor selections
 3171                            let comment_delimiter = maybe!({
 3172                                if !selection_is_empty {
 3173                                    return None;
 3174                                }
 3175
 3176                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3177                                    return None;
 3178                                }
 3179
 3180                                let delimiters = language.line_comment_prefixes();
 3181                                let max_len_of_delimiter =
 3182                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3183                                let (snapshot, range) =
 3184                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3185
 3186                                let mut index_of_first_non_whitespace = 0;
 3187                                let comment_candidate = snapshot
 3188                                    .chars_for_range(range)
 3189                                    .skip_while(|c| {
 3190                                        let should_skip = c.is_whitespace();
 3191                                        if should_skip {
 3192                                            index_of_first_non_whitespace += 1;
 3193                                        }
 3194                                        should_skip
 3195                                    })
 3196                                    .take(max_len_of_delimiter)
 3197                                    .collect::<String>();
 3198                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3199                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3200                                })?;
 3201                                let cursor_is_placed_after_comment_marker =
 3202                                    index_of_first_non_whitespace + comment_prefix.len()
 3203                                        <= start_point.column as usize;
 3204                                if cursor_is_placed_after_comment_marker {
 3205                                    Some(comment_prefix.clone())
 3206                                } else {
 3207                                    None
 3208                                }
 3209                            });
 3210                            (comment_delimiter, insert_extra_newline)
 3211                        } else {
 3212                            (None, false)
 3213                        };
 3214
 3215                        let capacity_for_delimiter = comment_delimiter
 3216                            .as_deref()
 3217                            .map(str::len)
 3218                            .unwrap_or_default();
 3219                        let mut new_text =
 3220                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3221                        new_text.push('\n');
 3222                        new_text.extend(indent.chars());
 3223                        if let Some(delimiter) = &comment_delimiter {
 3224                            new_text.push_str(delimiter);
 3225                        }
 3226                        if insert_extra_newline {
 3227                            new_text = new_text.repeat(2);
 3228                        }
 3229
 3230                        let anchor = buffer.anchor_after(end);
 3231                        let new_selection = selection.map(|_| anchor);
 3232                        (
 3233                            (start..end, new_text),
 3234                            (insert_extra_newline, new_selection),
 3235                        )
 3236                    })
 3237                    .unzip()
 3238            };
 3239
 3240            this.edit_with_autoindent(edits, cx);
 3241            let buffer = this.buffer.read(cx).snapshot(cx);
 3242            let new_selections = selection_fixup_info
 3243                .into_iter()
 3244                .map(|(extra_newline_inserted, new_selection)| {
 3245                    let mut cursor = new_selection.end.to_point(&buffer);
 3246                    if extra_newline_inserted {
 3247                        cursor.row -= 1;
 3248                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3249                    }
 3250                    new_selection.map(|_| cursor)
 3251                })
 3252                .collect();
 3253
 3254            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3255                s.select(new_selections)
 3256            });
 3257            this.refresh_inline_completion(true, false, window, cx);
 3258        });
 3259    }
 3260
 3261    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3262        let buffer = self.buffer.read(cx);
 3263        let snapshot = buffer.snapshot(cx);
 3264
 3265        let mut edits = Vec::new();
 3266        let mut rows = Vec::new();
 3267
 3268        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3269            let cursor = selection.head();
 3270            let row = cursor.row;
 3271
 3272            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3273
 3274            let newline = "\n".to_string();
 3275            edits.push((start_of_line..start_of_line, newline));
 3276
 3277            rows.push(row + rows_inserted as u32);
 3278        }
 3279
 3280        self.transact(window, cx, |editor, window, cx| {
 3281            editor.edit(edits, cx);
 3282
 3283            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3284                let mut index = 0;
 3285                s.move_cursors_with(|map, _, _| {
 3286                    let row = rows[index];
 3287                    index += 1;
 3288
 3289                    let point = Point::new(row, 0);
 3290                    let boundary = map.next_line_boundary(point).1;
 3291                    let clipped = map.clip_point(boundary, Bias::Left);
 3292
 3293                    (clipped, SelectionGoal::None)
 3294                });
 3295            });
 3296
 3297            let mut indent_edits = Vec::new();
 3298            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3299            for row in rows {
 3300                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3301                for (row, indent) in indents {
 3302                    if indent.len == 0 {
 3303                        continue;
 3304                    }
 3305
 3306                    let text = match indent.kind {
 3307                        IndentKind::Space => " ".repeat(indent.len as usize),
 3308                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3309                    };
 3310                    let point = Point::new(row.0, 0);
 3311                    indent_edits.push((point..point, text));
 3312                }
 3313            }
 3314            editor.edit(indent_edits, cx);
 3315        });
 3316    }
 3317
 3318    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3319        let buffer = self.buffer.read(cx);
 3320        let snapshot = buffer.snapshot(cx);
 3321
 3322        let mut edits = Vec::new();
 3323        let mut rows = Vec::new();
 3324        let mut rows_inserted = 0;
 3325
 3326        for selection in self.selections.all_adjusted(cx) {
 3327            let cursor = selection.head();
 3328            let row = cursor.row;
 3329
 3330            let point = Point::new(row + 1, 0);
 3331            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3332
 3333            let newline = "\n".to_string();
 3334            edits.push((start_of_line..start_of_line, newline));
 3335
 3336            rows_inserted += 1;
 3337            rows.push(row + rows_inserted);
 3338        }
 3339
 3340        self.transact(window, cx, |editor, window, cx| {
 3341            editor.edit(edits, cx);
 3342
 3343            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3344                let mut index = 0;
 3345                s.move_cursors_with(|map, _, _| {
 3346                    let row = rows[index];
 3347                    index += 1;
 3348
 3349                    let point = Point::new(row, 0);
 3350                    let boundary = map.next_line_boundary(point).1;
 3351                    let clipped = map.clip_point(boundary, Bias::Left);
 3352
 3353                    (clipped, SelectionGoal::None)
 3354                });
 3355            });
 3356
 3357            let mut indent_edits = Vec::new();
 3358            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3359            for row in rows {
 3360                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3361                for (row, indent) in indents {
 3362                    if indent.len == 0 {
 3363                        continue;
 3364                    }
 3365
 3366                    let text = match indent.kind {
 3367                        IndentKind::Space => " ".repeat(indent.len as usize),
 3368                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3369                    };
 3370                    let point = Point::new(row.0, 0);
 3371                    indent_edits.push((point..point, text));
 3372                }
 3373            }
 3374            editor.edit(indent_edits, cx);
 3375        });
 3376    }
 3377
 3378    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3379        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3380            original_indent_columns: Vec::new(),
 3381        });
 3382        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3383    }
 3384
 3385    fn insert_with_autoindent_mode(
 3386        &mut self,
 3387        text: &str,
 3388        autoindent_mode: Option<AutoindentMode>,
 3389        window: &mut Window,
 3390        cx: &mut Context<Self>,
 3391    ) {
 3392        if self.read_only(cx) {
 3393            return;
 3394        }
 3395
 3396        let text: Arc<str> = text.into();
 3397        self.transact(window, cx, |this, window, cx| {
 3398            let old_selections = this.selections.all_adjusted(cx);
 3399            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3400                let anchors = {
 3401                    let snapshot = buffer.read(cx);
 3402                    old_selections
 3403                        .iter()
 3404                        .map(|s| {
 3405                            let anchor = snapshot.anchor_after(s.head());
 3406                            s.map(|_| anchor)
 3407                        })
 3408                        .collect::<Vec<_>>()
 3409                };
 3410                buffer.edit(
 3411                    old_selections
 3412                        .iter()
 3413                        .map(|s| (s.start..s.end, text.clone())),
 3414                    autoindent_mode,
 3415                    cx,
 3416                );
 3417                anchors
 3418            });
 3419
 3420            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3421                s.select_anchors(selection_anchors);
 3422            });
 3423
 3424            cx.notify();
 3425        });
 3426    }
 3427
 3428    fn trigger_completion_on_input(
 3429        &mut self,
 3430        text: &str,
 3431        trigger_in_words: bool,
 3432        window: &mut Window,
 3433        cx: &mut Context<Self>,
 3434    ) {
 3435        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3436            self.show_completions(
 3437                &ShowCompletions {
 3438                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3439                },
 3440                window,
 3441                cx,
 3442            );
 3443        } else {
 3444            self.hide_context_menu(window, cx);
 3445        }
 3446    }
 3447
 3448    fn is_completion_trigger(
 3449        &self,
 3450        text: &str,
 3451        trigger_in_words: bool,
 3452        cx: &mut Context<Self>,
 3453    ) -> bool {
 3454        let position = self.selections.newest_anchor().head();
 3455        let multibuffer = self.buffer.read(cx);
 3456        let Some(buffer) = position
 3457            .buffer_id
 3458            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3459        else {
 3460            return false;
 3461        };
 3462
 3463        if let Some(completion_provider) = &self.completion_provider {
 3464            completion_provider.is_completion_trigger(
 3465                &buffer,
 3466                position.text_anchor,
 3467                text,
 3468                trigger_in_words,
 3469                cx,
 3470            )
 3471        } else {
 3472            false
 3473        }
 3474    }
 3475
 3476    /// If any empty selections is touching the start of its innermost containing autoclose
 3477    /// region, expand it to select the brackets.
 3478    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3479        let selections = self.selections.all::<usize>(cx);
 3480        let buffer = self.buffer.read(cx).read(cx);
 3481        let new_selections = self
 3482            .selections_with_autoclose_regions(selections, &buffer)
 3483            .map(|(mut selection, region)| {
 3484                if !selection.is_empty() {
 3485                    return selection;
 3486                }
 3487
 3488                if let Some(region) = region {
 3489                    let mut range = region.range.to_offset(&buffer);
 3490                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3491                        range.start -= region.pair.start.len();
 3492                        if buffer.contains_str_at(range.start, &region.pair.start)
 3493                            && buffer.contains_str_at(range.end, &region.pair.end)
 3494                        {
 3495                            range.end += region.pair.end.len();
 3496                            selection.start = range.start;
 3497                            selection.end = range.end;
 3498
 3499                            return selection;
 3500                        }
 3501                    }
 3502                }
 3503
 3504                let always_treat_brackets_as_autoclosed = buffer
 3505                    .settings_at(selection.start, cx)
 3506                    .always_treat_brackets_as_autoclosed;
 3507
 3508                if !always_treat_brackets_as_autoclosed {
 3509                    return selection;
 3510                }
 3511
 3512                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3513                    for (pair, enabled) in scope.brackets() {
 3514                        if !enabled || !pair.close {
 3515                            continue;
 3516                        }
 3517
 3518                        if buffer.contains_str_at(selection.start, &pair.end) {
 3519                            let pair_start_len = pair.start.len();
 3520                            if buffer.contains_str_at(
 3521                                selection.start.saturating_sub(pair_start_len),
 3522                                &pair.start,
 3523                            ) {
 3524                                selection.start -= pair_start_len;
 3525                                selection.end += pair.end.len();
 3526
 3527                                return selection;
 3528                            }
 3529                        }
 3530                    }
 3531                }
 3532
 3533                selection
 3534            })
 3535            .collect();
 3536
 3537        drop(buffer);
 3538        self.change_selections(None, window, cx, |selections| {
 3539            selections.select(new_selections)
 3540        });
 3541    }
 3542
 3543    /// Iterate the given selections, and for each one, find the smallest surrounding
 3544    /// autoclose region. This uses the ordering of the selections and the autoclose
 3545    /// regions to avoid repeated comparisons.
 3546    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3547        &'a self,
 3548        selections: impl IntoIterator<Item = Selection<D>>,
 3549        buffer: &'a MultiBufferSnapshot,
 3550    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3551        let mut i = 0;
 3552        let mut regions = self.autoclose_regions.as_slice();
 3553        selections.into_iter().map(move |selection| {
 3554            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3555
 3556            let mut enclosing = None;
 3557            while let Some(pair_state) = regions.get(i) {
 3558                if pair_state.range.end.to_offset(buffer) < range.start {
 3559                    regions = &regions[i + 1..];
 3560                    i = 0;
 3561                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3562                    break;
 3563                } else {
 3564                    if pair_state.selection_id == selection.id {
 3565                        enclosing = Some(pair_state);
 3566                    }
 3567                    i += 1;
 3568                }
 3569            }
 3570
 3571            (selection, enclosing)
 3572        })
 3573    }
 3574
 3575    /// Remove any autoclose regions that no longer contain their selection.
 3576    fn invalidate_autoclose_regions(
 3577        &mut self,
 3578        mut selections: &[Selection<Anchor>],
 3579        buffer: &MultiBufferSnapshot,
 3580    ) {
 3581        self.autoclose_regions.retain(|state| {
 3582            let mut i = 0;
 3583            while let Some(selection) = selections.get(i) {
 3584                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3585                    selections = &selections[1..];
 3586                    continue;
 3587                }
 3588                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3589                    break;
 3590                }
 3591                if selection.id == state.selection_id {
 3592                    return true;
 3593                } else {
 3594                    i += 1;
 3595                }
 3596            }
 3597            false
 3598        });
 3599    }
 3600
 3601    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3602        let offset = position.to_offset(buffer);
 3603        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3604        if offset > word_range.start && kind == Some(CharKind::Word) {
 3605            Some(
 3606                buffer
 3607                    .text_for_range(word_range.start..offset)
 3608                    .collect::<String>(),
 3609            )
 3610        } else {
 3611            None
 3612        }
 3613    }
 3614
 3615    pub fn toggle_inlay_hints(
 3616        &mut self,
 3617        _: &ToggleInlayHints,
 3618        _: &mut Window,
 3619        cx: &mut Context<Self>,
 3620    ) {
 3621        self.refresh_inlay_hints(
 3622            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3623            cx,
 3624        );
 3625    }
 3626
 3627    pub fn inlay_hints_enabled(&self) -> bool {
 3628        self.inlay_hint_cache.enabled
 3629    }
 3630
 3631    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3632        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3633            return;
 3634        }
 3635
 3636        let reason_description = reason.description();
 3637        let ignore_debounce = matches!(
 3638            reason,
 3639            InlayHintRefreshReason::SettingsChange(_)
 3640                | InlayHintRefreshReason::Toggle(_)
 3641                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3642        );
 3643        let (invalidate_cache, required_languages) = match reason {
 3644            InlayHintRefreshReason::Toggle(enabled) => {
 3645                self.inlay_hint_cache.enabled = enabled;
 3646                if enabled {
 3647                    (InvalidationStrategy::RefreshRequested, None)
 3648                } else {
 3649                    self.inlay_hint_cache.clear();
 3650                    self.splice_inlays(
 3651                        &self
 3652                            .visible_inlay_hints(cx)
 3653                            .iter()
 3654                            .map(|inlay| inlay.id)
 3655                            .collect::<Vec<InlayId>>(),
 3656                        Vec::new(),
 3657                        cx,
 3658                    );
 3659                    return;
 3660                }
 3661            }
 3662            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3663                match self.inlay_hint_cache.update_settings(
 3664                    &self.buffer,
 3665                    new_settings,
 3666                    self.visible_inlay_hints(cx),
 3667                    cx,
 3668                ) {
 3669                    ControlFlow::Break(Some(InlaySplice {
 3670                        to_remove,
 3671                        to_insert,
 3672                    })) => {
 3673                        self.splice_inlays(&to_remove, to_insert, cx);
 3674                        return;
 3675                    }
 3676                    ControlFlow::Break(None) => return,
 3677                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3678                }
 3679            }
 3680            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3681                if let Some(InlaySplice {
 3682                    to_remove,
 3683                    to_insert,
 3684                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3685                {
 3686                    self.splice_inlays(&to_remove, to_insert, cx);
 3687                }
 3688                return;
 3689            }
 3690            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3691            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3692                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3693            }
 3694            InlayHintRefreshReason::RefreshRequested => {
 3695                (InvalidationStrategy::RefreshRequested, None)
 3696            }
 3697        };
 3698
 3699        if let Some(InlaySplice {
 3700            to_remove,
 3701            to_insert,
 3702        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3703            reason_description,
 3704            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3705            invalidate_cache,
 3706            ignore_debounce,
 3707            cx,
 3708        ) {
 3709            self.splice_inlays(&to_remove, to_insert, cx);
 3710        }
 3711    }
 3712
 3713    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3714        self.display_map
 3715            .read(cx)
 3716            .current_inlays()
 3717            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3718            .cloned()
 3719            .collect()
 3720    }
 3721
 3722    pub fn excerpts_for_inlay_hints_query(
 3723        &self,
 3724        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3725        cx: &mut Context<Editor>,
 3726    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3727        let Some(project) = self.project.as_ref() else {
 3728            return HashMap::default();
 3729        };
 3730        let project = project.read(cx);
 3731        let multi_buffer = self.buffer().read(cx);
 3732        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3733        let multi_buffer_visible_start = self
 3734            .scroll_manager
 3735            .anchor()
 3736            .anchor
 3737            .to_point(&multi_buffer_snapshot);
 3738        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3739            multi_buffer_visible_start
 3740                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3741            Bias::Left,
 3742        );
 3743        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3744        multi_buffer_snapshot
 3745            .range_to_buffer_ranges(multi_buffer_visible_range)
 3746            .into_iter()
 3747            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3748            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3749                let buffer_file = project::File::from_dyn(buffer.file())?;
 3750                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3751                let worktree_entry = buffer_worktree
 3752                    .read(cx)
 3753                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3754                if worktree_entry.is_ignored {
 3755                    return None;
 3756                }
 3757
 3758                let language = buffer.language()?;
 3759                if let Some(restrict_to_languages) = restrict_to_languages {
 3760                    if !restrict_to_languages.contains(language) {
 3761                        return None;
 3762                    }
 3763                }
 3764                Some((
 3765                    excerpt_id,
 3766                    (
 3767                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3768                        buffer.version().clone(),
 3769                        excerpt_visible_range,
 3770                    ),
 3771                ))
 3772            })
 3773            .collect()
 3774    }
 3775
 3776    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3777        TextLayoutDetails {
 3778            text_system: window.text_system().clone(),
 3779            editor_style: self.style.clone().unwrap(),
 3780            rem_size: window.rem_size(),
 3781            scroll_anchor: self.scroll_manager.anchor(),
 3782            visible_rows: self.visible_line_count(),
 3783            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3784        }
 3785    }
 3786
 3787    pub fn splice_inlays(
 3788        &self,
 3789        to_remove: &[InlayId],
 3790        to_insert: Vec<Inlay>,
 3791        cx: &mut Context<Self>,
 3792    ) {
 3793        self.display_map.update(cx, |display_map, cx| {
 3794            display_map.splice_inlays(to_remove, to_insert, cx)
 3795        });
 3796        cx.notify();
 3797    }
 3798
 3799    fn trigger_on_type_formatting(
 3800        &self,
 3801        input: String,
 3802        window: &mut Window,
 3803        cx: &mut Context<Self>,
 3804    ) -> Option<Task<Result<()>>> {
 3805        if input.len() != 1 {
 3806            return None;
 3807        }
 3808
 3809        let project = self.project.as_ref()?;
 3810        let position = self.selections.newest_anchor().head();
 3811        let (buffer, buffer_position) = self
 3812            .buffer
 3813            .read(cx)
 3814            .text_anchor_for_position(position, cx)?;
 3815
 3816        let settings = language_settings::language_settings(
 3817            buffer
 3818                .read(cx)
 3819                .language_at(buffer_position)
 3820                .map(|l| l.name()),
 3821            buffer.read(cx).file(),
 3822            cx,
 3823        );
 3824        if !settings.use_on_type_format {
 3825            return None;
 3826        }
 3827
 3828        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3829        // hence we do LSP request & edit on host side only — add formats to host's history.
 3830        let push_to_lsp_host_history = true;
 3831        // If this is not the host, append its history with new edits.
 3832        let push_to_client_history = project.read(cx).is_via_collab();
 3833
 3834        let on_type_formatting = project.update(cx, |project, cx| {
 3835            project.on_type_format(
 3836                buffer.clone(),
 3837                buffer_position,
 3838                input,
 3839                push_to_lsp_host_history,
 3840                cx,
 3841            )
 3842        });
 3843        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3844            if let Some(transaction) = on_type_formatting.await? {
 3845                if push_to_client_history {
 3846                    buffer
 3847                        .update(&mut cx, |buffer, _| {
 3848                            buffer.push_transaction(transaction, Instant::now());
 3849                        })
 3850                        .ok();
 3851                }
 3852                editor.update(&mut cx, |editor, cx| {
 3853                    editor.refresh_document_highlights(cx);
 3854                })?;
 3855            }
 3856            Ok(())
 3857        }))
 3858    }
 3859
 3860    pub fn show_completions(
 3861        &mut self,
 3862        options: &ShowCompletions,
 3863        window: &mut Window,
 3864        cx: &mut Context<Self>,
 3865    ) {
 3866        if self.pending_rename.is_some() {
 3867            return;
 3868        }
 3869
 3870        let Some(provider) = self.completion_provider.as_ref() else {
 3871            return;
 3872        };
 3873
 3874        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3875            return;
 3876        }
 3877
 3878        let position = self.selections.newest_anchor().head();
 3879        if position.diff_base_anchor.is_some() {
 3880            return;
 3881        }
 3882        let (buffer, buffer_position) =
 3883            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3884                output
 3885            } else {
 3886                return;
 3887            };
 3888        let show_completion_documentation = buffer
 3889            .read(cx)
 3890            .snapshot()
 3891            .settings_at(buffer_position, cx)
 3892            .show_completion_documentation;
 3893
 3894        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3895
 3896        let trigger_kind = match &options.trigger {
 3897            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3898                CompletionTriggerKind::TRIGGER_CHARACTER
 3899            }
 3900            _ => CompletionTriggerKind::INVOKED,
 3901        };
 3902        let completion_context = CompletionContext {
 3903            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3904                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3905                    Some(String::from(trigger))
 3906                } else {
 3907                    None
 3908                }
 3909            }),
 3910            trigger_kind,
 3911        };
 3912        let completions =
 3913            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3914        let sort_completions = provider.sort_completions();
 3915
 3916        let id = post_inc(&mut self.next_completion_id);
 3917        let task = cx.spawn_in(window, |editor, mut cx| {
 3918            async move {
 3919                editor.update(&mut cx, |this, _| {
 3920                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3921                })?;
 3922                let completions = completions.await.log_err();
 3923                let menu = if let Some(completions) = completions {
 3924                    let mut menu = CompletionsMenu::new(
 3925                        id,
 3926                        sort_completions,
 3927                        show_completion_documentation,
 3928                        position,
 3929                        buffer.clone(),
 3930                        completions.into(),
 3931                    );
 3932
 3933                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3934                        .await;
 3935
 3936                    menu.visible().then_some(menu)
 3937                } else {
 3938                    None
 3939                };
 3940
 3941                editor.update_in(&mut cx, |editor, window, cx| {
 3942                    match editor.context_menu.borrow().as_ref() {
 3943                        None => {}
 3944                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3945                            if prev_menu.id > id {
 3946                                return;
 3947                            }
 3948                        }
 3949                        _ => return,
 3950                    }
 3951
 3952                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3953                        let mut menu = menu.unwrap();
 3954                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3955
 3956                        *editor.context_menu.borrow_mut() =
 3957                            Some(CodeContextMenu::Completions(menu));
 3958
 3959                        if editor.show_edit_predictions_in_menu() {
 3960                            editor.update_visible_inline_completion(window, cx);
 3961                        } else {
 3962                            editor.discard_inline_completion(false, cx);
 3963                        }
 3964
 3965                        cx.notify();
 3966                    } else if editor.completion_tasks.len() <= 1 {
 3967                        // If there are no more completion tasks and the last menu was
 3968                        // empty, we should hide it.
 3969                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3970                        // If it was already hidden and we don't show inline
 3971                        // completions in the menu, we should also show the
 3972                        // inline-completion when available.
 3973                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3974                            editor.update_visible_inline_completion(window, cx);
 3975                        }
 3976                    }
 3977                })?;
 3978
 3979                Ok::<_, anyhow::Error>(())
 3980            }
 3981            .log_err()
 3982        });
 3983
 3984        self.completion_tasks.push((id, task));
 3985    }
 3986
 3987    pub fn confirm_completion(
 3988        &mut self,
 3989        action: &ConfirmCompletion,
 3990        window: &mut Window,
 3991        cx: &mut Context<Self>,
 3992    ) -> Option<Task<Result<()>>> {
 3993        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3994    }
 3995
 3996    pub fn compose_completion(
 3997        &mut self,
 3998        action: &ComposeCompletion,
 3999        window: &mut Window,
 4000        cx: &mut Context<Self>,
 4001    ) -> Option<Task<Result<()>>> {
 4002        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4003    }
 4004
 4005    fn do_completion(
 4006        &mut self,
 4007        item_ix: Option<usize>,
 4008        intent: CompletionIntent,
 4009        window: &mut Window,
 4010        cx: &mut Context<Editor>,
 4011    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4012        use language::ToOffset as _;
 4013
 4014        let completions_menu =
 4015            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4016                menu
 4017            } else {
 4018                return None;
 4019            };
 4020
 4021        let entries = completions_menu.entries.borrow();
 4022        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4023        if self.show_edit_predictions_in_menu() {
 4024            self.discard_inline_completion(true, cx);
 4025        }
 4026        let candidate_id = mat.candidate_id;
 4027        drop(entries);
 4028
 4029        let buffer_handle = completions_menu.buffer;
 4030        let completion = completions_menu
 4031            .completions
 4032            .borrow()
 4033            .get(candidate_id)?
 4034            .clone();
 4035        cx.stop_propagation();
 4036
 4037        let snippet;
 4038        let text;
 4039
 4040        if completion.is_snippet() {
 4041            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4042            text = snippet.as_ref().unwrap().text.clone();
 4043        } else {
 4044            snippet = None;
 4045            text = completion.new_text.clone();
 4046        };
 4047        let selections = self.selections.all::<usize>(cx);
 4048        let buffer = buffer_handle.read(cx);
 4049        let old_range = completion.old_range.to_offset(buffer);
 4050        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4051
 4052        let newest_selection = self.selections.newest_anchor();
 4053        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4054            return None;
 4055        }
 4056
 4057        let lookbehind = newest_selection
 4058            .start
 4059            .text_anchor
 4060            .to_offset(buffer)
 4061            .saturating_sub(old_range.start);
 4062        let lookahead = old_range
 4063            .end
 4064            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4065        let mut common_prefix_len = old_text
 4066            .bytes()
 4067            .zip(text.bytes())
 4068            .take_while(|(a, b)| a == b)
 4069            .count();
 4070
 4071        let snapshot = self.buffer.read(cx).snapshot(cx);
 4072        let mut range_to_replace: Option<Range<isize>> = None;
 4073        let mut ranges = Vec::new();
 4074        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4075        for selection in &selections {
 4076            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4077                let start = selection.start.saturating_sub(lookbehind);
 4078                let end = selection.end + lookahead;
 4079                if selection.id == newest_selection.id {
 4080                    range_to_replace = Some(
 4081                        ((start + common_prefix_len) as isize - selection.start as isize)
 4082                            ..(end as isize - selection.start as isize),
 4083                    );
 4084                }
 4085                ranges.push(start + common_prefix_len..end);
 4086            } else {
 4087                common_prefix_len = 0;
 4088                ranges.clear();
 4089                ranges.extend(selections.iter().map(|s| {
 4090                    if s.id == newest_selection.id {
 4091                        range_to_replace = Some(
 4092                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4093                                - selection.start as isize
 4094                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4095                                    - selection.start as isize,
 4096                        );
 4097                        old_range.clone()
 4098                    } else {
 4099                        s.start..s.end
 4100                    }
 4101                }));
 4102                break;
 4103            }
 4104            if !self.linked_edit_ranges.is_empty() {
 4105                let start_anchor = snapshot.anchor_before(selection.head());
 4106                let end_anchor = snapshot.anchor_after(selection.tail());
 4107                if let Some(ranges) = self
 4108                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4109                {
 4110                    for (buffer, edits) in ranges {
 4111                        linked_edits.entry(buffer.clone()).or_default().extend(
 4112                            edits
 4113                                .into_iter()
 4114                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4115                        );
 4116                    }
 4117                }
 4118            }
 4119        }
 4120        let text = &text[common_prefix_len..];
 4121
 4122        cx.emit(EditorEvent::InputHandled {
 4123            utf16_range_to_replace: range_to_replace,
 4124            text: text.into(),
 4125        });
 4126
 4127        self.transact(window, cx, |this, window, cx| {
 4128            if let Some(mut snippet) = snippet {
 4129                snippet.text = text.to_string();
 4130                for tabstop in snippet
 4131                    .tabstops
 4132                    .iter_mut()
 4133                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4134                {
 4135                    tabstop.start -= common_prefix_len as isize;
 4136                    tabstop.end -= common_prefix_len as isize;
 4137                }
 4138
 4139                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4140            } else {
 4141                this.buffer.update(cx, |buffer, cx| {
 4142                    buffer.edit(
 4143                        ranges.iter().map(|range| (range.clone(), text)),
 4144                        this.autoindent_mode.clone(),
 4145                        cx,
 4146                    );
 4147                });
 4148            }
 4149            for (buffer, edits) in linked_edits {
 4150                buffer.update(cx, |buffer, cx| {
 4151                    let snapshot = buffer.snapshot();
 4152                    let edits = edits
 4153                        .into_iter()
 4154                        .map(|(range, text)| {
 4155                            use text::ToPoint as TP;
 4156                            let end_point = TP::to_point(&range.end, &snapshot);
 4157                            let start_point = TP::to_point(&range.start, &snapshot);
 4158                            (start_point..end_point, text)
 4159                        })
 4160                        .sorted_by_key(|(range, _)| range.start)
 4161                        .collect::<Vec<_>>();
 4162                    buffer.edit(edits, None, cx);
 4163                })
 4164            }
 4165
 4166            this.refresh_inline_completion(true, false, window, cx);
 4167        });
 4168
 4169        let show_new_completions_on_confirm = completion
 4170            .confirm
 4171            .as_ref()
 4172            .map_or(false, |confirm| confirm(intent, window, cx));
 4173        if show_new_completions_on_confirm {
 4174            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4175        }
 4176
 4177        let provider = self.completion_provider.as_ref()?;
 4178        drop(completion);
 4179        let apply_edits = provider.apply_additional_edits_for_completion(
 4180            buffer_handle,
 4181            completions_menu.completions.clone(),
 4182            candidate_id,
 4183            true,
 4184            cx,
 4185        );
 4186
 4187        let editor_settings = EditorSettings::get_global(cx);
 4188        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4189            // After the code completion is finished, users often want to know what signatures are needed.
 4190            // so we should automatically call signature_help
 4191            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4192        }
 4193
 4194        Some(cx.foreground_executor().spawn(async move {
 4195            apply_edits.await?;
 4196            Ok(())
 4197        }))
 4198    }
 4199
 4200    pub fn toggle_code_actions(
 4201        &mut self,
 4202        action: &ToggleCodeActions,
 4203        window: &mut Window,
 4204        cx: &mut Context<Self>,
 4205    ) {
 4206        let mut context_menu = self.context_menu.borrow_mut();
 4207        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4208            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4209                // Toggle if we're selecting the same one
 4210                *context_menu = None;
 4211                cx.notify();
 4212                return;
 4213            } else {
 4214                // Otherwise, clear it and start a new one
 4215                *context_menu = None;
 4216                cx.notify();
 4217            }
 4218        }
 4219        drop(context_menu);
 4220        let snapshot = self.snapshot(window, cx);
 4221        let deployed_from_indicator = action.deployed_from_indicator;
 4222        let mut task = self.code_actions_task.take();
 4223        let action = action.clone();
 4224        cx.spawn_in(window, |editor, mut cx| async move {
 4225            while let Some(prev_task) = task {
 4226                prev_task.await.log_err();
 4227                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4228            }
 4229
 4230            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4231                if editor.focus_handle.is_focused(window) {
 4232                    let multibuffer_point = action
 4233                        .deployed_from_indicator
 4234                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4235                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4236                    let (buffer, buffer_row) = snapshot
 4237                        .buffer_snapshot
 4238                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4239                        .and_then(|(buffer_snapshot, range)| {
 4240                            editor
 4241                                .buffer
 4242                                .read(cx)
 4243                                .buffer(buffer_snapshot.remote_id())
 4244                                .map(|buffer| (buffer, range.start.row))
 4245                        })?;
 4246                    let (_, code_actions) = editor
 4247                        .available_code_actions
 4248                        .clone()
 4249                        .and_then(|(location, code_actions)| {
 4250                            let snapshot = location.buffer.read(cx).snapshot();
 4251                            let point_range = location.range.to_point(&snapshot);
 4252                            let point_range = point_range.start.row..=point_range.end.row;
 4253                            if point_range.contains(&buffer_row) {
 4254                                Some((location, code_actions))
 4255                            } else {
 4256                                None
 4257                            }
 4258                        })
 4259                        .unzip();
 4260                    let buffer_id = buffer.read(cx).remote_id();
 4261                    let tasks = editor
 4262                        .tasks
 4263                        .get(&(buffer_id, buffer_row))
 4264                        .map(|t| Arc::new(t.to_owned()));
 4265                    if tasks.is_none() && code_actions.is_none() {
 4266                        return None;
 4267                    }
 4268
 4269                    editor.completion_tasks.clear();
 4270                    editor.discard_inline_completion(false, cx);
 4271                    let task_context =
 4272                        tasks
 4273                            .as_ref()
 4274                            .zip(editor.project.clone())
 4275                            .map(|(tasks, project)| {
 4276                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4277                            });
 4278
 4279                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4280                        let task_context = match task_context {
 4281                            Some(task_context) => task_context.await,
 4282                            None => None,
 4283                        };
 4284                        let resolved_tasks =
 4285                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4286                                Rc::new(ResolvedTasks {
 4287                                    templates: tasks.resolve(&task_context).collect(),
 4288                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4289                                        multibuffer_point.row,
 4290                                        tasks.column,
 4291                                    )),
 4292                                })
 4293                            });
 4294                        let spawn_straight_away = resolved_tasks
 4295                            .as_ref()
 4296                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4297                            && code_actions
 4298                                .as_ref()
 4299                                .map_or(true, |actions| actions.is_empty());
 4300                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4301                            *editor.context_menu.borrow_mut() =
 4302                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4303                                    buffer,
 4304                                    actions: CodeActionContents {
 4305                                        tasks: resolved_tasks,
 4306                                        actions: code_actions,
 4307                                    },
 4308                                    selected_item: Default::default(),
 4309                                    scroll_handle: UniformListScrollHandle::default(),
 4310                                    deployed_from_indicator,
 4311                                }));
 4312                            if spawn_straight_away {
 4313                                if let Some(task) = editor.confirm_code_action(
 4314                                    &ConfirmCodeAction { item_ix: Some(0) },
 4315                                    window,
 4316                                    cx,
 4317                                ) {
 4318                                    cx.notify();
 4319                                    return task;
 4320                                }
 4321                            }
 4322                            cx.notify();
 4323                            Task::ready(Ok(()))
 4324                        }) {
 4325                            task.await
 4326                        } else {
 4327                            Ok(())
 4328                        }
 4329                    }))
 4330                } else {
 4331                    Some(Task::ready(Ok(())))
 4332                }
 4333            })?;
 4334            if let Some(task) = spawned_test_task {
 4335                task.await?;
 4336            }
 4337
 4338            Ok::<_, anyhow::Error>(())
 4339        })
 4340        .detach_and_log_err(cx);
 4341    }
 4342
 4343    pub fn confirm_code_action(
 4344        &mut self,
 4345        action: &ConfirmCodeAction,
 4346        window: &mut Window,
 4347        cx: &mut Context<Self>,
 4348    ) -> Option<Task<Result<()>>> {
 4349        let actions_menu =
 4350            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4351                menu
 4352            } else {
 4353                return None;
 4354            };
 4355        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4356        let action = actions_menu.actions.get(action_ix)?;
 4357        let title = action.label();
 4358        let buffer = actions_menu.buffer;
 4359        let workspace = self.workspace()?;
 4360
 4361        match action {
 4362            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4363                workspace.update(cx, |workspace, cx| {
 4364                    workspace::tasks::schedule_resolved_task(
 4365                        workspace,
 4366                        task_source_kind,
 4367                        resolved_task,
 4368                        false,
 4369                        cx,
 4370                    );
 4371
 4372                    Some(Task::ready(Ok(())))
 4373                })
 4374            }
 4375            CodeActionsItem::CodeAction {
 4376                excerpt_id,
 4377                action,
 4378                provider,
 4379            } => {
 4380                let apply_code_action =
 4381                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4382                let workspace = workspace.downgrade();
 4383                Some(cx.spawn_in(window, |editor, cx| async move {
 4384                    let project_transaction = apply_code_action.await?;
 4385                    Self::open_project_transaction(
 4386                        &editor,
 4387                        workspace,
 4388                        project_transaction,
 4389                        title,
 4390                        cx,
 4391                    )
 4392                    .await
 4393                }))
 4394            }
 4395        }
 4396    }
 4397
 4398    pub async fn open_project_transaction(
 4399        this: &WeakEntity<Editor>,
 4400        workspace: WeakEntity<Workspace>,
 4401        transaction: ProjectTransaction,
 4402        title: String,
 4403        mut cx: AsyncWindowContext,
 4404    ) -> Result<()> {
 4405        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4406        cx.update(|_, cx| {
 4407            entries.sort_unstable_by_key(|(buffer, _)| {
 4408                buffer.read(cx).file().map(|f| f.path().clone())
 4409            });
 4410        })?;
 4411
 4412        // If the project transaction's edits are all contained within this editor, then
 4413        // avoid opening a new editor to display them.
 4414
 4415        if let Some((buffer, transaction)) = entries.first() {
 4416            if entries.len() == 1 {
 4417                let excerpt = this.update(&mut cx, |editor, cx| {
 4418                    editor
 4419                        .buffer()
 4420                        .read(cx)
 4421                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4422                })?;
 4423                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4424                    if excerpted_buffer == *buffer {
 4425                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4426                            let excerpt_range = excerpt_range.to_offset(buffer);
 4427                            buffer
 4428                                .edited_ranges_for_transaction::<usize>(transaction)
 4429                                .all(|range| {
 4430                                    excerpt_range.start <= range.start
 4431                                        && excerpt_range.end >= range.end
 4432                                })
 4433                        })?;
 4434
 4435                        if all_edits_within_excerpt {
 4436                            return Ok(());
 4437                        }
 4438                    }
 4439                }
 4440            }
 4441        } else {
 4442            return Ok(());
 4443        }
 4444
 4445        let mut ranges_to_highlight = Vec::new();
 4446        let excerpt_buffer = cx.new(|cx| {
 4447            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4448            for (buffer_handle, transaction) in &entries {
 4449                let buffer = buffer_handle.read(cx);
 4450                ranges_to_highlight.extend(
 4451                    multibuffer.push_excerpts_with_context_lines(
 4452                        buffer_handle.clone(),
 4453                        buffer
 4454                            .edited_ranges_for_transaction::<usize>(transaction)
 4455                            .collect(),
 4456                        DEFAULT_MULTIBUFFER_CONTEXT,
 4457                        cx,
 4458                    ),
 4459                );
 4460            }
 4461            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4462            multibuffer
 4463        })?;
 4464
 4465        workspace.update_in(&mut cx, |workspace, window, cx| {
 4466            let project = workspace.project().clone();
 4467            let editor = cx
 4468                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4469            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4470            editor.update(cx, |editor, cx| {
 4471                editor.highlight_background::<Self>(
 4472                    &ranges_to_highlight,
 4473                    |theme| theme.editor_highlighted_line_background,
 4474                    cx,
 4475                );
 4476            });
 4477        })?;
 4478
 4479        Ok(())
 4480    }
 4481
 4482    pub fn clear_code_action_providers(&mut self) {
 4483        self.code_action_providers.clear();
 4484        self.available_code_actions.take();
 4485    }
 4486
 4487    pub fn add_code_action_provider(
 4488        &mut self,
 4489        provider: Rc<dyn CodeActionProvider>,
 4490        window: &mut Window,
 4491        cx: &mut Context<Self>,
 4492    ) {
 4493        if self
 4494            .code_action_providers
 4495            .iter()
 4496            .any(|existing_provider| existing_provider.id() == provider.id())
 4497        {
 4498            return;
 4499        }
 4500
 4501        self.code_action_providers.push(provider);
 4502        self.refresh_code_actions(window, cx);
 4503    }
 4504
 4505    pub fn remove_code_action_provider(
 4506        &mut self,
 4507        id: Arc<str>,
 4508        window: &mut Window,
 4509        cx: &mut Context<Self>,
 4510    ) {
 4511        self.code_action_providers
 4512            .retain(|provider| provider.id() != id);
 4513        self.refresh_code_actions(window, cx);
 4514    }
 4515
 4516    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4517        let buffer = self.buffer.read(cx);
 4518        let newest_selection = self.selections.newest_anchor().clone();
 4519        if newest_selection.head().diff_base_anchor.is_some() {
 4520            return None;
 4521        }
 4522        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4523        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4524        if start_buffer != end_buffer {
 4525            return None;
 4526        }
 4527
 4528        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4529            cx.background_executor()
 4530                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4531                .await;
 4532
 4533            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4534                let providers = this.code_action_providers.clone();
 4535                let tasks = this
 4536                    .code_action_providers
 4537                    .iter()
 4538                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4539                    .collect::<Vec<_>>();
 4540                (providers, tasks)
 4541            })?;
 4542
 4543            let mut actions = Vec::new();
 4544            for (provider, provider_actions) in
 4545                providers.into_iter().zip(future::join_all(tasks).await)
 4546            {
 4547                if let Some(provider_actions) = provider_actions.log_err() {
 4548                    actions.extend(provider_actions.into_iter().map(|action| {
 4549                        AvailableCodeAction {
 4550                            excerpt_id: newest_selection.start.excerpt_id,
 4551                            action,
 4552                            provider: provider.clone(),
 4553                        }
 4554                    }));
 4555                }
 4556            }
 4557
 4558            this.update(&mut cx, |this, cx| {
 4559                this.available_code_actions = if actions.is_empty() {
 4560                    None
 4561                } else {
 4562                    Some((
 4563                        Location {
 4564                            buffer: start_buffer,
 4565                            range: start..end,
 4566                        },
 4567                        actions.into(),
 4568                    ))
 4569                };
 4570                cx.notify();
 4571            })
 4572        }));
 4573        None
 4574    }
 4575
 4576    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4577        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4578            self.show_git_blame_inline = false;
 4579
 4580            self.show_git_blame_inline_delay_task =
 4581                Some(cx.spawn_in(window, |this, mut cx| async move {
 4582                    cx.background_executor().timer(delay).await;
 4583
 4584                    this.update(&mut cx, |this, cx| {
 4585                        this.show_git_blame_inline = true;
 4586                        cx.notify();
 4587                    })
 4588                    .log_err();
 4589                }));
 4590        }
 4591    }
 4592
 4593    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4594        if self.pending_rename.is_some() {
 4595            return None;
 4596        }
 4597
 4598        let provider = self.semantics_provider.clone()?;
 4599        let buffer = self.buffer.read(cx);
 4600        let newest_selection = self.selections.newest_anchor().clone();
 4601        let cursor_position = newest_selection.head();
 4602        let (cursor_buffer, cursor_buffer_position) =
 4603            buffer.text_anchor_for_position(cursor_position, cx)?;
 4604        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4605        if cursor_buffer != tail_buffer {
 4606            return None;
 4607        }
 4608        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4609        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4610            cx.background_executor()
 4611                .timer(Duration::from_millis(debounce))
 4612                .await;
 4613
 4614            let highlights = if let Some(highlights) = cx
 4615                .update(|cx| {
 4616                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4617                })
 4618                .ok()
 4619                .flatten()
 4620            {
 4621                highlights.await.log_err()
 4622            } else {
 4623                None
 4624            };
 4625
 4626            if let Some(highlights) = highlights {
 4627                this.update(&mut cx, |this, cx| {
 4628                    if this.pending_rename.is_some() {
 4629                        return;
 4630                    }
 4631
 4632                    let buffer_id = cursor_position.buffer_id;
 4633                    let buffer = this.buffer.read(cx);
 4634                    if !buffer
 4635                        .text_anchor_for_position(cursor_position, cx)
 4636                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4637                    {
 4638                        return;
 4639                    }
 4640
 4641                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4642                    let mut write_ranges = Vec::new();
 4643                    let mut read_ranges = Vec::new();
 4644                    for highlight in highlights {
 4645                        for (excerpt_id, excerpt_range) in
 4646                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4647                        {
 4648                            let start = highlight
 4649                                .range
 4650                                .start
 4651                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4652                            let end = highlight
 4653                                .range
 4654                                .end
 4655                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4656                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4657                                continue;
 4658                            }
 4659
 4660                            let range = Anchor {
 4661                                buffer_id,
 4662                                excerpt_id,
 4663                                text_anchor: start,
 4664                                diff_base_anchor: None,
 4665                            }..Anchor {
 4666                                buffer_id,
 4667                                excerpt_id,
 4668                                text_anchor: end,
 4669                                diff_base_anchor: None,
 4670                            };
 4671                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4672                                write_ranges.push(range);
 4673                            } else {
 4674                                read_ranges.push(range);
 4675                            }
 4676                        }
 4677                    }
 4678
 4679                    this.highlight_background::<DocumentHighlightRead>(
 4680                        &read_ranges,
 4681                        |theme| theme.editor_document_highlight_read_background,
 4682                        cx,
 4683                    );
 4684                    this.highlight_background::<DocumentHighlightWrite>(
 4685                        &write_ranges,
 4686                        |theme| theme.editor_document_highlight_write_background,
 4687                        cx,
 4688                    );
 4689                    cx.notify();
 4690                })
 4691                .log_err();
 4692            }
 4693        }));
 4694        None
 4695    }
 4696
 4697    pub fn refresh_inline_completion(
 4698        &mut self,
 4699        debounce: bool,
 4700        user_requested: bool,
 4701        window: &mut Window,
 4702        cx: &mut Context<Self>,
 4703    ) -> Option<()> {
 4704        let provider = self.edit_prediction_provider()?;
 4705        let cursor = self.selections.newest_anchor().head();
 4706        let (buffer, cursor_buffer_position) =
 4707            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4708
 4709        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4710            self.discard_inline_completion(false, cx);
 4711            return None;
 4712        }
 4713
 4714        if !user_requested
 4715            && (!self.should_show_edit_predictions()
 4716                || !self.is_focused(window)
 4717                || buffer.read(cx).is_empty())
 4718        {
 4719            self.discard_inline_completion(false, cx);
 4720            return None;
 4721        }
 4722
 4723        self.update_visible_inline_completion(window, cx);
 4724        provider.refresh(
 4725            self.project.clone(),
 4726            buffer,
 4727            cursor_buffer_position,
 4728            debounce,
 4729            cx,
 4730        );
 4731        Some(())
 4732    }
 4733
 4734    fn show_edit_predictions_in_menu(&self) -> bool {
 4735        match self.edit_prediction_settings {
 4736            EditPredictionSettings::Disabled => false,
 4737            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4738        }
 4739    }
 4740
 4741    pub fn edit_predictions_enabled(&self) -> bool {
 4742        match self.edit_prediction_settings {
 4743            EditPredictionSettings::Disabled => false,
 4744            EditPredictionSettings::Enabled { .. } => true,
 4745        }
 4746    }
 4747
 4748    fn edit_prediction_requires_modifier(&self) -> bool {
 4749        match self.edit_prediction_settings {
 4750            EditPredictionSettings::Disabled => false,
 4751            EditPredictionSettings::Enabled {
 4752                preview_requires_modifier,
 4753                ..
 4754            } => preview_requires_modifier,
 4755        }
 4756    }
 4757
 4758    fn edit_prediction_settings_at_position(
 4759        &self,
 4760        buffer: &Entity<Buffer>,
 4761        buffer_position: language::Anchor,
 4762        cx: &App,
 4763    ) -> EditPredictionSettings {
 4764        if self.mode != EditorMode::Full
 4765            || !self.show_inline_completions_override.unwrap_or(true)
 4766            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4767        {
 4768            return EditPredictionSettings::Disabled;
 4769        }
 4770
 4771        let buffer = buffer.read(cx);
 4772
 4773        let file = buffer.file();
 4774
 4775        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4776            return EditPredictionSettings::Disabled;
 4777        };
 4778
 4779        let by_provider = matches!(
 4780            self.menu_inline_completions_policy,
 4781            MenuInlineCompletionsPolicy::ByProvider
 4782        );
 4783
 4784        let show_in_menu = by_provider
 4785            && self
 4786                .edit_prediction_provider
 4787                .as_ref()
 4788                .map_or(false, |provider| {
 4789                    provider.provider.show_completions_in_menu()
 4790                });
 4791
 4792        let preview_requires_modifier =
 4793            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4794
 4795        EditPredictionSettings::Enabled {
 4796            show_in_menu,
 4797            preview_requires_modifier,
 4798        }
 4799    }
 4800
 4801    fn should_show_edit_predictions(&self) -> bool {
 4802        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4803    }
 4804
 4805    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4806        matches!(
 4807            self.edit_prediction_preview,
 4808            EditPredictionPreview::Active { .. }
 4809        )
 4810    }
 4811
 4812    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4813        let cursor = self.selections.newest_anchor().head();
 4814        if let Some((buffer, cursor_position)) =
 4815            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4816        {
 4817            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4818        } else {
 4819            false
 4820        }
 4821    }
 4822
 4823    fn inline_completions_enabled_in_buffer(
 4824        &self,
 4825        buffer: &Entity<Buffer>,
 4826        buffer_position: language::Anchor,
 4827        cx: &App,
 4828    ) -> bool {
 4829        maybe!({
 4830            let provider = self.edit_prediction_provider()?;
 4831            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4832                return Some(false);
 4833            }
 4834            let buffer = buffer.read(cx);
 4835            let Some(file) = buffer.file() else {
 4836                return Some(true);
 4837            };
 4838            let settings = all_language_settings(Some(file), cx);
 4839            Some(settings.inline_completions_enabled_for_path(file.path()))
 4840        })
 4841        .unwrap_or(false)
 4842    }
 4843
 4844    fn cycle_inline_completion(
 4845        &mut self,
 4846        direction: Direction,
 4847        window: &mut Window,
 4848        cx: &mut Context<Self>,
 4849    ) -> Option<()> {
 4850        let provider = self.edit_prediction_provider()?;
 4851        let cursor = self.selections.newest_anchor().head();
 4852        let (buffer, cursor_buffer_position) =
 4853            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4854        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4855            return None;
 4856        }
 4857
 4858        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4859        self.update_visible_inline_completion(window, cx);
 4860
 4861        Some(())
 4862    }
 4863
 4864    pub fn show_inline_completion(
 4865        &mut self,
 4866        _: &ShowEditPrediction,
 4867        window: &mut Window,
 4868        cx: &mut Context<Self>,
 4869    ) {
 4870        if !self.has_active_inline_completion() {
 4871            self.refresh_inline_completion(false, true, window, cx);
 4872            return;
 4873        }
 4874
 4875        self.update_visible_inline_completion(window, cx);
 4876    }
 4877
 4878    pub fn display_cursor_names(
 4879        &mut self,
 4880        _: &DisplayCursorNames,
 4881        window: &mut Window,
 4882        cx: &mut Context<Self>,
 4883    ) {
 4884        self.show_cursor_names(window, cx);
 4885    }
 4886
 4887    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4888        self.show_cursor_names = true;
 4889        cx.notify();
 4890        cx.spawn_in(window, |this, mut cx| async move {
 4891            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4892            this.update(&mut cx, |this, cx| {
 4893                this.show_cursor_names = false;
 4894                cx.notify()
 4895            })
 4896            .ok()
 4897        })
 4898        .detach();
 4899    }
 4900
 4901    pub fn next_edit_prediction(
 4902        &mut self,
 4903        _: &NextEditPrediction,
 4904        window: &mut Window,
 4905        cx: &mut Context<Self>,
 4906    ) {
 4907        if self.has_active_inline_completion() {
 4908            self.cycle_inline_completion(Direction::Next, window, cx);
 4909        } else {
 4910            let is_copilot_disabled = self
 4911                .refresh_inline_completion(false, true, window, cx)
 4912                .is_none();
 4913            if is_copilot_disabled {
 4914                cx.propagate();
 4915            }
 4916        }
 4917    }
 4918
 4919    pub fn previous_edit_prediction(
 4920        &mut self,
 4921        _: &PreviousEditPrediction,
 4922        window: &mut Window,
 4923        cx: &mut Context<Self>,
 4924    ) {
 4925        if self.has_active_inline_completion() {
 4926            self.cycle_inline_completion(Direction::Prev, window, cx);
 4927        } else {
 4928            let is_copilot_disabled = self
 4929                .refresh_inline_completion(false, true, window, cx)
 4930                .is_none();
 4931            if is_copilot_disabled {
 4932                cx.propagate();
 4933            }
 4934        }
 4935    }
 4936
 4937    pub fn accept_edit_prediction(
 4938        &mut self,
 4939        _: &AcceptEditPrediction,
 4940        window: &mut Window,
 4941        cx: &mut Context<Self>,
 4942    ) {
 4943        if self.show_edit_predictions_in_menu() {
 4944            self.hide_context_menu(window, cx);
 4945        }
 4946
 4947        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4948            return;
 4949        };
 4950
 4951        self.report_inline_completion_event(
 4952            active_inline_completion.completion_id.clone(),
 4953            true,
 4954            cx,
 4955        );
 4956
 4957        match &active_inline_completion.completion {
 4958            InlineCompletion::Move { target, .. } => {
 4959                let target = *target;
 4960
 4961                if let Some(position_map) = &self.last_position_map {
 4962                    if position_map
 4963                        .visible_row_range
 4964                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4965                        || !self.edit_prediction_requires_modifier()
 4966                    {
 4967                        // Note that this is also done in vim's handler of the Tab action.
 4968                        self.change_selections(
 4969                            Some(Autoscroll::newest()),
 4970                            window,
 4971                            cx,
 4972                            |selections| {
 4973                                selections.select_anchor_ranges([target..target]);
 4974                            },
 4975                        );
 4976                        self.clear_row_highlights::<EditPredictionPreview>();
 4977
 4978                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4979                            previous_scroll_position: None,
 4980                        };
 4981                    } else {
 4982                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4983                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 4984                        };
 4985                        self.highlight_rows::<EditPredictionPreview>(
 4986                            target..target,
 4987                            cx.theme().colors().editor_highlighted_line_background,
 4988                            true,
 4989                            cx,
 4990                        );
 4991                        self.request_autoscroll(Autoscroll::fit(), cx);
 4992                    }
 4993                }
 4994            }
 4995            InlineCompletion::Edit { edits, .. } => {
 4996                if let Some(provider) = self.edit_prediction_provider() {
 4997                    provider.accept(cx);
 4998                }
 4999
 5000                let snapshot = self.buffer.read(cx).snapshot(cx);
 5001                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5002
 5003                self.buffer.update(cx, |buffer, cx| {
 5004                    buffer.edit(edits.iter().cloned(), None, cx)
 5005                });
 5006
 5007                self.change_selections(None, window, cx, |s| {
 5008                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5009                });
 5010
 5011                self.update_visible_inline_completion(window, cx);
 5012                if self.active_inline_completion.is_none() {
 5013                    self.refresh_inline_completion(true, true, window, cx);
 5014                }
 5015
 5016                cx.notify();
 5017            }
 5018        }
 5019
 5020        self.edit_prediction_requires_modifier_in_leading_space = false;
 5021    }
 5022
 5023    pub fn accept_partial_inline_completion(
 5024        &mut self,
 5025        _: &AcceptPartialEditPrediction,
 5026        window: &mut Window,
 5027        cx: &mut Context<Self>,
 5028    ) {
 5029        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5030            return;
 5031        };
 5032        if self.selections.count() != 1 {
 5033            return;
 5034        }
 5035
 5036        self.report_inline_completion_event(
 5037            active_inline_completion.completion_id.clone(),
 5038            true,
 5039            cx,
 5040        );
 5041
 5042        match &active_inline_completion.completion {
 5043            InlineCompletion::Move { target, .. } => {
 5044                let target = *target;
 5045                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5046                    selections.select_anchor_ranges([target..target]);
 5047                });
 5048            }
 5049            InlineCompletion::Edit { edits, .. } => {
 5050                // Find an insertion that starts at the cursor position.
 5051                let snapshot = self.buffer.read(cx).snapshot(cx);
 5052                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5053                let insertion = edits.iter().find_map(|(range, text)| {
 5054                    let range = range.to_offset(&snapshot);
 5055                    if range.is_empty() && range.start == cursor_offset {
 5056                        Some(text)
 5057                    } else {
 5058                        None
 5059                    }
 5060                });
 5061
 5062                if let Some(text) = insertion {
 5063                    let mut partial_completion = text
 5064                        .chars()
 5065                        .by_ref()
 5066                        .take_while(|c| c.is_alphabetic())
 5067                        .collect::<String>();
 5068                    if partial_completion.is_empty() {
 5069                        partial_completion = text
 5070                            .chars()
 5071                            .by_ref()
 5072                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5073                            .collect::<String>();
 5074                    }
 5075
 5076                    cx.emit(EditorEvent::InputHandled {
 5077                        utf16_range_to_replace: None,
 5078                        text: partial_completion.clone().into(),
 5079                    });
 5080
 5081                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5082
 5083                    self.refresh_inline_completion(true, true, window, cx);
 5084                    cx.notify();
 5085                } else {
 5086                    self.accept_edit_prediction(&Default::default(), window, cx);
 5087                }
 5088            }
 5089        }
 5090    }
 5091
 5092    fn discard_inline_completion(
 5093        &mut self,
 5094        should_report_inline_completion_event: bool,
 5095        cx: &mut Context<Self>,
 5096    ) -> bool {
 5097        if should_report_inline_completion_event {
 5098            let completion_id = self
 5099                .active_inline_completion
 5100                .as_ref()
 5101                .and_then(|active_completion| active_completion.completion_id.clone());
 5102
 5103            self.report_inline_completion_event(completion_id, false, cx);
 5104        }
 5105
 5106        if let Some(provider) = self.edit_prediction_provider() {
 5107            provider.discard(cx);
 5108        }
 5109
 5110        self.take_active_inline_completion(cx)
 5111    }
 5112
 5113    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5114        let Some(provider) = self.edit_prediction_provider() else {
 5115            return;
 5116        };
 5117
 5118        let Some((_, buffer, _)) = self
 5119            .buffer
 5120            .read(cx)
 5121            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5122        else {
 5123            return;
 5124        };
 5125
 5126        let extension = buffer
 5127            .read(cx)
 5128            .file()
 5129            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5130
 5131        let event_type = match accepted {
 5132            true => "Edit Prediction Accepted",
 5133            false => "Edit Prediction Discarded",
 5134        };
 5135        telemetry::event!(
 5136            event_type,
 5137            provider = provider.name(),
 5138            prediction_id = id,
 5139            suggestion_accepted = accepted,
 5140            file_extension = extension,
 5141        );
 5142    }
 5143
 5144    pub fn has_active_inline_completion(&self) -> bool {
 5145        self.active_inline_completion.is_some()
 5146    }
 5147
 5148    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5149        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5150            return false;
 5151        };
 5152
 5153        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5154        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5155        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5156        true
 5157    }
 5158
 5159    /// Returns true when we're displaying the edit prediction popover below the cursor
 5160    /// like we are not previewing and the LSP autocomplete menu is visible
 5161    /// or we are in `when_holding_modifier` mode.
 5162    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5163        if self.edit_prediction_preview_is_active()
 5164            || !self.show_edit_predictions_in_menu()
 5165            || !self.edit_predictions_enabled()
 5166        {
 5167            return false;
 5168        }
 5169
 5170        if self.has_visible_completions_menu() {
 5171            return true;
 5172        }
 5173
 5174        has_completion && self.edit_prediction_requires_modifier()
 5175    }
 5176
 5177    fn handle_modifiers_changed(
 5178        &mut self,
 5179        modifiers: Modifiers,
 5180        position_map: &PositionMap,
 5181        window: &mut Window,
 5182        cx: &mut Context<Self>,
 5183    ) {
 5184        if self.show_edit_predictions_in_menu() {
 5185            self.update_edit_prediction_preview(&modifiers, window, cx);
 5186        }
 5187
 5188        let mouse_position = window.mouse_position();
 5189        if !position_map.text_hitbox.is_hovered(window) {
 5190            return;
 5191        }
 5192
 5193        self.update_hovered_link(
 5194            position_map.point_for_position(mouse_position),
 5195            &position_map.snapshot,
 5196            modifiers,
 5197            window,
 5198            cx,
 5199        )
 5200    }
 5201
 5202    fn update_edit_prediction_preview(
 5203        &mut self,
 5204        modifiers: &Modifiers,
 5205        window: &mut Window,
 5206        cx: &mut Context<Self>,
 5207    ) {
 5208        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5209        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5210            return;
 5211        };
 5212
 5213        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5214            if matches!(
 5215                self.edit_prediction_preview,
 5216                EditPredictionPreview::Inactive
 5217            ) {
 5218                self.edit_prediction_preview = EditPredictionPreview::Active {
 5219                    previous_scroll_position: None,
 5220                };
 5221
 5222                self.update_visible_inline_completion(window, cx);
 5223                cx.notify();
 5224            }
 5225        } else if let EditPredictionPreview::Active {
 5226            previous_scroll_position,
 5227        } = self.edit_prediction_preview
 5228        {
 5229            if let (Some(previous_scroll_position), Some(position_map)) =
 5230                (previous_scroll_position, self.last_position_map.as_ref())
 5231            {
 5232                self.set_scroll_position(
 5233                    previous_scroll_position
 5234                        .scroll_position(&position_map.snapshot.display_snapshot),
 5235                    window,
 5236                    cx,
 5237                );
 5238            }
 5239
 5240            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5241            self.clear_row_highlights::<EditPredictionPreview>();
 5242            self.update_visible_inline_completion(window, cx);
 5243            cx.notify();
 5244        }
 5245    }
 5246
 5247    fn update_visible_inline_completion(
 5248        &mut self,
 5249        _window: &mut Window,
 5250        cx: &mut Context<Self>,
 5251    ) -> Option<()> {
 5252        let selection = self.selections.newest_anchor();
 5253        let cursor = selection.head();
 5254        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5255        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5256        let excerpt_id = cursor.excerpt_id;
 5257
 5258        let show_in_menu = self.show_edit_predictions_in_menu();
 5259        let completions_menu_has_precedence = !show_in_menu
 5260            && (self.context_menu.borrow().is_some()
 5261                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5262
 5263        if completions_menu_has_precedence
 5264            || !offset_selection.is_empty()
 5265            || self
 5266                .active_inline_completion
 5267                .as_ref()
 5268                .map_or(false, |completion| {
 5269                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5270                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5271                    !invalidation_range.contains(&offset_selection.head())
 5272                })
 5273        {
 5274            self.discard_inline_completion(false, cx);
 5275            return None;
 5276        }
 5277
 5278        self.take_active_inline_completion(cx);
 5279        let Some(provider) = self.edit_prediction_provider() else {
 5280            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5281            return None;
 5282        };
 5283
 5284        let (buffer, cursor_buffer_position) =
 5285            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5286
 5287        self.edit_prediction_settings =
 5288            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5289
 5290        if !self.edit_prediction_settings.is_enabled() {
 5291            self.discard_inline_completion(false, cx);
 5292            return None;
 5293        }
 5294
 5295        self.edit_prediction_cursor_on_leading_whitespace =
 5296            multibuffer.is_line_whitespace_upto(cursor);
 5297
 5298        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5299        let edits = inline_completion
 5300            .edits
 5301            .into_iter()
 5302            .flat_map(|(range, new_text)| {
 5303                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5304                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5305                Some((start..end, new_text))
 5306            })
 5307            .collect::<Vec<_>>();
 5308        if edits.is_empty() {
 5309            return None;
 5310        }
 5311
 5312        let first_edit_start = edits.first().unwrap().0.start;
 5313        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5314        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5315
 5316        let last_edit_end = edits.last().unwrap().0.end;
 5317        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5318        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5319
 5320        let cursor_row = cursor.to_point(&multibuffer).row;
 5321
 5322        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5323
 5324        let mut inlay_ids = Vec::new();
 5325        let invalidation_row_range;
 5326        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5327            Some(cursor_row..edit_end_row)
 5328        } else if cursor_row > edit_end_row {
 5329            Some(edit_start_row..cursor_row)
 5330        } else {
 5331            None
 5332        };
 5333        let is_move =
 5334            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5335        let completion = if is_move {
 5336            invalidation_row_range =
 5337                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5338            let target = first_edit_start;
 5339            InlineCompletion::Move { target, snapshot }
 5340        } else {
 5341            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5342                && !self.inline_completions_hidden_for_vim_mode;
 5343
 5344            if show_completions_in_buffer {
 5345                if edits
 5346                    .iter()
 5347                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5348                {
 5349                    let mut inlays = Vec::new();
 5350                    for (range, new_text) in &edits {
 5351                        let inlay = Inlay::inline_completion(
 5352                            post_inc(&mut self.next_inlay_id),
 5353                            range.start,
 5354                            new_text.as_str(),
 5355                        );
 5356                        inlay_ids.push(inlay.id);
 5357                        inlays.push(inlay);
 5358                    }
 5359
 5360                    self.splice_inlays(&[], inlays, cx);
 5361                } else {
 5362                    let background_color = cx.theme().status().deleted_background;
 5363                    self.highlight_text::<InlineCompletionHighlight>(
 5364                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5365                        HighlightStyle {
 5366                            background_color: Some(background_color),
 5367                            ..Default::default()
 5368                        },
 5369                        cx,
 5370                    );
 5371                }
 5372            }
 5373
 5374            invalidation_row_range = edit_start_row..edit_end_row;
 5375
 5376            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5377                if provider.show_tab_accept_marker() {
 5378                    EditDisplayMode::TabAccept
 5379                } else {
 5380                    EditDisplayMode::Inline
 5381                }
 5382            } else {
 5383                EditDisplayMode::DiffPopover
 5384            };
 5385
 5386            InlineCompletion::Edit {
 5387                edits,
 5388                edit_preview: inline_completion.edit_preview,
 5389                display_mode,
 5390                snapshot,
 5391            }
 5392        };
 5393
 5394        let invalidation_range = multibuffer
 5395            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5396            ..multibuffer.anchor_after(Point::new(
 5397                invalidation_row_range.end,
 5398                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5399            ));
 5400
 5401        self.stale_inline_completion_in_menu = None;
 5402        self.active_inline_completion = Some(InlineCompletionState {
 5403            inlay_ids,
 5404            completion,
 5405            completion_id: inline_completion.id,
 5406            invalidation_range,
 5407        });
 5408
 5409        cx.notify();
 5410
 5411        Some(())
 5412    }
 5413
 5414    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5415        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5416    }
 5417
 5418    fn render_code_actions_indicator(
 5419        &self,
 5420        _style: &EditorStyle,
 5421        row: DisplayRow,
 5422        is_active: bool,
 5423        cx: &mut Context<Self>,
 5424    ) -> Option<IconButton> {
 5425        if self.available_code_actions.is_some() {
 5426            Some(
 5427                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5428                    .shape(ui::IconButtonShape::Square)
 5429                    .icon_size(IconSize::XSmall)
 5430                    .icon_color(Color::Muted)
 5431                    .toggle_state(is_active)
 5432                    .tooltip({
 5433                        let focus_handle = self.focus_handle.clone();
 5434                        move |window, cx| {
 5435                            Tooltip::for_action_in(
 5436                                "Toggle Code Actions",
 5437                                &ToggleCodeActions {
 5438                                    deployed_from_indicator: None,
 5439                                },
 5440                                &focus_handle,
 5441                                window,
 5442                                cx,
 5443                            )
 5444                        }
 5445                    })
 5446                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5447                        window.focus(&editor.focus_handle(cx));
 5448                        editor.toggle_code_actions(
 5449                            &ToggleCodeActions {
 5450                                deployed_from_indicator: Some(row),
 5451                            },
 5452                            window,
 5453                            cx,
 5454                        );
 5455                    })),
 5456            )
 5457        } else {
 5458            None
 5459        }
 5460    }
 5461
 5462    fn clear_tasks(&mut self) {
 5463        self.tasks.clear()
 5464    }
 5465
 5466    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5467        if self.tasks.insert(key, value).is_some() {
 5468            // This case should hopefully be rare, but just in case...
 5469            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5470        }
 5471    }
 5472
 5473    fn build_tasks_context(
 5474        project: &Entity<Project>,
 5475        buffer: &Entity<Buffer>,
 5476        buffer_row: u32,
 5477        tasks: &Arc<RunnableTasks>,
 5478        cx: &mut Context<Self>,
 5479    ) -> Task<Option<task::TaskContext>> {
 5480        let position = Point::new(buffer_row, tasks.column);
 5481        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5482        let location = Location {
 5483            buffer: buffer.clone(),
 5484            range: range_start..range_start,
 5485        };
 5486        // Fill in the environmental variables from the tree-sitter captures
 5487        let mut captured_task_variables = TaskVariables::default();
 5488        for (capture_name, value) in tasks.extra_variables.clone() {
 5489            captured_task_variables.insert(
 5490                task::VariableName::Custom(capture_name.into()),
 5491                value.clone(),
 5492            );
 5493        }
 5494        project.update(cx, |project, cx| {
 5495            project.task_store().update(cx, |task_store, cx| {
 5496                task_store.task_context_for_location(captured_task_variables, location, cx)
 5497            })
 5498        })
 5499    }
 5500
 5501    pub fn spawn_nearest_task(
 5502        &mut self,
 5503        action: &SpawnNearestTask,
 5504        window: &mut Window,
 5505        cx: &mut Context<Self>,
 5506    ) {
 5507        let Some((workspace, _)) = self.workspace.clone() else {
 5508            return;
 5509        };
 5510        let Some(project) = self.project.clone() else {
 5511            return;
 5512        };
 5513
 5514        // Try to find a closest, enclosing node using tree-sitter that has a
 5515        // task
 5516        let Some((buffer, buffer_row, tasks)) = self
 5517            .find_enclosing_node_task(cx)
 5518            // Or find the task that's closest in row-distance.
 5519            .or_else(|| self.find_closest_task(cx))
 5520        else {
 5521            return;
 5522        };
 5523
 5524        let reveal_strategy = action.reveal;
 5525        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5526        cx.spawn_in(window, |_, mut cx| async move {
 5527            let context = task_context.await?;
 5528            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5529
 5530            let resolved = resolved_task.resolved.as_mut()?;
 5531            resolved.reveal = reveal_strategy;
 5532
 5533            workspace
 5534                .update(&mut cx, |workspace, cx| {
 5535                    workspace::tasks::schedule_resolved_task(
 5536                        workspace,
 5537                        task_source_kind,
 5538                        resolved_task,
 5539                        false,
 5540                        cx,
 5541                    );
 5542                })
 5543                .ok()
 5544        })
 5545        .detach();
 5546    }
 5547
 5548    fn find_closest_task(
 5549        &mut self,
 5550        cx: &mut Context<Self>,
 5551    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5552        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5553
 5554        let ((buffer_id, row), tasks) = self
 5555            .tasks
 5556            .iter()
 5557            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5558
 5559        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5560        let tasks = Arc::new(tasks.to_owned());
 5561        Some((buffer, *row, tasks))
 5562    }
 5563
 5564    fn find_enclosing_node_task(
 5565        &mut self,
 5566        cx: &mut Context<Self>,
 5567    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5568        let snapshot = self.buffer.read(cx).snapshot(cx);
 5569        let offset = self.selections.newest::<usize>(cx).head();
 5570        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5571        let buffer_id = excerpt.buffer().remote_id();
 5572
 5573        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5574        let mut cursor = layer.node().walk();
 5575
 5576        while cursor.goto_first_child_for_byte(offset).is_some() {
 5577            if cursor.node().end_byte() == offset {
 5578                cursor.goto_next_sibling();
 5579            }
 5580        }
 5581
 5582        // Ascend to the smallest ancestor that contains the range and has a task.
 5583        loop {
 5584            let node = cursor.node();
 5585            let node_range = node.byte_range();
 5586            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5587
 5588            // Check if this node contains our offset
 5589            if node_range.start <= offset && node_range.end >= offset {
 5590                // If it contains offset, check for task
 5591                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5592                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5593                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5594                }
 5595            }
 5596
 5597            if !cursor.goto_parent() {
 5598                break;
 5599            }
 5600        }
 5601        None
 5602    }
 5603
 5604    fn render_run_indicator(
 5605        &self,
 5606        _style: &EditorStyle,
 5607        is_active: bool,
 5608        row: DisplayRow,
 5609        cx: &mut Context<Self>,
 5610    ) -> IconButton {
 5611        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5612            .shape(ui::IconButtonShape::Square)
 5613            .icon_size(IconSize::XSmall)
 5614            .icon_color(Color::Muted)
 5615            .toggle_state(is_active)
 5616            .on_click(cx.listener(move |editor, _e, window, cx| {
 5617                window.focus(&editor.focus_handle(cx));
 5618                editor.toggle_code_actions(
 5619                    &ToggleCodeActions {
 5620                        deployed_from_indicator: Some(row),
 5621                    },
 5622                    window,
 5623                    cx,
 5624                );
 5625            }))
 5626    }
 5627
 5628    pub fn context_menu_visible(&self) -> bool {
 5629        !self.edit_prediction_preview_is_active()
 5630            && self
 5631                .context_menu
 5632                .borrow()
 5633                .as_ref()
 5634                .map_or(false, |menu| menu.visible())
 5635    }
 5636
 5637    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5638        self.context_menu
 5639            .borrow()
 5640            .as_ref()
 5641            .map(|menu| menu.origin())
 5642    }
 5643
 5644    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5645        px(30.)
 5646    }
 5647
 5648    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5649        if self.read_only(cx) {
 5650            cx.theme().players().read_only()
 5651        } else {
 5652            self.style.as_ref().unwrap().local_player
 5653        }
 5654    }
 5655
 5656    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5657        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5658        let accept_keystroke = accept_binding.keystroke()?;
 5659        let colors = cx.theme().colors();
 5660        let accent_color = colors.text_accent;
 5661        let editor_bg_color = colors.editor_background;
 5662        let bg_color = editor_bg_color.blend(accent_color.opacity(0.1));
 5663
 5664        h_flex()
 5665            .px_0p5()
 5666            .gap_1()
 5667            .bg(bg_color)
 5668            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5669            .text_size(TextSize::XSmall.rems(cx))
 5670            .children(ui::render_modifiers(
 5671                &accept_keystroke.modifiers,
 5672                PlatformStyle::platform(),
 5673                Some(if accept_keystroke.modifiers == window.modifiers() {
 5674                    Color::Accent
 5675                } else {
 5676                    Color::Muted
 5677                }),
 5678                Some(IconSize::XSmall.rems().into()),
 5679                false,
 5680            ))
 5681            .child(accept_keystroke.key.clone())
 5682            .into()
 5683    }
 5684
 5685    fn render_edit_prediction_line_popover(
 5686        &self,
 5687        label: impl Into<SharedString>,
 5688        icon: Option<IconName>,
 5689        window: &mut Window,
 5690        cx: &App,
 5691    ) -> Option<Div> {
 5692        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5693
 5694        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5695
 5696        let result = h_flex()
 5697            .gap_1()
 5698            .border_1()
 5699            .rounded_lg()
 5700            .shadow_sm()
 5701            .bg(bg_color)
 5702            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5703            .py_0p5()
 5704            .pl_1()
 5705            .pr(padding_right)
 5706            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5707            .child(Label::new(label).size(LabelSize::Small))
 5708            .when_some(icon, |element, icon| {
 5709                element.child(
 5710                    div()
 5711                        .mt(px(1.5))
 5712                        .child(Icon::new(icon).size(IconSize::Small)),
 5713                )
 5714            });
 5715
 5716        Some(result)
 5717    }
 5718
 5719    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5720        let accent_color = cx.theme().colors().text_accent;
 5721        let editor_bg_color = cx.theme().colors().editor_background;
 5722        editor_bg_color.blend(accent_color.opacity(0.1))
 5723    }
 5724
 5725    #[allow(clippy::too_many_arguments)]
 5726    fn render_edit_prediction_cursor_popover(
 5727        &self,
 5728        min_width: Pixels,
 5729        max_width: Pixels,
 5730        cursor_point: Point,
 5731        style: &EditorStyle,
 5732        accept_keystroke: &gpui::Keystroke,
 5733        _window: &Window,
 5734        cx: &mut Context<Editor>,
 5735    ) -> Option<AnyElement> {
 5736        let provider = self.edit_prediction_provider.as_ref()?;
 5737
 5738        if provider.provider.needs_terms_acceptance(cx) {
 5739            return Some(
 5740                h_flex()
 5741                    .min_w(min_width)
 5742                    .flex_1()
 5743                    .px_2()
 5744                    .py_1()
 5745                    .gap_3()
 5746                    .elevation_2(cx)
 5747                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5748                    .id("accept-terms")
 5749                    .cursor_pointer()
 5750                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5751                    .on_click(cx.listener(|this, _event, window, cx| {
 5752                        cx.stop_propagation();
 5753                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5754                        window.dispatch_action(
 5755                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5756                            cx,
 5757                        );
 5758                    }))
 5759                    .child(
 5760                        h_flex()
 5761                            .flex_1()
 5762                            .gap_2()
 5763                            .child(Icon::new(IconName::ZedPredict))
 5764                            .child(Label::new("Accept Terms of Service"))
 5765                            .child(div().w_full())
 5766                            .child(
 5767                                Icon::new(IconName::ArrowUpRight)
 5768                                    .color(Color::Muted)
 5769                                    .size(IconSize::Small),
 5770                            )
 5771                            .into_any_element(),
 5772                    )
 5773                    .into_any(),
 5774            );
 5775        }
 5776
 5777        let is_refreshing = provider.provider.is_refreshing(cx);
 5778
 5779        fn pending_completion_container() -> Div {
 5780            h_flex()
 5781                .h_full()
 5782                .flex_1()
 5783                .gap_2()
 5784                .child(Icon::new(IconName::ZedPredict))
 5785        }
 5786
 5787        let completion = match &self.active_inline_completion {
 5788            Some(completion) => match &completion.completion {
 5789                InlineCompletion::Move {
 5790                    target, snapshot, ..
 5791                } if !self.has_visible_completions_menu() => {
 5792                    use text::ToPoint as _;
 5793
 5794                    return Some(
 5795                        h_flex()
 5796                            .px_2()
 5797                            .py_1()
 5798                            .elevation_2(cx)
 5799                            .border_color(cx.theme().colors().border)
 5800                            .rounded_tl(px(0.))
 5801                            .gap_2()
 5802                            .child(
 5803                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5804                                    Icon::new(IconName::ZedPredictDown)
 5805                                } else {
 5806                                    Icon::new(IconName::ZedPredictUp)
 5807                                },
 5808                            )
 5809                            .child(Label::new("Hold").size(LabelSize::Small))
 5810                            .children(ui::render_modifiers(
 5811                                &accept_keystroke.modifiers,
 5812                                PlatformStyle::platform(),
 5813                                Some(Color::Default),
 5814                                Some(IconSize::Small.rems().into()),
 5815                                true,
 5816                            ))
 5817                            .into_any(),
 5818                    );
 5819                }
 5820                _ => self.render_edit_prediction_cursor_popover_preview(
 5821                    completion,
 5822                    cursor_point,
 5823                    style,
 5824                    cx,
 5825                )?,
 5826            },
 5827
 5828            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5829                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5830                    stale_completion,
 5831                    cursor_point,
 5832                    style,
 5833                    cx,
 5834                )?,
 5835
 5836                None => {
 5837                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5838                }
 5839            },
 5840
 5841            None => pending_completion_container().child(Label::new("No Prediction")),
 5842        };
 5843
 5844        let completion = if is_refreshing {
 5845            completion
 5846                .with_animation(
 5847                    "loading-completion",
 5848                    Animation::new(Duration::from_secs(2))
 5849                        .repeat()
 5850                        .with_easing(pulsating_between(0.4, 0.8)),
 5851                    |label, delta| label.opacity(delta),
 5852                )
 5853                .into_any_element()
 5854        } else {
 5855            completion.into_any_element()
 5856        };
 5857
 5858        let has_completion = self.active_inline_completion.is_some();
 5859
 5860        Some(
 5861            h_flex()
 5862                .min_w(min_width)
 5863                .max_w(max_width)
 5864                .flex_1()
 5865                .elevation_2(cx)
 5866                .border_color(cx.theme().colors().border)
 5867                .child(
 5868                    div()
 5869                        .flex_1()
 5870                        .py_1()
 5871                        .px_2()
 5872                        .overflow_hidden()
 5873                        .child(completion),
 5874                )
 5875                .child(
 5876                    h_flex()
 5877                        .h_full()
 5878                        .border_l_1()
 5879                        .rounded_r_lg()
 5880                        .border_color(cx.theme().colors().border)
 5881                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5882                        .gap_1()
 5883                        .py_1()
 5884                        .px_2()
 5885                        .child(
 5886                            h_flex()
 5887                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5888                                .gap_1()
 5889                                .children(ui::render_modifiers(
 5890                                    &accept_keystroke.modifiers,
 5891                                    PlatformStyle::platform(),
 5892                                    Some(if !has_completion {
 5893                                        Color::Muted
 5894                                    } else {
 5895                                        Color::Default
 5896                                    }),
 5897                                    None,
 5898                                    true,
 5899                                )),
 5900                        )
 5901                        .child(Label::new("Preview").into_any_element())
 5902                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5903                )
 5904                .into_any(),
 5905        )
 5906    }
 5907
 5908    fn render_edit_prediction_cursor_popover_preview(
 5909        &self,
 5910        completion: &InlineCompletionState,
 5911        cursor_point: Point,
 5912        style: &EditorStyle,
 5913        cx: &mut Context<Editor>,
 5914    ) -> Option<Div> {
 5915        use text::ToPoint as _;
 5916
 5917        fn render_relative_row_jump(
 5918            prefix: impl Into<String>,
 5919            current_row: u32,
 5920            target_row: u32,
 5921        ) -> Div {
 5922            let (row_diff, arrow) = if target_row < current_row {
 5923                (current_row - target_row, IconName::ArrowUp)
 5924            } else {
 5925                (target_row - current_row, IconName::ArrowDown)
 5926            };
 5927
 5928            h_flex()
 5929                .child(
 5930                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5931                        .color(Color::Muted)
 5932                        .size(LabelSize::Small),
 5933                )
 5934                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5935        }
 5936
 5937        match &completion.completion {
 5938            InlineCompletion::Move {
 5939                target, snapshot, ..
 5940            } => Some(
 5941                h_flex()
 5942                    .px_2()
 5943                    .gap_2()
 5944                    .flex_1()
 5945                    .child(
 5946                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5947                            Icon::new(IconName::ZedPredictDown)
 5948                        } else {
 5949                            Icon::new(IconName::ZedPredictUp)
 5950                        },
 5951                    )
 5952                    .child(Label::new("Jump to Edit")),
 5953            ),
 5954
 5955            InlineCompletion::Edit {
 5956                edits,
 5957                edit_preview,
 5958                snapshot,
 5959                display_mode: _,
 5960            } => {
 5961                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5962
 5963                let highlighted_edits = crate::inline_completion_edit_text(
 5964                    &snapshot,
 5965                    &edits,
 5966                    edit_preview.as_ref()?,
 5967                    true,
 5968                    cx,
 5969                );
 5970
 5971                let len_total = highlighted_edits.text.len();
 5972                let first_line = &highlighted_edits.text
 5973                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5974                let first_line_len = first_line.len();
 5975
 5976                let first_highlight_start = highlighted_edits
 5977                    .highlights
 5978                    .first()
 5979                    .map_or(0, |(range, _)| range.start);
 5980                let drop_prefix_len = first_line
 5981                    .char_indices()
 5982                    .find(|(_, c)| !c.is_whitespace())
 5983                    .map_or(first_highlight_start, |(ix, _)| {
 5984                        ix.min(first_highlight_start)
 5985                    });
 5986
 5987                let preview_text = &first_line[drop_prefix_len..];
 5988                let preview_len = preview_text.len();
 5989                let highlights = highlighted_edits
 5990                    .highlights
 5991                    .into_iter()
 5992                    .take_until(|(range, _)| range.start > first_line_len)
 5993                    .map(|(range, style)| {
 5994                        (
 5995                            range.start - drop_prefix_len
 5996                                ..(range.end - drop_prefix_len).min(preview_len),
 5997                            style,
 5998                        )
 5999                    });
 6000
 6001                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 6002                    .with_highlights(&style.text, highlights);
 6003
 6004                let preview = h_flex()
 6005                    .gap_1()
 6006                    .min_w_16()
 6007                    .child(styled_text)
 6008                    .when(len_total > first_line_len, |parent| parent.child(""));
 6009
 6010                let left = if first_edit_row != cursor_point.row {
 6011                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6012                        .into_any_element()
 6013                } else {
 6014                    Icon::new(IconName::ZedPredict).into_any_element()
 6015                };
 6016
 6017                Some(
 6018                    h_flex()
 6019                        .h_full()
 6020                        .flex_1()
 6021                        .gap_2()
 6022                        .pr_1()
 6023                        .overflow_x_hidden()
 6024                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6025                        .child(left)
 6026                        .child(preview),
 6027                )
 6028            }
 6029        }
 6030    }
 6031
 6032    fn render_context_menu(
 6033        &self,
 6034        style: &EditorStyle,
 6035        max_height_in_lines: u32,
 6036        y_flipped: bool,
 6037        window: &mut Window,
 6038        cx: &mut Context<Editor>,
 6039    ) -> Option<AnyElement> {
 6040        let menu = self.context_menu.borrow();
 6041        let menu = menu.as_ref()?;
 6042        if !menu.visible() {
 6043            return None;
 6044        };
 6045        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6046    }
 6047
 6048    fn render_context_menu_aside(
 6049        &self,
 6050        style: &EditorStyle,
 6051        max_size: Size<Pixels>,
 6052        cx: &mut Context<Editor>,
 6053    ) -> Option<AnyElement> {
 6054        self.context_menu.borrow().as_ref().and_then(|menu| {
 6055            if menu.visible() {
 6056                menu.render_aside(
 6057                    style,
 6058                    max_size,
 6059                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6060                    cx,
 6061                )
 6062            } else {
 6063                None
 6064            }
 6065        })
 6066    }
 6067
 6068    fn hide_context_menu(
 6069        &mut self,
 6070        window: &mut Window,
 6071        cx: &mut Context<Self>,
 6072    ) -> Option<CodeContextMenu> {
 6073        cx.notify();
 6074        self.completion_tasks.clear();
 6075        let context_menu = self.context_menu.borrow_mut().take();
 6076        self.stale_inline_completion_in_menu.take();
 6077        self.update_visible_inline_completion(window, cx);
 6078        context_menu
 6079    }
 6080
 6081    fn show_snippet_choices(
 6082        &mut self,
 6083        choices: &Vec<String>,
 6084        selection: Range<Anchor>,
 6085        cx: &mut Context<Self>,
 6086    ) {
 6087        if selection.start.buffer_id.is_none() {
 6088            return;
 6089        }
 6090        let buffer_id = selection.start.buffer_id.unwrap();
 6091        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6092        let id = post_inc(&mut self.next_completion_id);
 6093
 6094        if let Some(buffer) = buffer {
 6095            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6096                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6097            ));
 6098        }
 6099    }
 6100
 6101    pub fn insert_snippet(
 6102        &mut self,
 6103        insertion_ranges: &[Range<usize>],
 6104        snippet: Snippet,
 6105        window: &mut Window,
 6106        cx: &mut Context<Self>,
 6107    ) -> Result<()> {
 6108        struct Tabstop<T> {
 6109            is_end_tabstop: bool,
 6110            ranges: Vec<Range<T>>,
 6111            choices: Option<Vec<String>>,
 6112        }
 6113
 6114        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6115            let snippet_text: Arc<str> = snippet.text.clone().into();
 6116            buffer.edit(
 6117                insertion_ranges
 6118                    .iter()
 6119                    .cloned()
 6120                    .map(|range| (range, snippet_text.clone())),
 6121                Some(AutoindentMode::EachLine),
 6122                cx,
 6123            );
 6124
 6125            let snapshot = &*buffer.read(cx);
 6126            let snippet = &snippet;
 6127            snippet
 6128                .tabstops
 6129                .iter()
 6130                .map(|tabstop| {
 6131                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6132                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6133                    });
 6134                    let mut tabstop_ranges = tabstop
 6135                        .ranges
 6136                        .iter()
 6137                        .flat_map(|tabstop_range| {
 6138                            let mut delta = 0_isize;
 6139                            insertion_ranges.iter().map(move |insertion_range| {
 6140                                let insertion_start = insertion_range.start as isize + delta;
 6141                                delta +=
 6142                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6143
 6144                                let start = ((insertion_start + tabstop_range.start) as usize)
 6145                                    .min(snapshot.len());
 6146                                let end = ((insertion_start + tabstop_range.end) as usize)
 6147                                    .min(snapshot.len());
 6148                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6149                            })
 6150                        })
 6151                        .collect::<Vec<_>>();
 6152                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6153
 6154                    Tabstop {
 6155                        is_end_tabstop,
 6156                        ranges: tabstop_ranges,
 6157                        choices: tabstop.choices.clone(),
 6158                    }
 6159                })
 6160                .collect::<Vec<_>>()
 6161        });
 6162        if let Some(tabstop) = tabstops.first() {
 6163            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6164                s.select_ranges(tabstop.ranges.iter().cloned());
 6165            });
 6166
 6167            if let Some(choices) = &tabstop.choices {
 6168                if let Some(selection) = tabstop.ranges.first() {
 6169                    self.show_snippet_choices(choices, selection.clone(), cx)
 6170                }
 6171            }
 6172
 6173            // If we're already at the last tabstop and it's at the end of the snippet,
 6174            // we're done, we don't need to keep the state around.
 6175            if !tabstop.is_end_tabstop {
 6176                let choices = tabstops
 6177                    .iter()
 6178                    .map(|tabstop| tabstop.choices.clone())
 6179                    .collect();
 6180
 6181                let ranges = tabstops
 6182                    .into_iter()
 6183                    .map(|tabstop| tabstop.ranges)
 6184                    .collect::<Vec<_>>();
 6185
 6186                self.snippet_stack.push(SnippetState {
 6187                    active_index: 0,
 6188                    ranges,
 6189                    choices,
 6190                });
 6191            }
 6192
 6193            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6194            if self.autoclose_regions.is_empty() {
 6195                let snapshot = self.buffer.read(cx).snapshot(cx);
 6196                for selection in &mut self.selections.all::<Point>(cx) {
 6197                    let selection_head = selection.head();
 6198                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6199                        continue;
 6200                    };
 6201
 6202                    let mut bracket_pair = None;
 6203                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6204                    let prev_chars = snapshot
 6205                        .reversed_chars_at(selection_head)
 6206                        .collect::<String>();
 6207                    for (pair, enabled) in scope.brackets() {
 6208                        if enabled
 6209                            && pair.close
 6210                            && prev_chars.starts_with(pair.start.as_str())
 6211                            && next_chars.starts_with(pair.end.as_str())
 6212                        {
 6213                            bracket_pair = Some(pair.clone());
 6214                            break;
 6215                        }
 6216                    }
 6217                    if let Some(pair) = bracket_pair {
 6218                        let start = snapshot.anchor_after(selection_head);
 6219                        let end = snapshot.anchor_after(selection_head);
 6220                        self.autoclose_regions.push(AutocloseRegion {
 6221                            selection_id: selection.id,
 6222                            range: start..end,
 6223                            pair,
 6224                        });
 6225                    }
 6226                }
 6227            }
 6228        }
 6229        Ok(())
 6230    }
 6231
 6232    pub fn move_to_next_snippet_tabstop(
 6233        &mut self,
 6234        window: &mut Window,
 6235        cx: &mut Context<Self>,
 6236    ) -> bool {
 6237        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6238    }
 6239
 6240    pub fn move_to_prev_snippet_tabstop(
 6241        &mut self,
 6242        window: &mut Window,
 6243        cx: &mut Context<Self>,
 6244    ) -> bool {
 6245        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6246    }
 6247
 6248    pub fn move_to_snippet_tabstop(
 6249        &mut self,
 6250        bias: Bias,
 6251        window: &mut Window,
 6252        cx: &mut Context<Self>,
 6253    ) -> bool {
 6254        if let Some(mut snippet) = self.snippet_stack.pop() {
 6255            match bias {
 6256                Bias::Left => {
 6257                    if snippet.active_index > 0 {
 6258                        snippet.active_index -= 1;
 6259                    } else {
 6260                        self.snippet_stack.push(snippet);
 6261                        return false;
 6262                    }
 6263                }
 6264                Bias::Right => {
 6265                    if snippet.active_index + 1 < snippet.ranges.len() {
 6266                        snippet.active_index += 1;
 6267                    } else {
 6268                        self.snippet_stack.push(snippet);
 6269                        return false;
 6270                    }
 6271                }
 6272            }
 6273            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6274                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6275                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6276                });
 6277
 6278                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6279                    if let Some(selection) = current_ranges.first() {
 6280                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6281                    }
 6282                }
 6283
 6284                // If snippet state is not at the last tabstop, push it back on the stack
 6285                if snippet.active_index + 1 < snippet.ranges.len() {
 6286                    self.snippet_stack.push(snippet);
 6287                }
 6288                return true;
 6289            }
 6290        }
 6291
 6292        false
 6293    }
 6294
 6295    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6296        self.transact(window, cx, |this, window, cx| {
 6297            this.select_all(&SelectAll, window, cx);
 6298            this.insert("", window, cx);
 6299        });
 6300    }
 6301
 6302    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6303        self.transact(window, cx, |this, window, cx| {
 6304            this.select_autoclose_pair(window, cx);
 6305            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6306            if !this.linked_edit_ranges.is_empty() {
 6307                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6308                let snapshot = this.buffer.read(cx).snapshot(cx);
 6309
 6310                for selection in selections.iter() {
 6311                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6312                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6313                    if selection_start.buffer_id != selection_end.buffer_id {
 6314                        continue;
 6315                    }
 6316                    if let Some(ranges) =
 6317                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6318                    {
 6319                        for (buffer, entries) in ranges {
 6320                            linked_ranges.entry(buffer).or_default().extend(entries);
 6321                        }
 6322                    }
 6323                }
 6324            }
 6325
 6326            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6327            if !this.selections.line_mode {
 6328                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6329                for selection in &mut selections {
 6330                    if selection.is_empty() {
 6331                        let old_head = selection.head();
 6332                        let mut new_head =
 6333                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6334                                .to_point(&display_map);
 6335                        if let Some((buffer, line_buffer_range)) = display_map
 6336                            .buffer_snapshot
 6337                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6338                        {
 6339                            let indent_size =
 6340                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6341                            let indent_len = match indent_size.kind {
 6342                                IndentKind::Space => {
 6343                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6344                                }
 6345                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6346                            };
 6347                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6348                                let indent_len = indent_len.get();
 6349                                new_head = cmp::min(
 6350                                    new_head,
 6351                                    MultiBufferPoint::new(
 6352                                        old_head.row,
 6353                                        ((old_head.column - 1) / indent_len) * indent_len,
 6354                                    ),
 6355                                );
 6356                            }
 6357                        }
 6358
 6359                        selection.set_head(new_head, SelectionGoal::None);
 6360                    }
 6361                }
 6362            }
 6363
 6364            this.signature_help_state.set_backspace_pressed(true);
 6365            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6366                s.select(selections)
 6367            });
 6368            this.insert("", window, cx);
 6369            let empty_str: Arc<str> = Arc::from("");
 6370            for (buffer, edits) in linked_ranges {
 6371                let snapshot = buffer.read(cx).snapshot();
 6372                use text::ToPoint as TP;
 6373
 6374                let edits = edits
 6375                    .into_iter()
 6376                    .map(|range| {
 6377                        let end_point = TP::to_point(&range.end, &snapshot);
 6378                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6379
 6380                        if end_point == start_point {
 6381                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6382                                .saturating_sub(1);
 6383                            start_point =
 6384                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6385                        };
 6386
 6387                        (start_point..end_point, empty_str.clone())
 6388                    })
 6389                    .sorted_by_key(|(range, _)| range.start)
 6390                    .collect::<Vec<_>>();
 6391                buffer.update(cx, |this, cx| {
 6392                    this.edit(edits, None, cx);
 6393                })
 6394            }
 6395            this.refresh_inline_completion(true, false, window, cx);
 6396            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6397        });
 6398    }
 6399
 6400    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6401        self.transact(window, cx, |this, window, cx| {
 6402            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6403                let line_mode = s.line_mode;
 6404                s.move_with(|map, selection| {
 6405                    if selection.is_empty() && !line_mode {
 6406                        let cursor = movement::right(map, selection.head());
 6407                        selection.end = cursor;
 6408                        selection.reversed = true;
 6409                        selection.goal = SelectionGoal::None;
 6410                    }
 6411                })
 6412            });
 6413            this.insert("", window, cx);
 6414            this.refresh_inline_completion(true, false, window, cx);
 6415        });
 6416    }
 6417
 6418    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6419        if self.move_to_prev_snippet_tabstop(window, cx) {
 6420            return;
 6421        }
 6422
 6423        self.outdent(&Outdent, window, cx);
 6424    }
 6425
 6426    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6427        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6428            return;
 6429        }
 6430
 6431        let mut selections = self.selections.all_adjusted(cx);
 6432        let buffer = self.buffer.read(cx);
 6433        let snapshot = buffer.snapshot(cx);
 6434        let rows_iter = selections.iter().map(|s| s.head().row);
 6435        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6436
 6437        let mut edits = Vec::new();
 6438        let mut prev_edited_row = 0;
 6439        let mut row_delta = 0;
 6440        for selection in &mut selections {
 6441            if selection.start.row != prev_edited_row {
 6442                row_delta = 0;
 6443            }
 6444            prev_edited_row = selection.end.row;
 6445
 6446            // If the selection is non-empty, then increase the indentation of the selected lines.
 6447            if !selection.is_empty() {
 6448                row_delta =
 6449                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6450                continue;
 6451            }
 6452
 6453            // If the selection is empty and the cursor is in the leading whitespace before the
 6454            // suggested indentation, then auto-indent the line.
 6455            let cursor = selection.head();
 6456            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6457            if let Some(suggested_indent) =
 6458                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6459            {
 6460                if cursor.column < suggested_indent.len
 6461                    && cursor.column <= current_indent.len
 6462                    && current_indent.len <= suggested_indent.len
 6463                {
 6464                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6465                    selection.end = selection.start;
 6466                    if row_delta == 0 {
 6467                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6468                            cursor.row,
 6469                            current_indent,
 6470                            suggested_indent,
 6471                        ));
 6472                        row_delta = suggested_indent.len - current_indent.len;
 6473                    }
 6474                    continue;
 6475                }
 6476            }
 6477
 6478            // Otherwise, insert a hard or soft tab.
 6479            let settings = buffer.settings_at(cursor, cx);
 6480            let tab_size = if settings.hard_tabs {
 6481                IndentSize::tab()
 6482            } else {
 6483                let tab_size = settings.tab_size.get();
 6484                let char_column = snapshot
 6485                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6486                    .flat_map(str::chars)
 6487                    .count()
 6488                    + row_delta as usize;
 6489                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6490                IndentSize::spaces(chars_to_next_tab_stop)
 6491            };
 6492            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6493            selection.end = selection.start;
 6494            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6495            row_delta += tab_size.len;
 6496        }
 6497
 6498        self.transact(window, cx, |this, window, cx| {
 6499            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6500            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6501                s.select(selections)
 6502            });
 6503            this.refresh_inline_completion(true, false, window, cx);
 6504        });
 6505    }
 6506
 6507    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6508        if self.read_only(cx) {
 6509            return;
 6510        }
 6511        let mut selections = self.selections.all::<Point>(cx);
 6512        let mut prev_edited_row = 0;
 6513        let mut row_delta = 0;
 6514        let mut edits = Vec::new();
 6515        let buffer = self.buffer.read(cx);
 6516        let snapshot = buffer.snapshot(cx);
 6517        for selection in &mut selections {
 6518            if selection.start.row != prev_edited_row {
 6519                row_delta = 0;
 6520            }
 6521            prev_edited_row = selection.end.row;
 6522
 6523            row_delta =
 6524                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6525        }
 6526
 6527        self.transact(window, cx, |this, window, cx| {
 6528            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6529            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6530                s.select(selections)
 6531            });
 6532        });
 6533    }
 6534
 6535    fn indent_selection(
 6536        buffer: &MultiBuffer,
 6537        snapshot: &MultiBufferSnapshot,
 6538        selection: &mut Selection<Point>,
 6539        edits: &mut Vec<(Range<Point>, String)>,
 6540        delta_for_start_row: u32,
 6541        cx: &App,
 6542    ) -> u32 {
 6543        let settings = buffer.settings_at(selection.start, cx);
 6544        let tab_size = settings.tab_size.get();
 6545        let indent_kind = if settings.hard_tabs {
 6546            IndentKind::Tab
 6547        } else {
 6548            IndentKind::Space
 6549        };
 6550        let mut start_row = selection.start.row;
 6551        let mut end_row = selection.end.row + 1;
 6552
 6553        // If a selection ends at the beginning of a line, don't indent
 6554        // that last line.
 6555        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6556            end_row -= 1;
 6557        }
 6558
 6559        // Avoid re-indenting a row that has already been indented by a
 6560        // previous selection, but still update this selection's column
 6561        // to reflect that indentation.
 6562        if delta_for_start_row > 0 {
 6563            start_row += 1;
 6564            selection.start.column += delta_for_start_row;
 6565            if selection.end.row == selection.start.row {
 6566                selection.end.column += delta_for_start_row;
 6567            }
 6568        }
 6569
 6570        let mut delta_for_end_row = 0;
 6571        let has_multiple_rows = start_row + 1 != end_row;
 6572        for row in start_row..end_row {
 6573            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6574            let indent_delta = match (current_indent.kind, indent_kind) {
 6575                (IndentKind::Space, IndentKind::Space) => {
 6576                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6577                    IndentSize::spaces(columns_to_next_tab_stop)
 6578                }
 6579                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6580                (_, IndentKind::Tab) => IndentSize::tab(),
 6581            };
 6582
 6583            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6584                0
 6585            } else {
 6586                selection.start.column
 6587            };
 6588            let row_start = Point::new(row, start);
 6589            edits.push((
 6590                row_start..row_start,
 6591                indent_delta.chars().collect::<String>(),
 6592            ));
 6593
 6594            // Update this selection's endpoints to reflect the indentation.
 6595            if row == selection.start.row {
 6596                selection.start.column += indent_delta.len;
 6597            }
 6598            if row == selection.end.row {
 6599                selection.end.column += indent_delta.len;
 6600                delta_for_end_row = indent_delta.len;
 6601            }
 6602        }
 6603
 6604        if selection.start.row == selection.end.row {
 6605            delta_for_start_row + delta_for_end_row
 6606        } else {
 6607            delta_for_end_row
 6608        }
 6609    }
 6610
 6611    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6612        if self.read_only(cx) {
 6613            return;
 6614        }
 6615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6616        let selections = self.selections.all::<Point>(cx);
 6617        let mut deletion_ranges = Vec::new();
 6618        let mut last_outdent = None;
 6619        {
 6620            let buffer = self.buffer.read(cx);
 6621            let snapshot = buffer.snapshot(cx);
 6622            for selection in &selections {
 6623                let settings = buffer.settings_at(selection.start, cx);
 6624                let tab_size = settings.tab_size.get();
 6625                let mut rows = selection.spanned_rows(false, &display_map);
 6626
 6627                // Avoid re-outdenting a row that has already been outdented by a
 6628                // previous selection.
 6629                if let Some(last_row) = last_outdent {
 6630                    if last_row == rows.start {
 6631                        rows.start = rows.start.next_row();
 6632                    }
 6633                }
 6634                let has_multiple_rows = rows.len() > 1;
 6635                for row in rows.iter_rows() {
 6636                    let indent_size = snapshot.indent_size_for_line(row);
 6637                    if indent_size.len > 0 {
 6638                        let deletion_len = match indent_size.kind {
 6639                            IndentKind::Space => {
 6640                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6641                                if columns_to_prev_tab_stop == 0 {
 6642                                    tab_size
 6643                                } else {
 6644                                    columns_to_prev_tab_stop
 6645                                }
 6646                            }
 6647                            IndentKind::Tab => 1,
 6648                        };
 6649                        let start = if has_multiple_rows
 6650                            || deletion_len > selection.start.column
 6651                            || indent_size.len < selection.start.column
 6652                        {
 6653                            0
 6654                        } else {
 6655                            selection.start.column - deletion_len
 6656                        };
 6657                        deletion_ranges.push(
 6658                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6659                        );
 6660                        last_outdent = Some(row);
 6661                    }
 6662                }
 6663            }
 6664        }
 6665
 6666        self.transact(window, cx, |this, window, cx| {
 6667            this.buffer.update(cx, |buffer, cx| {
 6668                let empty_str: Arc<str> = Arc::default();
 6669                buffer.edit(
 6670                    deletion_ranges
 6671                        .into_iter()
 6672                        .map(|range| (range, empty_str.clone())),
 6673                    None,
 6674                    cx,
 6675                );
 6676            });
 6677            let selections = this.selections.all::<usize>(cx);
 6678            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6679                s.select(selections)
 6680            });
 6681        });
 6682    }
 6683
 6684    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6685        if self.read_only(cx) {
 6686            return;
 6687        }
 6688        let selections = self
 6689            .selections
 6690            .all::<usize>(cx)
 6691            .into_iter()
 6692            .map(|s| s.range());
 6693
 6694        self.transact(window, cx, |this, window, cx| {
 6695            this.buffer.update(cx, |buffer, cx| {
 6696                buffer.autoindent_ranges(selections, cx);
 6697            });
 6698            let selections = this.selections.all::<usize>(cx);
 6699            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6700                s.select(selections)
 6701            });
 6702        });
 6703    }
 6704
 6705    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6706        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6707        let selections = self.selections.all::<Point>(cx);
 6708
 6709        let mut new_cursors = Vec::new();
 6710        let mut edit_ranges = Vec::new();
 6711        let mut selections = selections.iter().peekable();
 6712        while let Some(selection) = selections.next() {
 6713            let mut rows = selection.spanned_rows(false, &display_map);
 6714            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6715
 6716            // Accumulate contiguous regions of rows that we want to delete.
 6717            while let Some(next_selection) = selections.peek() {
 6718                let next_rows = next_selection.spanned_rows(false, &display_map);
 6719                if next_rows.start <= rows.end {
 6720                    rows.end = next_rows.end;
 6721                    selections.next().unwrap();
 6722                } else {
 6723                    break;
 6724                }
 6725            }
 6726
 6727            let buffer = &display_map.buffer_snapshot;
 6728            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6729            let edit_end;
 6730            let cursor_buffer_row;
 6731            if buffer.max_point().row >= rows.end.0 {
 6732                // If there's a line after the range, delete the \n from the end of the row range
 6733                // and position the cursor on the next line.
 6734                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6735                cursor_buffer_row = rows.end;
 6736            } else {
 6737                // If there isn't a line after the range, delete the \n from the line before the
 6738                // start of the row range and position the cursor there.
 6739                edit_start = edit_start.saturating_sub(1);
 6740                edit_end = buffer.len();
 6741                cursor_buffer_row = rows.start.previous_row();
 6742            }
 6743
 6744            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6745            *cursor.column_mut() =
 6746                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6747
 6748            new_cursors.push((
 6749                selection.id,
 6750                buffer.anchor_after(cursor.to_point(&display_map)),
 6751            ));
 6752            edit_ranges.push(edit_start..edit_end);
 6753        }
 6754
 6755        self.transact(window, cx, |this, window, cx| {
 6756            let buffer = this.buffer.update(cx, |buffer, cx| {
 6757                let empty_str: Arc<str> = Arc::default();
 6758                buffer.edit(
 6759                    edit_ranges
 6760                        .into_iter()
 6761                        .map(|range| (range, empty_str.clone())),
 6762                    None,
 6763                    cx,
 6764                );
 6765                buffer.snapshot(cx)
 6766            });
 6767            let new_selections = new_cursors
 6768                .into_iter()
 6769                .map(|(id, cursor)| {
 6770                    let cursor = cursor.to_point(&buffer);
 6771                    Selection {
 6772                        id,
 6773                        start: cursor,
 6774                        end: cursor,
 6775                        reversed: false,
 6776                        goal: SelectionGoal::None,
 6777                    }
 6778                })
 6779                .collect();
 6780
 6781            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6782                s.select(new_selections);
 6783            });
 6784        });
 6785    }
 6786
 6787    pub fn join_lines_impl(
 6788        &mut self,
 6789        insert_whitespace: bool,
 6790        window: &mut Window,
 6791        cx: &mut Context<Self>,
 6792    ) {
 6793        if self.read_only(cx) {
 6794            return;
 6795        }
 6796        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6797        for selection in self.selections.all::<Point>(cx) {
 6798            let start = MultiBufferRow(selection.start.row);
 6799            // Treat single line selections as if they include the next line. Otherwise this action
 6800            // would do nothing for single line selections individual cursors.
 6801            let end = if selection.start.row == selection.end.row {
 6802                MultiBufferRow(selection.start.row + 1)
 6803            } else {
 6804                MultiBufferRow(selection.end.row)
 6805            };
 6806
 6807            if let Some(last_row_range) = row_ranges.last_mut() {
 6808                if start <= last_row_range.end {
 6809                    last_row_range.end = end;
 6810                    continue;
 6811                }
 6812            }
 6813            row_ranges.push(start..end);
 6814        }
 6815
 6816        let snapshot = self.buffer.read(cx).snapshot(cx);
 6817        let mut cursor_positions = Vec::new();
 6818        for row_range in &row_ranges {
 6819            let anchor = snapshot.anchor_before(Point::new(
 6820                row_range.end.previous_row().0,
 6821                snapshot.line_len(row_range.end.previous_row()),
 6822            ));
 6823            cursor_positions.push(anchor..anchor);
 6824        }
 6825
 6826        self.transact(window, cx, |this, window, cx| {
 6827            for row_range in row_ranges.into_iter().rev() {
 6828                for row in row_range.iter_rows().rev() {
 6829                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6830                    let next_line_row = row.next_row();
 6831                    let indent = snapshot.indent_size_for_line(next_line_row);
 6832                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6833
 6834                    let replace =
 6835                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6836                            " "
 6837                        } else {
 6838                            ""
 6839                        };
 6840
 6841                    this.buffer.update(cx, |buffer, cx| {
 6842                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6843                    });
 6844                }
 6845            }
 6846
 6847            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6848                s.select_anchor_ranges(cursor_positions)
 6849            });
 6850        });
 6851    }
 6852
 6853    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6854        self.join_lines_impl(true, window, cx);
 6855    }
 6856
 6857    pub fn sort_lines_case_sensitive(
 6858        &mut self,
 6859        _: &SortLinesCaseSensitive,
 6860        window: &mut Window,
 6861        cx: &mut Context<Self>,
 6862    ) {
 6863        self.manipulate_lines(window, cx, |lines| lines.sort())
 6864    }
 6865
 6866    pub fn sort_lines_case_insensitive(
 6867        &mut self,
 6868        _: &SortLinesCaseInsensitive,
 6869        window: &mut Window,
 6870        cx: &mut Context<Self>,
 6871    ) {
 6872        self.manipulate_lines(window, cx, |lines| {
 6873            lines.sort_by_key(|line| line.to_lowercase())
 6874        })
 6875    }
 6876
 6877    pub fn unique_lines_case_insensitive(
 6878        &mut self,
 6879        _: &UniqueLinesCaseInsensitive,
 6880        window: &mut Window,
 6881        cx: &mut Context<Self>,
 6882    ) {
 6883        self.manipulate_lines(window, cx, |lines| {
 6884            let mut seen = HashSet::default();
 6885            lines.retain(|line| seen.insert(line.to_lowercase()));
 6886        })
 6887    }
 6888
 6889    pub fn unique_lines_case_sensitive(
 6890        &mut self,
 6891        _: &UniqueLinesCaseSensitive,
 6892        window: &mut Window,
 6893        cx: &mut Context<Self>,
 6894    ) {
 6895        self.manipulate_lines(window, cx, |lines| {
 6896            let mut seen = HashSet::default();
 6897            lines.retain(|line| seen.insert(*line));
 6898        })
 6899    }
 6900
 6901    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6902        let mut revert_changes = HashMap::default();
 6903        let snapshot = self.snapshot(window, cx);
 6904        for hunk in snapshot
 6905            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6906        {
 6907            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6908        }
 6909        if !revert_changes.is_empty() {
 6910            self.transact(window, cx, |editor, window, cx| {
 6911                editor.revert(revert_changes, window, cx);
 6912            });
 6913        }
 6914    }
 6915
 6916    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6917        let Some(project) = self.project.clone() else {
 6918            return;
 6919        };
 6920        self.reload(project, window, cx)
 6921            .detach_and_notify_err(window, cx);
 6922    }
 6923
 6924    pub fn revert_selected_hunks(
 6925        &mut self,
 6926        _: &RevertSelectedHunks,
 6927        window: &mut Window,
 6928        cx: &mut Context<Self>,
 6929    ) {
 6930        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6931        self.revert_hunks_in_ranges(selections, window, cx);
 6932    }
 6933
 6934    fn revert_hunks_in_ranges(
 6935        &mut self,
 6936        ranges: impl Iterator<Item = Range<Point>>,
 6937        window: &mut Window,
 6938        cx: &mut Context<Editor>,
 6939    ) {
 6940        let mut revert_changes = HashMap::default();
 6941        let snapshot = self.snapshot(window, cx);
 6942        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6943            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6944        }
 6945        if !revert_changes.is_empty() {
 6946            self.transact(window, cx, |editor, window, cx| {
 6947                editor.revert(revert_changes, window, cx);
 6948            });
 6949        }
 6950    }
 6951
 6952    pub fn open_active_item_in_terminal(
 6953        &mut self,
 6954        _: &OpenInTerminal,
 6955        window: &mut Window,
 6956        cx: &mut Context<Self>,
 6957    ) {
 6958        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6959            let project_path = buffer.read(cx).project_path(cx)?;
 6960            let project = self.project.as_ref()?.read(cx);
 6961            let entry = project.entry_for_path(&project_path, cx)?;
 6962            let parent = match &entry.canonical_path {
 6963                Some(canonical_path) => canonical_path.to_path_buf(),
 6964                None => project.absolute_path(&project_path, cx)?,
 6965            }
 6966            .parent()?
 6967            .to_path_buf();
 6968            Some(parent)
 6969        }) {
 6970            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6971        }
 6972    }
 6973
 6974    pub fn prepare_revert_change(
 6975        &self,
 6976        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6977        hunk: &MultiBufferDiffHunk,
 6978        cx: &mut App,
 6979    ) -> Option<()> {
 6980        let buffer = self.buffer.read(cx);
 6981        let diff = buffer.diff_for(hunk.buffer_id)?;
 6982        let buffer = buffer.buffer(hunk.buffer_id)?;
 6983        let buffer = buffer.read(cx);
 6984        let original_text = diff
 6985            .read(cx)
 6986            .base_text()
 6987            .as_ref()?
 6988            .as_rope()
 6989            .slice(hunk.diff_base_byte_range.clone());
 6990        let buffer_snapshot = buffer.snapshot();
 6991        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6992        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6993            probe
 6994                .0
 6995                .start
 6996                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6997                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6998        }) {
 6999            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7000            Some(())
 7001        } else {
 7002            None
 7003        }
 7004    }
 7005
 7006    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7007        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7008    }
 7009
 7010    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7011        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7012    }
 7013
 7014    fn manipulate_lines<Fn>(
 7015        &mut self,
 7016        window: &mut Window,
 7017        cx: &mut Context<Self>,
 7018        mut callback: Fn,
 7019    ) where
 7020        Fn: FnMut(&mut Vec<&str>),
 7021    {
 7022        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7023        let buffer = self.buffer.read(cx).snapshot(cx);
 7024
 7025        let mut edits = Vec::new();
 7026
 7027        let selections = self.selections.all::<Point>(cx);
 7028        let mut selections = selections.iter().peekable();
 7029        let mut contiguous_row_selections = Vec::new();
 7030        let mut new_selections = Vec::new();
 7031        let mut added_lines = 0;
 7032        let mut removed_lines = 0;
 7033
 7034        while let Some(selection) = selections.next() {
 7035            let (start_row, end_row) = consume_contiguous_rows(
 7036                &mut contiguous_row_selections,
 7037                selection,
 7038                &display_map,
 7039                &mut selections,
 7040            );
 7041
 7042            let start_point = Point::new(start_row.0, 0);
 7043            let end_point = Point::new(
 7044                end_row.previous_row().0,
 7045                buffer.line_len(end_row.previous_row()),
 7046            );
 7047            let text = buffer
 7048                .text_for_range(start_point..end_point)
 7049                .collect::<String>();
 7050
 7051            let mut lines = text.split('\n').collect_vec();
 7052
 7053            let lines_before = lines.len();
 7054            callback(&mut lines);
 7055            let lines_after = lines.len();
 7056
 7057            edits.push((start_point..end_point, lines.join("\n")));
 7058
 7059            // Selections must change based on added and removed line count
 7060            let start_row =
 7061                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7062            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7063            new_selections.push(Selection {
 7064                id: selection.id,
 7065                start: start_row,
 7066                end: end_row,
 7067                goal: SelectionGoal::None,
 7068                reversed: selection.reversed,
 7069            });
 7070
 7071            if lines_after > lines_before {
 7072                added_lines += lines_after - lines_before;
 7073            } else if lines_before > lines_after {
 7074                removed_lines += lines_before - lines_after;
 7075            }
 7076        }
 7077
 7078        self.transact(window, cx, |this, window, cx| {
 7079            let buffer = this.buffer.update(cx, |buffer, cx| {
 7080                buffer.edit(edits, None, cx);
 7081                buffer.snapshot(cx)
 7082            });
 7083
 7084            // Recalculate offsets on newly edited buffer
 7085            let new_selections = new_selections
 7086                .iter()
 7087                .map(|s| {
 7088                    let start_point = Point::new(s.start.0, 0);
 7089                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7090                    Selection {
 7091                        id: s.id,
 7092                        start: buffer.point_to_offset(start_point),
 7093                        end: buffer.point_to_offset(end_point),
 7094                        goal: s.goal,
 7095                        reversed: s.reversed,
 7096                    }
 7097                })
 7098                .collect();
 7099
 7100            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7101                s.select(new_selections);
 7102            });
 7103
 7104            this.request_autoscroll(Autoscroll::fit(), cx);
 7105        });
 7106    }
 7107
 7108    pub fn convert_to_upper_case(
 7109        &mut self,
 7110        _: &ConvertToUpperCase,
 7111        window: &mut Window,
 7112        cx: &mut Context<Self>,
 7113    ) {
 7114        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7115    }
 7116
 7117    pub fn convert_to_lower_case(
 7118        &mut self,
 7119        _: &ConvertToLowerCase,
 7120        window: &mut Window,
 7121        cx: &mut Context<Self>,
 7122    ) {
 7123        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7124    }
 7125
 7126    pub fn convert_to_title_case(
 7127        &mut self,
 7128        _: &ConvertToTitleCase,
 7129        window: &mut Window,
 7130        cx: &mut Context<Self>,
 7131    ) {
 7132        self.manipulate_text(window, cx, |text| {
 7133            text.split('\n')
 7134                .map(|line| line.to_case(Case::Title))
 7135                .join("\n")
 7136        })
 7137    }
 7138
 7139    pub fn convert_to_snake_case(
 7140        &mut self,
 7141        _: &ConvertToSnakeCase,
 7142        window: &mut Window,
 7143        cx: &mut Context<Self>,
 7144    ) {
 7145        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7146    }
 7147
 7148    pub fn convert_to_kebab_case(
 7149        &mut self,
 7150        _: &ConvertToKebabCase,
 7151        window: &mut Window,
 7152        cx: &mut Context<Self>,
 7153    ) {
 7154        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7155    }
 7156
 7157    pub fn convert_to_upper_camel_case(
 7158        &mut self,
 7159        _: &ConvertToUpperCamelCase,
 7160        window: &mut Window,
 7161        cx: &mut Context<Self>,
 7162    ) {
 7163        self.manipulate_text(window, cx, |text| {
 7164            text.split('\n')
 7165                .map(|line| line.to_case(Case::UpperCamel))
 7166                .join("\n")
 7167        })
 7168    }
 7169
 7170    pub fn convert_to_lower_camel_case(
 7171        &mut self,
 7172        _: &ConvertToLowerCamelCase,
 7173        window: &mut Window,
 7174        cx: &mut Context<Self>,
 7175    ) {
 7176        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7177    }
 7178
 7179    pub fn convert_to_opposite_case(
 7180        &mut self,
 7181        _: &ConvertToOppositeCase,
 7182        window: &mut Window,
 7183        cx: &mut Context<Self>,
 7184    ) {
 7185        self.manipulate_text(window, cx, |text| {
 7186            text.chars()
 7187                .fold(String::with_capacity(text.len()), |mut t, c| {
 7188                    if c.is_uppercase() {
 7189                        t.extend(c.to_lowercase());
 7190                    } else {
 7191                        t.extend(c.to_uppercase());
 7192                    }
 7193                    t
 7194                })
 7195        })
 7196    }
 7197
 7198    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7199    where
 7200        Fn: FnMut(&str) -> String,
 7201    {
 7202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7203        let buffer = self.buffer.read(cx).snapshot(cx);
 7204
 7205        let mut new_selections = Vec::new();
 7206        let mut edits = Vec::new();
 7207        let mut selection_adjustment = 0i32;
 7208
 7209        for selection in self.selections.all::<usize>(cx) {
 7210            let selection_is_empty = selection.is_empty();
 7211
 7212            let (start, end) = if selection_is_empty {
 7213                let word_range = movement::surrounding_word(
 7214                    &display_map,
 7215                    selection.start.to_display_point(&display_map),
 7216                );
 7217                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7218                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7219                (start, end)
 7220            } else {
 7221                (selection.start, selection.end)
 7222            };
 7223
 7224            let text = buffer.text_for_range(start..end).collect::<String>();
 7225            let old_length = text.len() as i32;
 7226            let text = callback(&text);
 7227
 7228            new_selections.push(Selection {
 7229                start: (start as i32 - selection_adjustment) as usize,
 7230                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7231                goal: SelectionGoal::None,
 7232                ..selection
 7233            });
 7234
 7235            selection_adjustment += old_length - text.len() as i32;
 7236
 7237            edits.push((start..end, text));
 7238        }
 7239
 7240        self.transact(window, cx, |this, window, cx| {
 7241            this.buffer.update(cx, |buffer, cx| {
 7242                buffer.edit(edits, None, cx);
 7243            });
 7244
 7245            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7246                s.select(new_selections);
 7247            });
 7248
 7249            this.request_autoscroll(Autoscroll::fit(), cx);
 7250        });
 7251    }
 7252
 7253    pub fn duplicate(
 7254        &mut self,
 7255        upwards: bool,
 7256        whole_lines: bool,
 7257        window: &mut Window,
 7258        cx: &mut Context<Self>,
 7259    ) {
 7260        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7261        let buffer = &display_map.buffer_snapshot;
 7262        let selections = self.selections.all::<Point>(cx);
 7263
 7264        let mut edits = Vec::new();
 7265        let mut selections_iter = selections.iter().peekable();
 7266        while let Some(selection) = selections_iter.next() {
 7267            let mut rows = selection.spanned_rows(false, &display_map);
 7268            // duplicate line-wise
 7269            if whole_lines || selection.start == selection.end {
 7270                // Avoid duplicating the same lines twice.
 7271                while let Some(next_selection) = selections_iter.peek() {
 7272                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7273                    if next_rows.start < rows.end {
 7274                        rows.end = next_rows.end;
 7275                        selections_iter.next().unwrap();
 7276                    } else {
 7277                        break;
 7278                    }
 7279                }
 7280
 7281                // Copy the text from the selected row region and splice it either at the start
 7282                // or end of the region.
 7283                let start = Point::new(rows.start.0, 0);
 7284                let end = Point::new(
 7285                    rows.end.previous_row().0,
 7286                    buffer.line_len(rows.end.previous_row()),
 7287                );
 7288                let text = buffer
 7289                    .text_for_range(start..end)
 7290                    .chain(Some("\n"))
 7291                    .collect::<String>();
 7292                let insert_location = if upwards {
 7293                    Point::new(rows.end.0, 0)
 7294                } else {
 7295                    start
 7296                };
 7297                edits.push((insert_location..insert_location, text));
 7298            } else {
 7299                // duplicate character-wise
 7300                let start = selection.start;
 7301                let end = selection.end;
 7302                let text = buffer.text_for_range(start..end).collect::<String>();
 7303                edits.push((selection.end..selection.end, text));
 7304            }
 7305        }
 7306
 7307        self.transact(window, cx, |this, _, cx| {
 7308            this.buffer.update(cx, |buffer, cx| {
 7309                buffer.edit(edits, None, cx);
 7310            });
 7311
 7312            this.request_autoscroll(Autoscroll::fit(), cx);
 7313        });
 7314    }
 7315
 7316    pub fn duplicate_line_up(
 7317        &mut self,
 7318        _: &DuplicateLineUp,
 7319        window: &mut Window,
 7320        cx: &mut Context<Self>,
 7321    ) {
 7322        self.duplicate(true, true, window, cx);
 7323    }
 7324
 7325    pub fn duplicate_line_down(
 7326        &mut self,
 7327        _: &DuplicateLineDown,
 7328        window: &mut Window,
 7329        cx: &mut Context<Self>,
 7330    ) {
 7331        self.duplicate(false, true, window, cx);
 7332    }
 7333
 7334    pub fn duplicate_selection(
 7335        &mut self,
 7336        _: &DuplicateSelection,
 7337        window: &mut Window,
 7338        cx: &mut Context<Self>,
 7339    ) {
 7340        self.duplicate(false, false, window, cx);
 7341    }
 7342
 7343    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7344        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7345        let buffer = self.buffer.read(cx).snapshot(cx);
 7346
 7347        let mut edits = Vec::new();
 7348        let mut unfold_ranges = Vec::new();
 7349        let mut refold_creases = Vec::new();
 7350
 7351        let selections = self.selections.all::<Point>(cx);
 7352        let mut selections = selections.iter().peekable();
 7353        let mut contiguous_row_selections = Vec::new();
 7354        let mut new_selections = Vec::new();
 7355
 7356        while let Some(selection) = selections.next() {
 7357            // Find all the selections that span a contiguous row range
 7358            let (start_row, end_row) = consume_contiguous_rows(
 7359                &mut contiguous_row_selections,
 7360                selection,
 7361                &display_map,
 7362                &mut selections,
 7363            );
 7364
 7365            // Move the text spanned by the row range to be before the line preceding the row range
 7366            if start_row.0 > 0 {
 7367                let range_to_move = Point::new(
 7368                    start_row.previous_row().0,
 7369                    buffer.line_len(start_row.previous_row()),
 7370                )
 7371                    ..Point::new(
 7372                        end_row.previous_row().0,
 7373                        buffer.line_len(end_row.previous_row()),
 7374                    );
 7375                let insertion_point = display_map
 7376                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7377                    .0;
 7378
 7379                // Don't move lines across excerpts
 7380                if buffer
 7381                    .excerpt_containing(insertion_point..range_to_move.end)
 7382                    .is_some()
 7383                {
 7384                    let text = buffer
 7385                        .text_for_range(range_to_move.clone())
 7386                        .flat_map(|s| s.chars())
 7387                        .skip(1)
 7388                        .chain(['\n'])
 7389                        .collect::<String>();
 7390
 7391                    edits.push((
 7392                        buffer.anchor_after(range_to_move.start)
 7393                            ..buffer.anchor_before(range_to_move.end),
 7394                        String::new(),
 7395                    ));
 7396                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7397                    edits.push((insertion_anchor..insertion_anchor, text));
 7398
 7399                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7400
 7401                    // Move selections up
 7402                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7403                        |mut selection| {
 7404                            selection.start.row -= row_delta;
 7405                            selection.end.row -= row_delta;
 7406                            selection
 7407                        },
 7408                    ));
 7409
 7410                    // Move folds up
 7411                    unfold_ranges.push(range_to_move.clone());
 7412                    for fold in display_map.folds_in_range(
 7413                        buffer.anchor_before(range_to_move.start)
 7414                            ..buffer.anchor_after(range_to_move.end),
 7415                    ) {
 7416                        let mut start = fold.range.start.to_point(&buffer);
 7417                        let mut end = fold.range.end.to_point(&buffer);
 7418                        start.row -= row_delta;
 7419                        end.row -= row_delta;
 7420                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7421                    }
 7422                }
 7423            }
 7424
 7425            // If we didn't move line(s), preserve the existing selections
 7426            new_selections.append(&mut contiguous_row_selections);
 7427        }
 7428
 7429        self.transact(window, cx, |this, window, cx| {
 7430            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7431            this.buffer.update(cx, |buffer, cx| {
 7432                for (range, text) in edits {
 7433                    buffer.edit([(range, text)], None, cx);
 7434                }
 7435            });
 7436            this.fold_creases(refold_creases, true, window, cx);
 7437            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7438                s.select(new_selections);
 7439            })
 7440        });
 7441    }
 7442
 7443    pub fn move_line_down(
 7444        &mut self,
 7445        _: &MoveLineDown,
 7446        window: &mut Window,
 7447        cx: &mut Context<Self>,
 7448    ) {
 7449        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7450        let buffer = self.buffer.read(cx).snapshot(cx);
 7451
 7452        let mut edits = Vec::new();
 7453        let mut unfold_ranges = Vec::new();
 7454        let mut refold_creases = Vec::new();
 7455
 7456        let selections = self.selections.all::<Point>(cx);
 7457        let mut selections = selections.iter().peekable();
 7458        let mut contiguous_row_selections = Vec::new();
 7459        let mut new_selections = Vec::new();
 7460
 7461        while let Some(selection) = selections.next() {
 7462            // Find all the selections that span a contiguous row range
 7463            let (start_row, end_row) = consume_contiguous_rows(
 7464                &mut contiguous_row_selections,
 7465                selection,
 7466                &display_map,
 7467                &mut selections,
 7468            );
 7469
 7470            // Move the text spanned by the row range to be after the last line of the row range
 7471            if end_row.0 <= buffer.max_point().row {
 7472                let range_to_move =
 7473                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7474                let insertion_point = display_map
 7475                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7476                    .0;
 7477
 7478                // Don't move lines across excerpt boundaries
 7479                if buffer
 7480                    .excerpt_containing(range_to_move.start..insertion_point)
 7481                    .is_some()
 7482                {
 7483                    let mut text = String::from("\n");
 7484                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7485                    text.pop(); // Drop trailing newline
 7486                    edits.push((
 7487                        buffer.anchor_after(range_to_move.start)
 7488                            ..buffer.anchor_before(range_to_move.end),
 7489                        String::new(),
 7490                    ));
 7491                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7492                    edits.push((insertion_anchor..insertion_anchor, text));
 7493
 7494                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7495
 7496                    // Move selections down
 7497                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7498                        |mut selection| {
 7499                            selection.start.row += row_delta;
 7500                            selection.end.row += row_delta;
 7501                            selection
 7502                        },
 7503                    ));
 7504
 7505                    // Move folds down
 7506                    unfold_ranges.push(range_to_move.clone());
 7507                    for fold in display_map.folds_in_range(
 7508                        buffer.anchor_before(range_to_move.start)
 7509                            ..buffer.anchor_after(range_to_move.end),
 7510                    ) {
 7511                        let mut start = fold.range.start.to_point(&buffer);
 7512                        let mut end = fold.range.end.to_point(&buffer);
 7513                        start.row += row_delta;
 7514                        end.row += row_delta;
 7515                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7516                    }
 7517                }
 7518            }
 7519
 7520            // If we didn't move line(s), preserve the existing selections
 7521            new_selections.append(&mut contiguous_row_selections);
 7522        }
 7523
 7524        self.transact(window, cx, |this, window, cx| {
 7525            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7526            this.buffer.update(cx, |buffer, cx| {
 7527                for (range, text) in edits {
 7528                    buffer.edit([(range, text)], None, cx);
 7529                }
 7530            });
 7531            this.fold_creases(refold_creases, true, window, cx);
 7532            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7533                s.select(new_selections)
 7534            });
 7535        });
 7536    }
 7537
 7538    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7539        let text_layout_details = &self.text_layout_details(window);
 7540        self.transact(window, cx, |this, window, cx| {
 7541            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7542                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7543                let line_mode = s.line_mode;
 7544                s.move_with(|display_map, selection| {
 7545                    if !selection.is_empty() || line_mode {
 7546                        return;
 7547                    }
 7548
 7549                    let mut head = selection.head();
 7550                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7551                    if head.column() == display_map.line_len(head.row()) {
 7552                        transpose_offset = display_map
 7553                            .buffer_snapshot
 7554                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7555                    }
 7556
 7557                    if transpose_offset == 0 {
 7558                        return;
 7559                    }
 7560
 7561                    *head.column_mut() += 1;
 7562                    head = display_map.clip_point(head, Bias::Right);
 7563                    let goal = SelectionGoal::HorizontalPosition(
 7564                        display_map
 7565                            .x_for_display_point(head, text_layout_details)
 7566                            .into(),
 7567                    );
 7568                    selection.collapse_to(head, goal);
 7569
 7570                    let transpose_start = display_map
 7571                        .buffer_snapshot
 7572                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7573                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7574                        let transpose_end = display_map
 7575                            .buffer_snapshot
 7576                            .clip_offset(transpose_offset + 1, Bias::Right);
 7577                        if let Some(ch) =
 7578                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7579                        {
 7580                            edits.push((transpose_start..transpose_offset, String::new()));
 7581                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7582                        }
 7583                    }
 7584                });
 7585                edits
 7586            });
 7587            this.buffer
 7588                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7589            let selections = this.selections.all::<usize>(cx);
 7590            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7591                s.select(selections);
 7592            });
 7593        });
 7594    }
 7595
 7596    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7597        self.rewrap_impl(IsVimMode::No, cx)
 7598    }
 7599
 7600    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7601        let buffer = self.buffer.read(cx).snapshot(cx);
 7602        let selections = self.selections.all::<Point>(cx);
 7603        let mut selections = selections.iter().peekable();
 7604
 7605        let mut edits = Vec::new();
 7606        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7607
 7608        while let Some(selection) = selections.next() {
 7609            let mut start_row = selection.start.row;
 7610            let mut end_row = selection.end.row;
 7611
 7612            // Skip selections that overlap with a range that has already been rewrapped.
 7613            let selection_range = start_row..end_row;
 7614            if rewrapped_row_ranges
 7615                .iter()
 7616                .any(|range| range.overlaps(&selection_range))
 7617            {
 7618                continue;
 7619            }
 7620
 7621            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7622
 7623            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7624                match language_scope.language_name().as_ref() {
 7625                    "Markdown" | "Plain Text" => {
 7626                        should_rewrap = true;
 7627                    }
 7628                    _ => {}
 7629                }
 7630            }
 7631
 7632            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7633
 7634            // Since not all lines in the selection may be at the same indent
 7635            // level, choose the indent size that is the most common between all
 7636            // of the lines.
 7637            //
 7638            // If there is a tie, we use the deepest indent.
 7639            let (indent_size, indent_end) = {
 7640                let mut indent_size_occurrences = HashMap::default();
 7641                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7642
 7643                for row in start_row..=end_row {
 7644                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7645                    rows_by_indent_size.entry(indent).or_default().push(row);
 7646                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7647                }
 7648
 7649                let indent_size = indent_size_occurrences
 7650                    .into_iter()
 7651                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7652                    .map(|(indent, _)| indent)
 7653                    .unwrap_or_default();
 7654                let row = rows_by_indent_size[&indent_size][0];
 7655                let indent_end = Point::new(row, indent_size.len);
 7656
 7657                (indent_size, indent_end)
 7658            };
 7659
 7660            let mut line_prefix = indent_size.chars().collect::<String>();
 7661
 7662            if let Some(comment_prefix) =
 7663                buffer
 7664                    .language_scope_at(selection.head())
 7665                    .and_then(|language| {
 7666                        language
 7667                            .line_comment_prefixes()
 7668                            .iter()
 7669                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7670                            .cloned()
 7671                    })
 7672            {
 7673                line_prefix.push_str(&comment_prefix);
 7674                should_rewrap = true;
 7675            }
 7676
 7677            if !should_rewrap {
 7678                continue;
 7679            }
 7680
 7681            if selection.is_empty() {
 7682                'expand_upwards: while start_row > 0 {
 7683                    let prev_row = start_row - 1;
 7684                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7685                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7686                    {
 7687                        start_row = prev_row;
 7688                    } else {
 7689                        break 'expand_upwards;
 7690                    }
 7691                }
 7692
 7693                'expand_downwards: while end_row < buffer.max_point().row {
 7694                    let next_row = end_row + 1;
 7695                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7696                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7697                    {
 7698                        end_row = next_row;
 7699                    } else {
 7700                        break 'expand_downwards;
 7701                    }
 7702                }
 7703            }
 7704
 7705            let start = Point::new(start_row, 0);
 7706            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7707            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7708            let Some(lines_without_prefixes) = selection_text
 7709                .lines()
 7710                .map(|line| {
 7711                    line.strip_prefix(&line_prefix)
 7712                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7713                        .ok_or_else(|| {
 7714                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7715                        })
 7716                })
 7717                .collect::<Result<Vec<_>, _>>()
 7718                .log_err()
 7719            else {
 7720                continue;
 7721            };
 7722
 7723            let wrap_column = buffer
 7724                .settings_at(Point::new(start_row, 0), cx)
 7725                .preferred_line_length as usize;
 7726            let wrapped_text = wrap_with_prefix(
 7727                line_prefix,
 7728                lines_without_prefixes.join(" "),
 7729                wrap_column,
 7730                tab_size,
 7731            );
 7732
 7733            // TODO: should always use char-based diff while still supporting cursor behavior that
 7734            // matches vim.
 7735            let diff = match is_vim_mode {
 7736                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7737                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7738            };
 7739            let mut offset = start.to_offset(&buffer);
 7740            let mut moved_since_edit = true;
 7741
 7742            for change in diff.iter_all_changes() {
 7743                let value = change.value();
 7744                match change.tag() {
 7745                    ChangeTag::Equal => {
 7746                        offset += value.len();
 7747                        moved_since_edit = true;
 7748                    }
 7749                    ChangeTag::Delete => {
 7750                        let start = buffer.anchor_after(offset);
 7751                        let end = buffer.anchor_before(offset + value.len());
 7752
 7753                        if moved_since_edit {
 7754                            edits.push((start..end, String::new()));
 7755                        } else {
 7756                            edits.last_mut().unwrap().0.end = end;
 7757                        }
 7758
 7759                        offset += value.len();
 7760                        moved_since_edit = false;
 7761                    }
 7762                    ChangeTag::Insert => {
 7763                        if moved_since_edit {
 7764                            let anchor = buffer.anchor_after(offset);
 7765                            edits.push((anchor..anchor, value.to_string()));
 7766                        } else {
 7767                            edits.last_mut().unwrap().1.push_str(value);
 7768                        }
 7769
 7770                        moved_since_edit = false;
 7771                    }
 7772                }
 7773            }
 7774
 7775            rewrapped_row_ranges.push(start_row..=end_row);
 7776        }
 7777
 7778        self.buffer
 7779            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7780    }
 7781
 7782    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7783        let mut text = String::new();
 7784        let buffer = self.buffer.read(cx).snapshot(cx);
 7785        let mut selections = self.selections.all::<Point>(cx);
 7786        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7787        {
 7788            let max_point = buffer.max_point();
 7789            let mut is_first = true;
 7790            for selection in &mut selections {
 7791                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7792                if is_entire_line {
 7793                    selection.start = Point::new(selection.start.row, 0);
 7794                    if !selection.is_empty() && selection.end.column == 0 {
 7795                        selection.end = cmp::min(max_point, selection.end);
 7796                    } else {
 7797                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7798                    }
 7799                    selection.goal = SelectionGoal::None;
 7800                }
 7801                if is_first {
 7802                    is_first = false;
 7803                } else {
 7804                    text += "\n";
 7805                }
 7806                let mut len = 0;
 7807                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7808                    text.push_str(chunk);
 7809                    len += chunk.len();
 7810                }
 7811                clipboard_selections.push(ClipboardSelection {
 7812                    len,
 7813                    is_entire_line,
 7814                    first_line_indent: buffer
 7815                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7816                        .len,
 7817                });
 7818            }
 7819        }
 7820
 7821        self.transact(window, cx, |this, window, cx| {
 7822            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7823                s.select(selections);
 7824            });
 7825            this.insert("", window, cx);
 7826        });
 7827        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7828    }
 7829
 7830    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7831        let item = self.cut_common(window, cx);
 7832        cx.write_to_clipboard(item);
 7833    }
 7834
 7835    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7836        self.change_selections(None, window, cx, |s| {
 7837            s.move_with(|snapshot, sel| {
 7838                if sel.is_empty() {
 7839                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7840                }
 7841            });
 7842        });
 7843        let item = self.cut_common(window, cx);
 7844        cx.set_global(KillRing(item))
 7845    }
 7846
 7847    pub fn kill_ring_yank(
 7848        &mut self,
 7849        _: &KillRingYank,
 7850        window: &mut Window,
 7851        cx: &mut Context<Self>,
 7852    ) {
 7853        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7854            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7855                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7856            } else {
 7857                return;
 7858            }
 7859        } else {
 7860            return;
 7861        };
 7862        self.do_paste(&text, metadata, false, window, cx);
 7863    }
 7864
 7865    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7866        let selections = self.selections.all::<Point>(cx);
 7867        let buffer = self.buffer.read(cx).read(cx);
 7868        let mut text = String::new();
 7869
 7870        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7871        {
 7872            let max_point = buffer.max_point();
 7873            let mut is_first = true;
 7874            for selection in selections.iter() {
 7875                let mut start = selection.start;
 7876                let mut end = selection.end;
 7877                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7878                if is_entire_line {
 7879                    start = Point::new(start.row, 0);
 7880                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7881                }
 7882                if is_first {
 7883                    is_first = false;
 7884                } else {
 7885                    text += "\n";
 7886                }
 7887                let mut len = 0;
 7888                for chunk in buffer.text_for_range(start..end) {
 7889                    text.push_str(chunk);
 7890                    len += chunk.len();
 7891                }
 7892                clipboard_selections.push(ClipboardSelection {
 7893                    len,
 7894                    is_entire_line,
 7895                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7896                });
 7897            }
 7898        }
 7899
 7900        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7901            text,
 7902            clipboard_selections,
 7903        ));
 7904    }
 7905
 7906    pub fn do_paste(
 7907        &mut self,
 7908        text: &String,
 7909        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7910        handle_entire_lines: bool,
 7911        window: &mut Window,
 7912        cx: &mut Context<Self>,
 7913    ) {
 7914        if self.read_only(cx) {
 7915            return;
 7916        }
 7917
 7918        let clipboard_text = Cow::Borrowed(text);
 7919
 7920        self.transact(window, cx, |this, window, cx| {
 7921            if let Some(mut clipboard_selections) = clipboard_selections {
 7922                let old_selections = this.selections.all::<usize>(cx);
 7923                let all_selections_were_entire_line =
 7924                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7925                let first_selection_indent_column =
 7926                    clipboard_selections.first().map(|s| s.first_line_indent);
 7927                if clipboard_selections.len() != old_selections.len() {
 7928                    clipboard_selections.drain(..);
 7929                }
 7930                let cursor_offset = this.selections.last::<usize>(cx).head();
 7931                let mut auto_indent_on_paste = true;
 7932
 7933                this.buffer.update(cx, |buffer, cx| {
 7934                    let snapshot = buffer.read(cx);
 7935                    auto_indent_on_paste =
 7936                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7937
 7938                    let mut start_offset = 0;
 7939                    let mut edits = Vec::new();
 7940                    let mut original_indent_columns = Vec::new();
 7941                    for (ix, selection) in old_selections.iter().enumerate() {
 7942                        let to_insert;
 7943                        let entire_line;
 7944                        let original_indent_column;
 7945                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7946                            let end_offset = start_offset + clipboard_selection.len;
 7947                            to_insert = &clipboard_text[start_offset..end_offset];
 7948                            entire_line = clipboard_selection.is_entire_line;
 7949                            start_offset = end_offset + 1;
 7950                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7951                        } else {
 7952                            to_insert = clipboard_text.as_str();
 7953                            entire_line = all_selections_were_entire_line;
 7954                            original_indent_column = first_selection_indent_column
 7955                        }
 7956
 7957                        // If the corresponding selection was empty when this slice of the
 7958                        // clipboard text was written, then the entire line containing the
 7959                        // selection was copied. If this selection is also currently empty,
 7960                        // then paste the line before the current line of the buffer.
 7961                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7962                            let column = selection.start.to_point(&snapshot).column as usize;
 7963                            let line_start = selection.start - column;
 7964                            line_start..line_start
 7965                        } else {
 7966                            selection.range()
 7967                        };
 7968
 7969                        edits.push((range, to_insert));
 7970                        original_indent_columns.extend(original_indent_column);
 7971                    }
 7972                    drop(snapshot);
 7973
 7974                    buffer.edit(
 7975                        edits,
 7976                        if auto_indent_on_paste {
 7977                            Some(AutoindentMode::Block {
 7978                                original_indent_columns,
 7979                            })
 7980                        } else {
 7981                            None
 7982                        },
 7983                        cx,
 7984                    );
 7985                });
 7986
 7987                let selections = this.selections.all::<usize>(cx);
 7988                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7989                    s.select(selections)
 7990                });
 7991            } else {
 7992                this.insert(&clipboard_text, window, cx);
 7993            }
 7994        });
 7995    }
 7996
 7997    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7998        if let Some(item) = cx.read_from_clipboard() {
 7999            let entries = item.entries();
 8000
 8001            match entries.first() {
 8002                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8003                // of all the pasted entries.
 8004                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8005                    .do_paste(
 8006                        clipboard_string.text(),
 8007                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8008                        true,
 8009                        window,
 8010                        cx,
 8011                    ),
 8012                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8013            }
 8014        }
 8015    }
 8016
 8017    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8018        if self.read_only(cx) {
 8019            return;
 8020        }
 8021
 8022        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8023            if let Some((selections, _)) =
 8024                self.selection_history.transaction(transaction_id).cloned()
 8025            {
 8026                self.change_selections(None, window, cx, |s| {
 8027                    s.select_anchors(selections.to_vec());
 8028                });
 8029            }
 8030            self.request_autoscroll(Autoscroll::fit(), cx);
 8031            self.unmark_text(window, cx);
 8032            self.refresh_inline_completion(true, false, window, cx);
 8033            cx.emit(EditorEvent::Edited { transaction_id });
 8034            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8035        }
 8036    }
 8037
 8038    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8039        if self.read_only(cx) {
 8040            return;
 8041        }
 8042
 8043        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8044            if let Some((_, Some(selections))) =
 8045                self.selection_history.transaction(transaction_id).cloned()
 8046            {
 8047                self.change_selections(None, window, cx, |s| {
 8048                    s.select_anchors(selections.to_vec());
 8049                });
 8050            }
 8051            self.request_autoscroll(Autoscroll::fit(), cx);
 8052            self.unmark_text(window, cx);
 8053            self.refresh_inline_completion(true, false, window, cx);
 8054            cx.emit(EditorEvent::Edited { transaction_id });
 8055        }
 8056    }
 8057
 8058    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8059        self.buffer
 8060            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8061    }
 8062
 8063    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8064        self.buffer
 8065            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8066    }
 8067
 8068    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8069        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8070            let line_mode = s.line_mode;
 8071            s.move_with(|map, selection| {
 8072                let cursor = if selection.is_empty() && !line_mode {
 8073                    movement::left(map, selection.start)
 8074                } else {
 8075                    selection.start
 8076                };
 8077                selection.collapse_to(cursor, SelectionGoal::None);
 8078            });
 8079        })
 8080    }
 8081
 8082    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8083        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8084            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8085        })
 8086    }
 8087
 8088    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8090            let line_mode = s.line_mode;
 8091            s.move_with(|map, selection| {
 8092                let cursor = if selection.is_empty() && !line_mode {
 8093                    movement::right(map, selection.end)
 8094                } else {
 8095                    selection.end
 8096                };
 8097                selection.collapse_to(cursor, SelectionGoal::None)
 8098            });
 8099        })
 8100    }
 8101
 8102    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8103        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8104            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8105        })
 8106    }
 8107
 8108    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8109        if self.take_rename(true, window, cx).is_some() {
 8110            return;
 8111        }
 8112
 8113        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8114            cx.propagate();
 8115            return;
 8116        }
 8117
 8118        let text_layout_details = &self.text_layout_details(window);
 8119        let selection_count = self.selections.count();
 8120        let first_selection = self.selections.first_anchor();
 8121
 8122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8123            let line_mode = s.line_mode;
 8124            s.move_with(|map, selection| {
 8125                if !selection.is_empty() && !line_mode {
 8126                    selection.goal = SelectionGoal::None;
 8127                }
 8128                let (cursor, goal) = movement::up(
 8129                    map,
 8130                    selection.start,
 8131                    selection.goal,
 8132                    false,
 8133                    text_layout_details,
 8134                );
 8135                selection.collapse_to(cursor, goal);
 8136            });
 8137        });
 8138
 8139        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8140        {
 8141            cx.propagate();
 8142        }
 8143    }
 8144
 8145    pub fn move_up_by_lines(
 8146        &mut self,
 8147        action: &MoveUpByLines,
 8148        window: &mut Window,
 8149        cx: &mut Context<Self>,
 8150    ) {
 8151        if self.take_rename(true, window, cx).is_some() {
 8152            return;
 8153        }
 8154
 8155        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8156            cx.propagate();
 8157            return;
 8158        }
 8159
 8160        let text_layout_details = &self.text_layout_details(window);
 8161
 8162        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8163            let line_mode = s.line_mode;
 8164            s.move_with(|map, selection| {
 8165                if !selection.is_empty() && !line_mode {
 8166                    selection.goal = SelectionGoal::None;
 8167                }
 8168                let (cursor, goal) = movement::up_by_rows(
 8169                    map,
 8170                    selection.start,
 8171                    action.lines,
 8172                    selection.goal,
 8173                    false,
 8174                    text_layout_details,
 8175                );
 8176                selection.collapse_to(cursor, goal);
 8177            });
 8178        })
 8179    }
 8180
 8181    pub fn move_down_by_lines(
 8182        &mut self,
 8183        action: &MoveDownByLines,
 8184        window: &mut Window,
 8185        cx: &mut Context<Self>,
 8186    ) {
 8187        if self.take_rename(true, window, cx).is_some() {
 8188            return;
 8189        }
 8190
 8191        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8192            cx.propagate();
 8193            return;
 8194        }
 8195
 8196        let text_layout_details = &self.text_layout_details(window);
 8197
 8198        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8199            let line_mode = s.line_mode;
 8200            s.move_with(|map, selection| {
 8201                if !selection.is_empty() && !line_mode {
 8202                    selection.goal = SelectionGoal::None;
 8203                }
 8204                let (cursor, goal) = movement::down_by_rows(
 8205                    map,
 8206                    selection.start,
 8207                    action.lines,
 8208                    selection.goal,
 8209                    false,
 8210                    text_layout_details,
 8211                );
 8212                selection.collapse_to(cursor, goal);
 8213            });
 8214        })
 8215    }
 8216
 8217    pub fn select_down_by_lines(
 8218        &mut self,
 8219        action: &SelectDownByLines,
 8220        window: &mut Window,
 8221        cx: &mut Context<Self>,
 8222    ) {
 8223        let text_layout_details = &self.text_layout_details(window);
 8224        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8225            s.move_heads_with(|map, head, goal| {
 8226                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8227            })
 8228        })
 8229    }
 8230
 8231    pub fn select_up_by_lines(
 8232        &mut self,
 8233        action: &SelectUpByLines,
 8234        window: &mut Window,
 8235        cx: &mut Context<Self>,
 8236    ) {
 8237        let text_layout_details = &self.text_layout_details(window);
 8238        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8239            s.move_heads_with(|map, head, goal| {
 8240                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8241            })
 8242        })
 8243    }
 8244
 8245    pub fn select_page_up(
 8246        &mut self,
 8247        _: &SelectPageUp,
 8248        window: &mut Window,
 8249        cx: &mut Context<Self>,
 8250    ) {
 8251        let Some(row_count) = self.visible_row_count() else {
 8252            return;
 8253        };
 8254
 8255        let text_layout_details = &self.text_layout_details(window);
 8256
 8257        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8258            s.move_heads_with(|map, head, goal| {
 8259                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8260            })
 8261        })
 8262    }
 8263
 8264    pub fn move_page_up(
 8265        &mut self,
 8266        action: &MovePageUp,
 8267        window: &mut Window,
 8268        cx: &mut Context<Self>,
 8269    ) {
 8270        if self.take_rename(true, window, cx).is_some() {
 8271            return;
 8272        }
 8273
 8274        if self
 8275            .context_menu
 8276            .borrow_mut()
 8277            .as_mut()
 8278            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8279            .unwrap_or(false)
 8280        {
 8281            return;
 8282        }
 8283
 8284        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8285            cx.propagate();
 8286            return;
 8287        }
 8288
 8289        let Some(row_count) = self.visible_row_count() else {
 8290            return;
 8291        };
 8292
 8293        let autoscroll = if action.center_cursor {
 8294            Autoscroll::center()
 8295        } else {
 8296            Autoscroll::fit()
 8297        };
 8298
 8299        let text_layout_details = &self.text_layout_details(window);
 8300
 8301        self.change_selections(Some(autoscroll), window, cx, |s| {
 8302            let line_mode = s.line_mode;
 8303            s.move_with(|map, selection| {
 8304                if !selection.is_empty() && !line_mode {
 8305                    selection.goal = SelectionGoal::None;
 8306                }
 8307                let (cursor, goal) = movement::up_by_rows(
 8308                    map,
 8309                    selection.end,
 8310                    row_count,
 8311                    selection.goal,
 8312                    false,
 8313                    text_layout_details,
 8314                );
 8315                selection.collapse_to(cursor, goal);
 8316            });
 8317        });
 8318    }
 8319
 8320    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8321        let text_layout_details = &self.text_layout_details(window);
 8322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8323            s.move_heads_with(|map, head, goal| {
 8324                movement::up(map, head, goal, false, text_layout_details)
 8325            })
 8326        })
 8327    }
 8328
 8329    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8330        self.take_rename(true, window, cx);
 8331
 8332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8333            cx.propagate();
 8334            return;
 8335        }
 8336
 8337        let text_layout_details = &self.text_layout_details(window);
 8338        let selection_count = self.selections.count();
 8339        let first_selection = self.selections.first_anchor();
 8340
 8341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8342            let line_mode = s.line_mode;
 8343            s.move_with(|map, selection| {
 8344                if !selection.is_empty() && !line_mode {
 8345                    selection.goal = SelectionGoal::None;
 8346                }
 8347                let (cursor, goal) = movement::down(
 8348                    map,
 8349                    selection.end,
 8350                    selection.goal,
 8351                    false,
 8352                    text_layout_details,
 8353                );
 8354                selection.collapse_to(cursor, goal);
 8355            });
 8356        });
 8357
 8358        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8359        {
 8360            cx.propagate();
 8361        }
 8362    }
 8363
 8364    pub fn select_page_down(
 8365        &mut self,
 8366        _: &SelectPageDown,
 8367        window: &mut Window,
 8368        cx: &mut Context<Self>,
 8369    ) {
 8370        let Some(row_count) = self.visible_row_count() else {
 8371            return;
 8372        };
 8373
 8374        let text_layout_details = &self.text_layout_details(window);
 8375
 8376        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8377            s.move_heads_with(|map, head, goal| {
 8378                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8379            })
 8380        })
 8381    }
 8382
 8383    pub fn move_page_down(
 8384        &mut self,
 8385        action: &MovePageDown,
 8386        window: &mut Window,
 8387        cx: &mut Context<Self>,
 8388    ) {
 8389        if self.take_rename(true, window, cx).is_some() {
 8390            return;
 8391        }
 8392
 8393        if self
 8394            .context_menu
 8395            .borrow_mut()
 8396            .as_mut()
 8397            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8398            .unwrap_or(false)
 8399        {
 8400            return;
 8401        }
 8402
 8403        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8404            cx.propagate();
 8405            return;
 8406        }
 8407
 8408        let Some(row_count) = self.visible_row_count() else {
 8409            return;
 8410        };
 8411
 8412        let autoscroll = if action.center_cursor {
 8413            Autoscroll::center()
 8414        } else {
 8415            Autoscroll::fit()
 8416        };
 8417
 8418        let text_layout_details = &self.text_layout_details(window);
 8419        self.change_selections(Some(autoscroll), window, cx, |s| {
 8420            let line_mode = s.line_mode;
 8421            s.move_with(|map, selection| {
 8422                if !selection.is_empty() && !line_mode {
 8423                    selection.goal = SelectionGoal::None;
 8424                }
 8425                let (cursor, goal) = movement::down_by_rows(
 8426                    map,
 8427                    selection.end,
 8428                    row_count,
 8429                    selection.goal,
 8430                    false,
 8431                    text_layout_details,
 8432                );
 8433                selection.collapse_to(cursor, goal);
 8434            });
 8435        });
 8436    }
 8437
 8438    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8439        let text_layout_details = &self.text_layout_details(window);
 8440        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8441            s.move_heads_with(|map, head, goal| {
 8442                movement::down(map, head, goal, false, text_layout_details)
 8443            })
 8444        });
 8445    }
 8446
 8447    pub fn context_menu_first(
 8448        &mut self,
 8449        _: &ContextMenuFirst,
 8450        _window: &mut Window,
 8451        cx: &mut Context<Self>,
 8452    ) {
 8453        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8454            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8455        }
 8456    }
 8457
 8458    pub fn context_menu_prev(
 8459        &mut self,
 8460        _: &ContextMenuPrev,
 8461        _window: &mut Window,
 8462        cx: &mut Context<Self>,
 8463    ) {
 8464        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8465            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8466        }
 8467    }
 8468
 8469    pub fn context_menu_next(
 8470        &mut self,
 8471        _: &ContextMenuNext,
 8472        _window: &mut Window,
 8473        cx: &mut Context<Self>,
 8474    ) {
 8475        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8476            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8477        }
 8478    }
 8479
 8480    pub fn context_menu_last(
 8481        &mut self,
 8482        _: &ContextMenuLast,
 8483        _window: &mut Window,
 8484        cx: &mut Context<Self>,
 8485    ) {
 8486        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8487            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8488        }
 8489    }
 8490
 8491    pub fn move_to_previous_word_start(
 8492        &mut self,
 8493        _: &MoveToPreviousWordStart,
 8494        window: &mut Window,
 8495        cx: &mut Context<Self>,
 8496    ) {
 8497        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8498            s.move_cursors_with(|map, head, _| {
 8499                (
 8500                    movement::previous_word_start(map, head),
 8501                    SelectionGoal::None,
 8502                )
 8503            });
 8504        })
 8505    }
 8506
 8507    pub fn move_to_previous_subword_start(
 8508        &mut self,
 8509        _: &MoveToPreviousSubwordStart,
 8510        window: &mut Window,
 8511        cx: &mut Context<Self>,
 8512    ) {
 8513        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8514            s.move_cursors_with(|map, head, _| {
 8515                (
 8516                    movement::previous_subword_start(map, head),
 8517                    SelectionGoal::None,
 8518                )
 8519            });
 8520        })
 8521    }
 8522
 8523    pub fn select_to_previous_word_start(
 8524        &mut self,
 8525        _: &SelectToPreviousWordStart,
 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                (
 8532                    movement::previous_word_start(map, head),
 8533                    SelectionGoal::None,
 8534                )
 8535            });
 8536        })
 8537    }
 8538
 8539    pub fn select_to_previous_subword_start(
 8540        &mut self,
 8541        _: &SelectToPreviousSubwordStart,
 8542        window: &mut Window,
 8543        cx: &mut Context<Self>,
 8544    ) {
 8545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8546            s.move_heads_with(|map, head, _| {
 8547                (
 8548                    movement::previous_subword_start(map, head),
 8549                    SelectionGoal::None,
 8550                )
 8551            });
 8552        })
 8553    }
 8554
 8555    pub fn delete_to_previous_word_start(
 8556        &mut self,
 8557        action: &DeleteToPreviousWordStart,
 8558        window: &mut Window,
 8559        cx: &mut Context<Self>,
 8560    ) {
 8561        self.transact(window, cx, |this, window, cx| {
 8562            this.select_autoclose_pair(window, cx);
 8563            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8564                let line_mode = s.line_mode;
 8565                s.move_with(|map, selection| {
 8566                    if selection.is_empty() && !line_mode {
 8567                        let cursor = if action.ignore_newlines {
 8568                            movement::previous_word_start(map, selection.head())
 8569                        } else {
 8570                            movement::previous_word_start_or_newline(map, selection.head())
 8571                        };
 8572                        selection.set_head(cursor, SelectionGoal::None);
 8573                    }
 8574                });
 8575            });
 8576            this.insert("", window, cx);
 8577        });
 8578    }
 8579
 8580    pub fn delete_to_previous_subword_start(
 8581        &mut self,
 8582        _: &DeleteToPreviousSubwordStart,
 8583        window: &mut Window,
 8584        cx: &mut Context<Self>,
 8585    ) {
 8586        self.transact(window, cx, |this, window, cx| {
 8587            this.select_autoclose_pair(window, cx);
 8588            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8589                let line_mode = s.line_mode;
 8590                s.move_with(|map, selection| {
 8591                    if selection.is_empty() && !line_mode {
 8592                        let cursor = movement::previous_subword_start(map, selection.head());
 8593                        selection.set_head(cursor, SelectionGoal::None);
 8594                    }
 8595                });
 8596            });
 8597            this.insert("", window, cx);
 8598        });
 8599    }
 8600
 8601    pub fn move_to_next_word_end(
 8602        &mut self,
 8603        _: &MoveToNextWordEnd,
 8604        window: &mut Window,
 8605        cx: &mut Context<Self>,
 8606    ) {
 8607        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608            s.move_cursors_with(|map, head, _| {
 8609                (movement::next_word_end(map, head), SelectionGoal::None)
 8610            });
 8611        })
 8612    }
 8613
 8614    pub fn move_to_next_subword_end(
 8615        &mut self,
 8616        _: &MoveToNextSubwordEnd,
 8617        window: &mut Window,
 8618        cx: &mut Context<Self>,
 8619    ) {
 8620        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8621            s.move_cursors_with(|map, head, _| {
 8622                (movement::next_subword_end(map, head), SelectionGoal::None)
 8623            });
 8624        })
 8625    }
 8626
 8627    pub fn select_to_next_word_end(
 8628        &mut self,
 8629        _: &SelectToNextWordEnd,
 8630        window: &mut Window,
 8631        cx: &mut Context<Self>,
 8632    ) {
 8633        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8634            s.move_heads_with(|map, head, _| {
 8635                (movement::next_word_end(map, head), SelectionGoal::None)
 8636            });
 8637        })
 8638    }
 8639
 8640    pub fn select_to_next_subword_end(
 8641        &mut self,
 8642        _: &SelectToNextSubwordEnd,
 8643        window: &mut Window,
 8644        cx: &mut Context<Self>,
 8645    ) {
 8646        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8647            s.move_heads_with(|map, head, _| {
 8648                (movement::next_subword_end(map, head), SelectionGoal::None)
 8649            });
 8650        })
 8651    }
 8652
 8653    pub fn delete_to_next_word_end(
 8654        &mut self,
 8655        action: &DeleteToNextWordEnd,
 8656        window: &mut Window,
 8657        cx: &mut Context<Self>,
 8658    ) {
 8659        self.transact(window, cx, |this, window, cx| {
 8660            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8661                let line_mode = s.line_mode;
 8662                s.move_with(|map, selection| {
 8663                    if selection.is_empty() && !line_mode {
 8664                        let cursor = if action.ignore_newlines {
 8665                            movement::next_word_end(map, selection.head())
 8666                        } else {
 8667                            movement::next_word_end_or_newline(map, selection.head())
 8668                        };
 8669                        selection.set_head(cursor, SelectionGoal::None);
 8670                    }
 8671                });
 8672            });
 8673            this.insert("", window, cx);
 8674        });
 8675    }
 8676
 8677    pub fn delete_to_next_subword_end(
 8678        &mut self,
 8679        _: &DeleteToNextSubwordEnd,
 8680        window: &mut Window,
 8681        cx: &mut Context<Self>,
 8682    ) {
 8683        self.transact(window, cx, |this, window, cx| {
 8684            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8685                s.move_with(|map, selection| {
 8686                    if selection.is_empty() {
 8687                        let cursor = movement::next_subword_end(map, selection.head());
 8688                        selection.set_head(cursor, SelectionGoal::None);
 8689                    }
 8690                });
 8691            });
 8692            this.insert("", window, cx);
 8693        });
 8694    }
 8695
 8696    pub fn move_to_beginning_of_line(
 8697        &mut self,
 8698        action: &MoveToBeginningOfLine,
 8699        window: &mut Window,
 8700        cx: &mut Context<Self>,
 8701    ) {
 8702        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8703            s.move_cursors_with(|map, head, _| {
 8704                (
 8705                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8706                    SelectionGoal::None,
 8707                )
 8708            });
 8709        })
 8710    }
 8711
 8712    pub fn select_to_beginning_of_line(
 8713        &mut self,
 8714        action: &SelectToBeginningOfLine,
 8715        window: &mut Window,
 8716        cx: &mut Context<Self>,
 8717    ) {
 8718        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8719            s.move_heads_with(|map, head, _| {
 8720                (
 8721                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8722                    SelectionGoal::None,
 8723                )
 8724            });
 8725        });
 8726    }
 8727
 8728    pub fn delete_to_beginning_of_line(
 8729        &mut self,
 8730        _: &DeleteToBeginningOfLine,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        self.transact(window, cx, |this, window, cx| {
 8735            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8736                s.move_with(|_, selection| {
 8737                    selection.reversed = true;
 8738                });
 8739            });
 8740
 8741            this.select_to_beginning_of_line(
 8742                &SelectToBeginningOfLine {
 8743                    stop_at_soft_wraps: false,
 8744                },
 8745                window,
 8746                cx,
 8747            );
 8748            this.backspace(&Backspace, window, cx);
 8749        });
 8750    }
 8751
 8752    pub fn move_to_end_of_line(
 8753        &mut self,
 8754        action: &MoveToEndOfLine,
 8755        window: &mut Window,
 8756        cx: &mut Context<Self>,
 8757    ) {
 8758        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8759            s.move_cursors_with(|map, head, _| {
 8760                (
 8761                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8762                    SelectionGoal::None,
 8763                )
 8764            });
 8765        })
 8766    }
 8767
 8768    pub fn select_to_end_of_line(
 8769        &mut self,
 8770        action: &SelectToEndOfLine,
 8771        window: &mut Window,
 8772        cx: &mut Context<Self>,
 8773    ) {
 8774        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8775            s.move_heads_with(|map, head, _| {
 8776                (
 8777                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8778                    SelectionGoal::None,
 8779                )
 8780            });
 8781        })
 8782    }
 8783
 8784    pub fn delete_to_end_of_line(
 8785        &mut self,
 8786        _: &DeleteToEndOfLine,
 8787        window: &mut Window,
 8788        cx: &mut Context<Self>,
 8789    ) {
 8790        self.transact(window, cx, |this, window, cx| {
 8791            this.select_to_end_of_line(
 8792                &SelectToEndOfLine {
 8793                    stop_at_soft_wraps: false,
 8794                },
 8795                window,
 8796                cx,
 8797            );
 8798            this.delete(&Delete, window, cx);
 8799        });
 8800    }
 8801
 8802    pub fn cut_to_end_of_line(
 8803        &mut self,
 8804        _: &CutToEndOfLine,
 8805        window: &mut Window,
 8806        cx: &mut Context<Self>,
 8807    ) {
 8808        self.transact(window, cx, |this, window, cx| {
 8809            this.select_to_end_of_line(
 8810                &SelectToEndOfLine {
 8811                    stop_at_soft_wraps: false,
 8812                },
 8813                window,
 8814                cx,
 8815            );
 8816            this.cut(&Cut, window, cx);
 8817        });
 8818    }
 8819
 8820    pub fn move_to_start_of_paragraph(
 8821        &mut self,
 8822        _: &MoveToStartOfParagraph,
 8823        window: &mut Window,
 8824        cx: &mut Context<Self>,
 8825    ) {
 8826        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8827            cx.propagate();
 8828            return;
 8829        }
 8830
 8831        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8832            s.move_with(|map, selection| {
 8833                selection.collapse_to(
 8834                    movement::start_of_paragraph(map, selection.head(), 1),
 8835                    SelectionGoal::None,
 8836                )
 8837            });
 8838        })
 8839    }
 8840
 8841    pub fn move_to_end_of_paragraph(
 8842        &mut self,
 8843        _: &MoveToEndOfParagraph,
 8844        window: &mut Window,
 8845        cx: &mut Context<Self>,
 8846    ) {
 8847        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8848            cx.propagate();
 8849            return;
 8850        }
 8851
 8852        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8853            s.move_with(|map, selection| {
 8854                selection.collapse_to(
 8855                    movement::end_of_paragraph(map, selection.head(), 1),
 8856                    SelectionGoal::None,
 8857                )
 8858            });
 8859        })
 8860    }
 8861
 8862    pub fn select_to_start_of_paragraph(
 8863        &mut self,
 8864        _: &SelectToStartOfParagraph,
 8865        window: &mut Window,
 8866        cx: &mut Context<Self>,
 8867    ) {
 8868        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8869            cx.propagate();
 8870            return;
 8871        }
 8872
 8873        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8874            s.move_heads_with(|map, head, _| {
 8875                (
 8876                    movement::start_of_paragraph(map, head, 1),
 8877                    SelectionGoal::None,
 8878                )
 8879            });
 8880        })
 8881    }
 8882
 8883    pub fn select_to_end_of_paragraph(
 8884        &mut self,
 8885        _: &SelectToEndOfParagraph,
 8886        window: &mut Window,
 8887        cx: &mut Context<Self>,
 8888    ) {
 8889        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8890            cx.propagate();
 8891            return;
 8892        }
 8893
 8894        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8895            s.move_heads_with(|map, head, _| {
 8896                (
 8897                    movement::end_of_paragraph(map, head, 1),
 8898                    SelectionGoal::None,
 8899                )
 8900            });
 8901        })
 8902    }
 8903
 8904    pub fn move_to_beginning(
 8905        &mut self,
 8906        _: &MoveToBeginning,
 8907        window: &mut Window,
 8908        cx: &mut Context<Self>,
 8909    ) {
 8910        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8911            cx.propagate();
 8912            return;
 8913        }
 8914
 8915        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8916            s.select_ranges(vec![0..0]);
 8917        });
 8918    }
 8919
 8920    pub fn select_to_beginning(
 8921        &mut self,
 8922        _: &SelectToBeginning,
 8923        window: &mut Window,
 8924        cx: &mut Context<Self>,
 8925    ) {
 8926        let mut selection = self.selections.last::<Point>(cx);
 8927        selection.set_head(Point::zero(), SelectionGoal::None);
 8928
 8929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8930            s.select(vec![selection]);
 8931        });
 8932    }
 8933
 8934    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8935        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8936            cx.propagate();
 8937            return;
 8938        }
 8939
 8940        let cursor = self.buffer.read(cx).read(cx).len();
 8941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8942            s.select_ranges(vec![cursor..cursor])
 8943        });
 8944    }
 8945
 8946    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8947        self.nav_history = nav_history;
 8948    }
 8949
 8950    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8951        self.nav_history.as_ref()
 8952    }
 8953
 8954    fn push_to_nav_history(
 8955        &mut self,
 8956        cursor_anchor: Anchor,
 8957        new_position: Option<Point>,
 8958        cx: &mut Context<Self>,
 8959    ) {
 8960        if let Some(nav_history) = self.nav_history.as_mut() {
 8961            let buffer = self.buffer.read(cx).read(cx);
 8962            let cursor_position = cursor_anchor.to_point(&buffer);
 8963            let scroll_state = self.scroll_manager.anchor();
 8964            let scroll_top_row = scroll_state.top_row(&buffer);
 8965            drop(buffer);
 8966
 8967            if let Some(new_position) = new_position {
 8968                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8969                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8970                    return;
 8971                }
 8972            }
 8973
 8974            nav_history.push(
 8975                Some(NavigationData {
 8976                    cursor_anchor,
 8977                    cursor_position,
 8978                    scroll_anchor: scroll_state,
 8979                    scroll_top_row,
 8980                }),
 8981                cx,
 8982            );
 8983        }
 8984    }
 8985
 8986    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8987        let buffer = self.buffer.read(cx).snapshot(cx);
 8988        let mut selection = self.selections.first::<usize>(cx);
 8989        selection.set_head(buffer.len(), SelectionGoal::None);
 8990        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8991            s.select(vec![selection]);
 8992        });
 8993    }
 8994
 8995    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8996        let end = self.buffer.read(cx).read(cx).len();
 8997        self.change_selections(None, window, cx, |s| {
 8998            s.select_ranges(vec![0..end]);
 8999        });
 9000    }
 9001
 9002    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9003        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9004        let mut selections = self.selections.all::<Point>(cx);
 9005        let max_point = display_map.buffer_snapshot.max_point();
 9006        for selection in &mut selections {
 9007            let rows = selection.spanned_rows(true, &display_map);
 9008            selection.start = Point::new(rows.start.0, 0);
 9009            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9010            selection.reversed = false;
 9011        }
 9012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9013            s.select(selections);
 9014        });
 9015    }
 9016
 9017    pub fn split_selection_into_lines(
 9018        &mut self,
 9019        _: &SplitSelectionIntoLines,
 9020        window: &mut Window,
 9021        cx: &mut Context<Self>,
 9022    ) {
 9023        let mut to_unfold = Vec::new();
 9024        let mut new_selection_ranges = Vec::new();
 9025        {
 9026            let selections = self.selections.all::<Point>(cx);
 9027            let buffer = self.buffer.read(cx).read(cx);
 9028            for selection in selections {
 9029                for row in selection.start.row..selection.end.row {
 9030                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9031                    new_selection_ranges.push(cursor..cursor);
 9032                }
 9033                new_selection_ranges.push(selection.end..selection.end);
 9034                to_unfold.push(selection.start..selection.end);
 9035            }
 9036        }
 9037        self.unfold_ranges(&to_unfold, true, true, cx);
 9038        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9039            s.select_ranges(new_selection_ranges);
 9040        });
 9041    }
 9042
 9043    pub fn add_selection_above(
 9044        &mut self,
 9045        _: &AddSelectionAbove,
 9046        window: &mut Window,
 9047        cx: &mut Context<Self>,
 9048    ) {
 9049        self.add_selection(true, window, cx);
 9050    }
 9051
 9052    pub fn add_selection_below(
 9053        &mut self,
 9054        _: &AddSelectionBelow,
 9055        window: &mut Window,
 9056        cx: &mut Context<Self>,
 9057    ) {
 9058        self.add_selection(false, window, cx);
 9059    }
 9060
 9061    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9062        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9063        let mut selections = self.selections.all::<Point>(cx);
 9064        let text_layout_details = self.text_layout_details(window);
 9065        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9066            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9067            let range = oldest_selection.display_range(&display_map).sorted();
 9068
 9069            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9070            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9071            let positions = start_x.min(end_x)..start_x.max(end_x);
 9072
 9073            selections.clear();
 9074            let mut stack = Vec::new();
 9075            for row in range.start.row().0..=range.end.row().0 {
 9076                if let Some(selection) = self.selections.build_columnar_selection(
 9077                    &display_map,
 9078                    DisplayRow(row),
 9079                    &positions,
 9080                    oldest_selection.reversed,
 9081                    &text_layout_details,
 9082                ) {
 9083                    stack.push(selection.id);
 9084                    selections.push(selection);
 9085                }
 9086            }
 9087
 9088            if above {
 9089                stack.reverse();
 9090            }
 9091
 9092            AddSelectionsState { above, stack }
 9093        });
 9094
 9095        let last_added_selection = *state.stack.last().unwrap();
 9096        let mut new_selections = Vec::new();
 9097        if above == state.above {
 9098            let end_row = if above {
 9099                DisplayRow(0)
 9100            } else {
 9101                display_map.max_point().row()
 9102            };
 9103
 9104            'outer: for selection in selections {
 9105                if selection.id == last_added_selection {
 9106                    let range = selection.display_range(&display_map).sorted();
 9107                    debug_assert_eq!(range.start.row(), range.end.row());
 9108                    let mut row = range.start.row();
 9109                    let positions =
 9110                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9111                            px(start)..px(end)
 9112                        } else {
 9113                            let start_x =
 9114                                display_map.x_for_display_point(range.start, &text_layout_details);
 9115                            let end_x =
 9116                                display_map.x_for_display_point(range.end, &text_layout_details);
 9117                            start_x.min(end_x)..start_x.max(end_x)
 9118                        };
 9119
 9120                    while row != end_row {
 9121                        if above {
 9122                            row.0 -= 1;
 9123                        } else {
 9124                            row.0 += 1;
 9125                        }
 9126
 9127                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9128                            &display_map,
 9129                            row,
 9130                            &positions,
 9131                            selection.reversed,
 9132                            &text_layout_details,
 9133                        ) {
 9134                            state.stack.push(new_selection.id);
 9135                            if above {
 9136                                new_selections.push(new_selection);
 9137                                new_selections.push(selection);
 9138                            } else {
 9139                                new_selections.push(selection);
 9140                                new_selections.push(new_selection);
 9141                            }
 9142
 9143                            continue 'outer;
 9144                        }
 9145                    }
 9146                }
 9147
 9148                new_selections.push(selection);
 9149            }
 9150        } else {
 9151            new_selections = selections;
 9152            new_selections.retain(|s| s.id != last_added_selection);
 9153            state.stack.pop();
 9154        }
 9155
 9156        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9157            s.select(new_selections);
 9158        });
 9159        if state.stack.len() > 1 {
 9160            self.add_selections_state = Some(state);
 9161        }
 9162    }
 9163
 9164    pub fn select_next_match_internal(
 9165        &mut self,
 9166        display_map: &DisplaySnapshot,
 9167        replace_newest: bool,
 9168        autoscroll: Option<Autoscroll>,
 9169        window: &mut Window,
 9170        cx: &mut Context<Self>,
 9171    ) -> Result<()> {
 9172        fn select_next_match_ranges(
 9173            this: &mut Editor,
 9174            range: Range<usize>,
 9175            replace_newest: bool,
 9176            auto_scroll: Option<Autoscroll>,
 9177            window: &mut Window,
 9178            cx: &mut Context<Editor>,
 9179        ) {
 9180            this.unfold_ranges(&[range.clone()], false, true, cx);
 9181            this.change_selections(auto_scroll, window, cx, |s| {
 9182                if replace_newest {
 9183                    s.delete(s.newest_anchor().id);
 9184                }
 9185                s.insert_range(range.clone());
 9186            });
 9187        }
 9188
 9189        let buffer = &display_map.buffer_snapshot;
 9190        let mut selections = self.selections.all::<usize>(cx);
 9191        if let Some(mut select_next_state) = self.select_next_state.take() {
 9192            let query = &select_next_state.query;
 9193            if !select_next_state.done {
 9194                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9195                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9196                let mut next_selected_range = None;
 9197
 9198                let bytes_after_last_selection =
 9199                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9200                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9201                let query_matches = query
 9202                    .stream_find_iter(bytes_after_last_selection)
 9203                    .map(|result| (last_selection.end, result))
 9204                    .chain(
 9205                        query
 9206                            .stream_find_iter(bytes_before_first_selection)
 9207                            .map(|result| (0, result)),
 9208                    );
 9209
 9210                for (start_offset, query_match) in query_matches {
 9211                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9212                    let offset_range =
 9213                        start_offset + query_match.start()..start_offset + query_match.end();
 9214                    let display_range = offset_range.start.to_display_point(display_map)
 9215                        ..offset_range.end.to_display_point(display_map);
 9216
 9217                    if !select_next_state.wordwise
 9218                        || (!movement::is_inside_word(display_map, display_range.start)
 9219                            && !movement::is_inside_word(display_map, display_range.end))
 9220                    {
 9221                        // TODO: This is n^2, because we might check all the selections
 9222                        if !selections
 9223                            .iter()
 9224                            .any(|selection| selection.range().overlaps(&offset_range))
 9225                        {
 9226                            next_selected_range = Some(offset_range);
 9227                            break;
 9228                        }
 9229                    }
 9230                }
 9231
 9232                if let Some(next_selected_range) = next_selected_range {
 9233                    select_next_match_ranges(
 9234                        self,
 9235                        next_selected_range,
 9236                        replace_newest,
 9237                        autoscroll,
 9238                        window,
 9239                        cx,
 9240                    );
 9241                } else {
 9242                    select_next_state.done = true;
 9243                }
 9244            }
 9245
 9246            self.select_next_state = Some(select_next_state);
 9247        } else {
 9248            let mut only_carets = true;
 9249            let mut same_text_selected = true;
 9250            let mut selected_text = None;
 9251
 9252            let mut selections_iter = selections.iter().peekable();
 9253            while let Some(selection) = selections_iter.next() {
 9254                if selection.start != selection.end {
 9255                    only_carets = false;
 9256                }
 9257
 9258                if same_text_selected {
 9259                    if selected_text.is_none() {
 9260                        selected_text =
 9261                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9262                    }
 9263
 9264                    if let Some(next_selection) = selections_iter.peek() {
 9265                        if next_selection.range().len() == selection.range().len() {
 9266                            let next_selected_text = buffer
 9267                                .text_for_range(next_selection.range())
 9268                                .collect::<String>();
 9269                            if Some(next_selected_text) != selected_text {
 9270                                same_text_selected = false;
 9271                                selected_text = None;
 9272                            }
 9273                        } else {
 9274                            same_text_selected = false;
 9275                            selected_text = None;
 9276                        }
 9277                    }
 9278                }
 9279            }
 9280
 9281            if only_carets {
 9282                for selection in &mut selections {
 9283                    let word_range = movement::surrounding_word(
 9284                        display_map,
 9285                        selection.start.to_display_point(display_map),
 9286                    );
 9287                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9288                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9289                    selection.goal = SelectionGoal::None;
 9290                    selection.reversed = false;
 9291                    select_next_match_ranges(
 9292                        self,
 9293                        selection.start..selection.end,
 9294                        replace_newest,
 9295                        autoscroll,
 9296                        window,
 9297                        cx,
 9298                    );
 9299                }
 9300
 9301                if selections.len() == 1 {
 9302                    let selection = selections
 9303                        .last()
 9304                        .expect("ensured that there's only one selection");
 9305                    let query = buffer
 9306                        .text_for_range(selection.start..selection.end)
 9307                        .collect::<String>();
 9308                    let is_empty = query.is_empty();
 9309                    let select_state = SelectNextState {
 9310                        query: AhoCorasick::new(&[query])?,
 9311                        wordwise: true,
 9312                        done: is_empty,
 9313                    };
 9314                    self.select_next_state = Some(select_state);
 9315                } else {
 9316                    self.select_next_state = None;
 9317                }
 9318            } else if let Some(selected_text) = selected_text {
 9319                self.select_next_state = Some(SelectNextState {
 9320                    query: AhoCorasick::new(&[selected_text])?,
 9321                    wordwise: false,
 9322                    done: false,
 9323                });
 9324                self.select_next_match_internal(
 9325                    display_map,
 9326                    replace_newest,
 9327                    autoscroll,
 9328                    window,
 9329                    cx,
 9330                )?;
 9331            }
 9332        }
 9333        Ok(())
 9334    }
 9335
 9336    pub fn select_all_matches(
 9337        &mut self,
 9338        _action: &SelectAllMatches,
 9339        window: &mut Window,
 9340        cx: &mut Context<Self>,
 9341    ) -> Result<()> {
 9342        self.push_to_selection_history();
 9343        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9344
 9345        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9346        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9347            return Ok(());
 9348        };
 9349        if select_next_state.done {
 9350            return Ok(());
 9351        }
 9352
 9353        let mut new_selections = self.selections.all::<usize>(cx);
 9354
 9355        let buffer = &display_map.buffer_snapshot;
 9356        let query_matches = select_next_state
 9357            .query
 9358            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9359
 9360        for query_match in query_matches {
 9361            let query_match = query_match.unwrap(); // can only fail due to I/O
 9362            let offset_range = query_match.start()..query_match.end();
 9363            let display_range = offset_range.start.to_display_point(&display_map)
 9364                ..offset_range.end.to_display_point(&display_map);
 9365
 9366            if !select_next_state.wordwise
 9367                || (!movement::is_inside_word(&display_map, display_range.start)
 9368                    && !movement::is_inside_word(&display_map, display_range.end))
 9369            {
 9370                self.selections.change_with(cx, |selections| {
 9371                    new_selections.push(Selection {
 9372                        id: selections.new_selection_id(),
 9373                        start: offset_range.start,
 9374                        end: offset_range.end,
 9375                        reversed: false,
 9376                        goal: SelectionGoal::None,
 9377                    });
 9378                });
 9379            }
 9380        }
 9381
 9382        new_selections.sort_by_key(|selection| selection.start);
 9383        let mut ix = 0;
 9384        while ix + 1 < new_selections.len() {
 9385            let current_selection = &new_selections[ix];
 9386            let next_selection = &new_selections[ix + 1];
 9387            if current_selection.range().overlaps(&next_selection.range()) {
 9388                if current_selection.id < next_selection.id {
 9389                    new_selections.remove(ix + 1);
 9390                } else {
 9391                    new_selections.remove(ix);
 9392                }
 9393            } else {
 9394                ix += 1;
 9395            }
 9396        }
 9397
 9398        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9399
 9400        for selection in new_selections.iter_mut() {
 9401            selection.reversed = reversed;
 9402        }
 9403
 9404        select_next_state.done = true;
 9405        self.unfold_ranges(
 9406            &new_selections
 9407                .iter()
 9408                .map(|selection| selection.range())
 9409                .collect::<Vec<_>>(),
 9410            false,
 9411            false,
 9412            cx,
 9413        );
 9414        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9415            selections.select(new_selections)
 9416        });
 9417
 9418        Ok(())
 9419    }
 9420
 9421    pub fn select_next(
 9422        &mut self,
 9423        action: &SelectNext,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) -> Result<()> {
 9427        self.push_to_selection_history();
 9428        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9429        self.select_next_match_internal(
 9430            &display_map,
 9431            action.replace_newest,
 9432            Some(Autoscroll::newest()),
 9433            window,
 9434            cx,
 9435        )?;
 9436        Ok(())
 9437    }
 9438
 9439    pub fn select_previous(
 9440        &mut self,
 9441        action: &SelectPrevious,
 9442        window: &mut Window,
 9443        cx: &mut Context<Self>,
 9444    ) -> Result<()> {
 9445        self.push_to_selection_history();
 9446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9447        let buffer = &display_map.buffer_snapshot;
 9448        let mut selections = self.selections.all::<usize>(cx);
 9449        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9450            let query = &select_prev_state.query;
 9451            if !select_prev_state.done {
 9452                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9453                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9454                let mut next_selected_range = None;
 9455                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9456                let bytes_before_last_selection =
 9457                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9458                let bytes_after_first_selection =
 9459                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9460                let query_matches = query
 9461                    .stream_find_iter(bytes_before_last_selection)
 9462                    .map(|result| (last_selection.start, result))
 9463                    .chain(
 9464                        query
 9465                            .stream_find_iter(bytes_after_first_selection)
 9466                            .map(|result| (buffer.len(), result)),
 9467                    );
 9468                for (end_offset, query_match) in query_matches {
 9469                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9470                    let offset_range =
 9471                        end_offset - query_match.end()..end_offset - query_match.start();
 9472                    let display_range = offset_range.start.to_display_point(&display_map)
 9473                        ..offset_range.end.to_display_point(&display_map);
 9474
 9475                    if !select_prev_state.wordwise
 9476                        || (!movement::is_inside_word(&display_map, display_range.start)
 9477                            && !movement::is_inside_word(&display_map, display_range.end))
 9478                    {
 9479                        next_selected_range = Some(offset_range);
 9480                        break;
 9481                    }
 9482                }
 9483
 9484                if let Some(next_selected_range) = next_selected_range {
 9485                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9486                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9487                        if action.replace_newest {
 9488                            s.delete(s.newest_anchor().id);
 9489                        }
 9490                        s.insert_range(next_selected_range);
 9491                    });
 9492                } else {
 9493                    select_prev_state.done = true;
 9494                }
 9495            }
 9496
 9497            self.select_prev_state = Some(select_prev_state);
 9498        } else {
 9499            let mut only_carets = true;
 9500            let mut same_text_selected = true;
 9501            let mut selected_text = None;
 9502
 9503            let mut selections_iter = selections.iter().peekable();
 9504            while let Some(selection) = selections_iter.next() {
 9505                if selection.start != selection.end {
 9506                    only_carets = false;
 9507                }
 9508
 9509                if same_text_selected {
 9510                    if selected_text.is_none() {
 9511                        selected_text =
 9512                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9513                    }
 9514
 9515                    if let Some(next_selection) = selections_iter.peek() {
 9516                        if next_selection.range().len() == selection.range().len() {
 9517                            let next_selected_text = buffer
 9518                                .text_for_range(next_selection.range())
 9519                                .collect::<String>();
 9520                            if Some(next_selected_text) != selected_text {
 9521                                same_text_selected = false;
 9522                                selected_text = None;
 9523                            }
 9524                        } else {
 9525                            same_text_selected = false;
 9526                            selected_text = None;
 9527                        }
 9528                    }
 9529                }
 9530            }
 9531
 9532            if only_carets {
 9533                for selection in &mut selections {
 9534                    let word_range = movement::surrounding_word(
 9535                        &display_map,
 9536                        selection.start.to_display_point(&display_map),
 9537                    );
 9538                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9539                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9540                    selection.goal = SelectionGoal::None;
 9541                    selection.reversed = false;
 9542                }
 9543                if selections.len() == 1 {
 9544                    let selection = selections
 9545                        .last()
 9546                        .expect("ensured that there's only one selection");
 9547                    let query = buffer
 9548                        .text_for_range(selection.start..selection.end)
 9549                        .collect::<String>();
 9550                    let is_empty = query.is_empty();
 9551                    let select_state = SelectNextState {
 9552                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9553                        wordwise: true,
 9554                        done: is_empty,
 9555                    };
 9556                    self.select_prev_state = Some(select_state);
 9557                } else {
 9558                    self.select_prev_state = None;
 9559                }
 9560
 9561                self.unfold_ranges(
 9562                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9563                    false,
 9564                    true,
 9565                    cx,
 9566                );
 9567                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9568                    s.select(selections);
 9569                });
 9570            } else if let Some(selected_text) = selected_text {
 9571                self.select_prev_state = Some(SelectNextState {
 9572                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9573                    wordwise: false,
 9574                    done: false,
 9575                });
 9576                self.select_previous(action, window, cx)?;
 9577            }
 9578        }
 9579        Ok(())
 9580    }
 9581
 9582    pub fn toggle_comments(
 9583        &mut self,
 9584        action: &ToggleComments,
 9585        window: &mut Window,
 9586        cx: &mut Context<Self>,
 9587    ) {
 9588        if self.read_only(cx) {
 9589            return;
 9590        }
 9591        let text_layout_details = &self.text_layout_details(window);
 9592        self.transact(window, cx, |this, window, cx| {
 9593            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9594            let mut edits = Vec::new();
 9595            let mut selection_edit_ranges = Vec::new();
 9596            let mut last_toggled_row = None;
 9597            let snapshot = this.buffer.read(cx).read(cx);
 9598            let empty_str: Arc<str> = Arc::default();
 9599            let mut suffixes_inserted = Vec::new();
 9600            let ignore_indent = action.ignore_indent;
 9601
 9602            fn comment_prefix_range(
 9603                snapshot: &MultiBufferSnapshot,
 9604                row: MultiBufferRow,
 9605                comment_prefix: &str,
 9606                comment_prefix_whitespace: &str,
 9607                ignore_indent: bool,
 9608            ) -> Range<Point> {
 9609                let indent_size = if ignore_indent {
 9610                    0
 9611                } else {
 9612                    snapshot.indent_size_for_line(row).len
 9613                };
 9614
 9615                let start = Point::new(row.0, indent_size);
 9616
 9617                let mut line_bytes = snapshot
 9618                    .bytes_in_range(start..snapshot.max_point())
 9619                    .flatten()
 9620                    .copied();
 9621
 9622                // If this line currently begins with the line comment prefix, then record
 9623                // the range containing the prefix.
 9624                if line_bytes
 9625                    .by_ref()
 9626                    .take(comment_prefix.len())
 9627                    .eq(comment_prefix.bytes())
 9628                {
 9629                    // Include any whitespace that matches the comment prefix.
 9630                    let matching_whitespace_len = line_bytes
 9631                        .zip(comment_prefix_whitespace.bytes())
 9632                        .take_while(|(a, b)| a == b)
 9633                        .count() as u32;
 9634                    let end = Point::new(
 9635                        start.row,
 9636                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9637                    );
 9638                    start..end
 9639                } else {
 9640                    start..start
 9641                }
 9642            }
 9643
 9644            fn comment_suffix_range(
 9645                snapshot: &MultiBufferSnapshot,
 9646                row: MultiBufferRow,
 9647                comment_suffix: &str,
 9648                comment_suffix_has_leading_space: bool,
 9649            ) -> Range<Point> {
 9650                let end = Point::new(row.0, snapshot.line_len(row));
 9651                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9652
 9653                let mut line_end_bytes = snapshot
 9654                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9655                    .flatten()
 9656                    .copied();
 9657
 9658                let leading_space_len = if suffix_start_column > 0
 9659                    && line_end_bytes.next() == Some(b' ')
 9660                    && comment_suffix_has_leading_space
 9661                {
 9662                    1
 9663                } else {
 9664                    0
 9665                };
 9666
 9667                // If this line currently begins with the line comment prefix, then record
 9668                // the range containing the prefix.
 9669                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9670                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9671                    start..end
 9672                } else {
 9673                    end..end
 9674                }
 9675            }
 9676
 9677            // TODO: Handle selections that cross excerpts
 9678            for selection in &mut selections {
 9679                let start_column = snapshot
 9680                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9681                    .len;
 9682                let language = if let Some(language) =
 9683                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9684                {
 9685                    language
 9686                } else {
 9687                    continue;
 9688                };
 9689
 9690                selection_edit_ranges.clear();
 9691
 9692                // If multiple selections contain a given row, avoid processing that
 9693                // row more than once.
 9694                let mut start_row = MultiBufferRow(selection.start.row);
 9695                if last_toggled_row == Some(start_row) {
 9696                    start_row = start_row.next_row();
 9697                }
 9698                let end_row =
 9699                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9700                        MultiBufferRow(selection.end.row - 1)
 9701                    } else {
 9702                        MultiBufferRow(selection.end.row)
 9703                    };
 9704                last_toggled_row = Some(end_row);
 9705
 9706                if start_row > end_row {
 9707                    continue;
 9708                }
 9709
 9710                // If the language has line comments, toggle those.
 9711                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9712
 9713                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9714                if ignore_indent {
 9715                    full_comment_prefixes = full_comment_prefixes
 9716                        .into_iter()
 9717                        .map(|s| Arc::from(s.trim_end()))
 9718                        .collect();
 9719                }
 9720
 9721                if !full_comment_prefixes.is_empty() {
 9722                    let first_prefix = full_comment_prefixes
 9723                        .first()
 9724                        .expect("prefixes is non-empty");
 9725                    let prefix_trimmed_lengths = full_comment_prefixes
 9726                        .iter()
 9727                        .map(|p| p.trim_end_matches(' ').len())
 9728                        .collect::<SmallVec<[usize; 4]>>();
 9729
 9730                    let mut all_selection_lines_are_comments = true;
 9731
 9732                    for row in start_row.0..=end_row.0 {
 9733                        let row = MultiBufferRow(row);
 9734                        if start_row < end_row && snapshot.is_line_blank(row) {
 9735                            continue;
 9736                        }
 9737
 9738                        let prefix_range = full_comment_prefixes
 9739                            .iter()
 9740                            .zip(prefix_trimmed_lengths.iter().copied())
 9741                            .map(|(prefix, trimmed_prefix_len)| {
 9742                                comment_prefix_range(
 9743                                    snapshot.deref(),
 9744                                    row,
 9745                                    &prefix[..trimmed_prefix_len],
 9746                                    &prefix[trimmed_prefix_len..],
 9747                                    ignore_indent,
 9748                                )
 9749                            })
 9750                            .max_by_key(|range| range.end.column - range.start.column)
 9751                            .expect("prefixes is non-empty");
 9752
 9753                        if prefix_range.is_empty() {
 9754                            all_selection_lines_are_comments = false;
 9755                        }
 9756
 9757                        selection_edit_ranges.push(prefix_range);
 9758                    }
 9759
 9760                    if all_selection_lines_are_comments {
 9761                        edits.extend(
 9762                            selection_edit_ranges
 9763                                .iter()
 9764                                .cloned()
 9765                                .map(|range| (range, empty_str.clone())),
 9766                        );
 9767                    } else {
 9768                        let min_column = selection_edit_ranges
 9769                            .iter()
 9770                            .map(|range| range.start.column)
 9771                            .min()
 9772                            .unwrap_or(0);
 9773                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9774                            let position = Point::new(range.start.row, min_column);
 9775                            (position..position, first_prefix.clone())
 9776                        }));
 9777                    }
 9778                } else if let Some((full_comment_prefix, comment_suffix)) =
 9779                    language.block_comment_delimiters()
 9780                {
 9781                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9782                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9783                    let prefix_range = comment_prefix_range(
 9784                        snapshot.deref(),
 9785                        start_row,
 9786                        comment_prefix,
 9787                        comment_prefix_whitespace,
 9788                        ignore_indent,
 9789                    );
 9790                    let suffix_range = comment_suffix_range(
 9791                        snapshot.deref(),
 9792                        end_row,
 9793                        comment_suffix.trim_start_matches(' '),
 9794                        comment_suffix.starts_with(' '),
 9795                    );
 9796
 9797                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9798                        edits.push((
 9799                            prefix_range.start..prefix_range.start,
 9800                            full_comment_prefix.clone(),
 9801                        ));
 9802                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9803                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9804                    } else {
 9805                        edits.push((prefix_range, empty_str.clone()));
 9806                        edits.push((suffix_range, empty_str.clone()));
 9807                    }
 9808                } else {
 9809                    continue;
 9810                }
 9811            }
 9812
 9813            drop(snapshot);
 9814            this.buffer.update(cx, |buffer, cx| {
 9815                buffer.edit(edits, None, cx);
 9816            });
 9817
 9818            // Adjust selections so that they end before any comment suffixes that
 9819            // were inserted.
 9820            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9821            let mut selections = this.selections.all::<Point>(cx);
 9822            let snapshot = this.buffer.read(cx).read(cx);
 9823            for selection in &mut selections {
 9824                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9825                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9826                        Ordering::Less => {
 9827                            suffixes_inserted.next();
 9828                            continue;
 9829                        }
 9830                        Ordering::Greater => break,
 9831                        Ordering::Equal => {
 9832                            if selection.end.column == snapshot.line_len(row) {
 9833                                if selection.is_empty() {
 9834                                    selection.start.column -= suffix_len as u32;
 9835                                }
 9836                                selection.end.column -= suffix_len as u32;
 9837                            }
 9838                            break;
 9839                        }
 9840                    }
 9841                }
 9842            }
 9843
 9844            drop(snapshot);
 9845            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9846                s.select(selections)
 9847            });
 9848
 9849            let selections = this.selections.all::<Point>(cx);
 9850            let selections_on_single_row = selections.windows(2).all(|selections| {
 9851                selections[0].start.row == selections[1].start.row
 9852                    && selections[0].end.row == selections[1].end.row
 9853                    && selections[0].start.row == selections[0].end.row
 9854            });
 9855            let selections_selecting = selections
 9856                .iter()
 9857                .any(|selection| selection.start != selection.end);
 9858            let advance_downwards = action.advance_downwards
 9859                && selections_on_single_row
 9860                && !selections_selecting
 9861                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9862
 9863            if advance_downwards {
 9864                let snapshot = this.buffer.read(cx).snapshot(cx);
 9865
 9866                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9867                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9868                        let mut point = display_point.to_point(display_snapshot);
 9869                        point.row += 1;
 9870                        point = snapshot.clip_point(point, Bias::Left);
 9871                        let display_point = point.to_display_point(display_snapshot);
 9872                        let goal = SelectionGoal::HorizontalPosition(
 9873                            display_snapshot
 9874                                .x_for_display_point(display_point, text_layout_details)
 9875                                .into(),
 9876                        );
 9877                        (display_point, goal)
 9878                    })
 9879                });
 9880            }
 9881        });
 9882    }
 9883
 9884    pub fn select_enclosing_symbol(
 9885        &mut self,
 9886        _: &SelectEnclosingSymbol,
 9887        window: &mut Window,
 9888        cx: &mut Context<Self>,
 9889    ) {
 9890        let buffer = self.buffer.read(cx).snapshot(cx);
 9891        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9892
 9893        fn update_selection(
 9894            selection: &Selection<usize>,
 9895            buffer_snap: &MultiBufferSnapshot,
 9896        ) -> Option<Selection<usize>> {
 9897            let cursor = selection.head();
 9898            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9899            for symbol in symbols.iter().rev() {
 9900                let start = symbol.range.start.to_offset(buffer_snap);
 9901                let end = symbol.range.end.to_offset(buffer_snap);
 9902                let new_range = start..end;
 9903                if start < selection.start || end > selection.end {
 9904                    return Some(Selection {
 9905                        id: selection.id,
 9906                        start: new_range.start,
 9907                        end: new_range.end,
 9908                        goal: SelectionGoal::None,
 9909                        reversed: selection.reversed,
 9910                    });
 9911                }
 9912            }
 9913            None
 9914        }
 9915
 9916        let mut selected_larger_symbol = false;
 9917        let new_selections = old_selections
 9918            .iter()
 9919            .map(|selection| match update_selection(selection, &buffer) {
 9920                Some(new_selection) => {
 9921                    if new_selection.range() != selection.range() {
 9922                        selected_larger_symbol = true;
 9923                    }
 9924                    new_selection
 9925                }
 9926                None => selection.clone(),
 9927            })
 9928            .collect::<Vec<_>>();
 9929
 9930        if selected_larger_symbol {
 9931            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9932                s.select(new_selections);
 9933            });
 9934        }
 9935    }
 9936
 9937    pub fn select_larger_syntax_node(
 9938        &mut self,
 9939        _: &SelectLargerSyntaxNode,
 9940        window: &mut Window,
 9941        cx: &mut Context<Self>,
 9942    ) {
 9943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9944        let buffer = self.buffer.read(cx).snapshot(cx);
 9945        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9946
 9947        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9948        let mut selected_larger_node = false;
 9949        let new_selections = old_selections
 9950            .iter()
 9951            .map(|selection| {
 9952                let old_range = selection.start..selection.end;
 9953                let mut new_range = old_range.clone();
 9954                let mut new_node = None;
 9955                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9956                {
 9957                    new_node = Some(node);
 9958                    new_range = containing_range;
 9959                    if !display_map.intersects_fold(new_range.start)
 9960                        && !display_map.intersects_fold(new_range.end)
 9961                    {
 9962                        break;
 9963                    }
 9964                }
 9965
 9966                if let Some(node) = new_node {
 9967                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9968                    // nodes. Parent and grandparent are also logged because this operation will not
 9969                    // visit nodes that have the same range as their parent.
 9970                    log::info!("Node: {node:?}");
 9971                    let parent = node.parent();
 9972                    log::info!("Parent: {parent:?}");
 9973                    let grandparent = parent.and_then(|x| x.parent());
 9974                    log::info!("Grandparent: {grandparent:?}");
 9975                }
 9976
 9977                selected_larger_node |= new_range != old_range;
 9978                Selection {
 9979                    id: selection.id,
 9980                    start: new_range.start,
 9981                    end: new_range.end,
 9982                    goal: SelectionGoal::None,
 9983                    reversed: selection.reversed,
 9984                }
 9985            })
 9986            .collect::<Vec<_>>();
 9987
 9988        if selected_larger_node {
 9989            stack.push(old_selections);
 9990            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9991                s.select(new_selections);
 9992            });
 9993        }
 9994        self.select_larger_syntax_node_stack = stack;
 9995    }
 9996
 9997    pub fn select_smaller_syntax_node(
 9998        &mut self,
 9999        _: &SelectSmallerSyntaxNode,
10000        window: &mut Window,
10001        cx: &mut Context<Self>,
10002    ) {
10003        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10004        if let Some(selections) = stack.pop() {
10005            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10006                s.select(selections.to_vec());
10007            });
10008        }
10009        self.select_larger_syntax_node_stack = stack;
10010    }
10011
10012    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10013        if !EditorSettings::get_global(cx).gutter.runnables {
10014            self.clear_tasks();
10015            return Task::ready(());
10016        }
10017        let project = self.project.as_ref().map(Entity::downgrade);
10018        cx.spawn_in(window, |this, mut cx| async move {
10019            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10020            let Some(project) = project.and_then(|p| p.upgrade()) else {
10021                return;
10022            };
10023            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10024                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10025            }) else {
10026                return;
10027            };
10028
10029            let hide_runnables = project
10030                .update(&mut cx, |project, cx| {
10031                    // Do not display any test indicators in non-dev server remote projects.
10032                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10033                })
10034                .unwrap_or(true);
10035            if hide_runnables {
10036                return;
10037            }
10038            let new_rows =
10039                cx.background_executor()
10040                    .spawn({
10041                        let snapshot = display_snapshot.clone();
10042                        async move {
10043                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10044                        }
10045                    })
10046                    .await;
10047
10048            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10049            this.update(&mut cx, |this, _| {
10050                this.clear_tasks();
10051                for (key, value) in rows {
10052                    this.insert_tasks(key, value);
10053                }
10054            })
10055            .ok();
10056        })
10057    }
10058    fn fetch_runnable_ranges(
10059        snapshot: &DisplaySnapshot,
10060        range: Range<Anchor>,
10061    ) -> Vec<language::RunnableRange> {
10062        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10063    }
10064
10065    fn runnable_rows(
10066        project: Entity<Project>,
10067        snapshot: DisplaySnapshot,
10068        runnable_ranges: Vec<RunnableRange>,
10069        mut cx: AsyncWindowContext,
10070    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10071        runnable_ranges
10072            .into_iter()
10073            .filter_map(|mut runnable| {
10074                let tasks = cx
10075                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10076                    .ok()?;
10077                if tasks.is_empty() {
10078                    return None;
10079                }
10080
10081                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10082
10083                let row = snapshot
10084                    .buffer_snapshot
10085                    .buffer_line_for_row(MultiBufferRow(point.row))?
10086                    .1
10087                    .start
10088                    .row;
10089
10090                let context_range =
10091                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10092                Some((
10093                    (runnable.buffer_id, row),
10094                    RunnableTasks {
10095                        templates: tasks,
10096                        offset: MultiBufferOffset(runnable.run_range.start),
10097                        context_range,
10098                        column: point.column,
10099                        extra_variables: runnable.extra_captures,
10100                    },
10101                ))
10102            })
10103            .collect()
10104    }
10105
10106    fn templates_with_tags(
10107        project: &Entity<Project>,
10108        runnable: &mut Runnable,
10109        cx: &mut App,
10110    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10111        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10112            let (worktree_id, file) = project
10113                .buffer_for_id(runnable.buffer, cx)
10114                .and_then(|buffer| buffer.read(cx).file())
10115                .map(|file| (file.worktree_id(cx), file.clone()))
10116                .unzip();
10117
10118            (
10119                project.task_store().read(cx).task_inventory().cloned(),
10120                worktree_id,
10121                file,
10122            )
10123        });
10124
10125        let tags = mem::take(&mut runnable.tags);
10126        let mut tags: Vec<_> = tags
10127            .into_iter()
10128            .flat_map(|tag| {
10129                let tag = tag.0.clone();
10130                inventory
10131                    .as_ref()
10132                    .into_iter()
10133                    .flat_map(|inventory| {
10134                        inventory.read(cx).list_tasks(
10135                            file.clone(),
10136                            Some(runnable.language.clone()),
10137                            worktree_id,
10138                            cx,
10139                        )
10140                    })
10141                    .filter(move |(_, template)| {
10142                        template.tags.iter().any(|source_tag| source_tag == &tag)
10143                    })
10144            })
10145            .sorted_by_key(|(kind, _)| kind.to_owned())
10146            .collect();
10147        if let Some((leading_tag_source, _)) = tags.first() {
10148            // Strongest source wins; if we have worktree tag binding, prefer that to
10149            // global and language bindings;
10150            // if we have a global binding, prefer that to language binding.
10151            let first_mismatch = tags
10152                .iter()
10153                .position(|(tag_source, _)| tag_source != leading_tag_source);
10154            if let Some(index) = first_mismatch {
10155                tags.truncate(index);
10156            }
10157        }
10158
10159        tags
10160    }
10161
10162    pub fn move_to_enclosing_bracket(
10163        &mut self,
10164        _: &MoveToEnclosingBracket,
10165        window: &mut Window,
10166        cx: &mut Context<Self>,
10167    ) {
10168        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10169            s.move_offsets_with(|snapshot, selection| {
10170                let Some(enclosing_bracket_ranges) =
10171                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10172                else {
10173                    return;
10174                };
10175
10176                let mut best_length = usize::MAX;
10177                let mut best_inside = false;
10178                let mut best_in_bracket_range = false;
10179                let mut best_destination = None;
10180                for (open, close) in enclosing_bracket_ranges {
10181                    let close = close.to_inclusive();
10182                    let length = close.end() - open.start;
10183                    let inside = selection.start >= open.end && selection.end <= *close.start();
10184                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10185                        || close.contains(&selection.head());
10186
10187                    // If best is next to a bracket and current isn't, skip
10188                    if !in_bracket_range && best_in_bracket_range {
10189                        continue;
10190                    }
10191
10192                    // Prefer smaller lengths unless best is inside and current isn't
10193                    if length > best_length && (best_inside || !inside) {
10194                        continue;
10195                    }
10196
10197                    best_length = length;
10198                    best_inside = inside;
10199                    best_in_bracket_range = in_bracket_range;
10200                    best_destination = Some(
10201                        if close.contains(&selection.start) && close.contains(&selection.end) {
10202                            if inside {
10203                                open.end
10204                            } else {
10205                                open.start
10206                            }
10207                        } else if inside {
10208                            *close.start()
10209                        } else {
10210                            *close.end()
10211                        },
10212                    );
10213                }
10214
10215                if let Some(destination) = best_destination {
10216                    selection.collapse_to(destination, SelectionGoal::None);
10217                }
10218            })
10219        });
10220    }
10221
10222    pub fn undo_selection(
10223        &mut self,
10224        _: &UndoSelection,
10225        window: &mut Window,
10226        cx: &mut Context<Self>,
10227    ) {
10228        self.end_selection(window, cx);
10229        self.selection_history.mode = SelectionHistoryMode::Undoing;
10230        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10231            self.change_selections(None, window, cx, |s| {
10232                s.select_anchors(entry.selections.to_vec())
10233            });
10234            self.select_next_state = entry.select_next_state;
10235            self.select_prev_state = entry.select_prev_state;
10236            self.add_selections_state = entry.add_selections_state;
10237            self.request_autoscroll(Autoscroll::newest(), cx);
10238        }
10239        self.selection_history.mode = SelectionHistoryMode::Normal;
10240    }
10241
10242    pub fn redo_selection(
10243        &mut self,
10244        _: &RedoSelection,
10245        window: &mut Window,
10246        cx: &mut Context<Self>,
10247    ) {
10248        self.end_selection(window, cx);
10249        self.selection_history.mode = SelectionHistoryMode::Redoing;
10250        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10251            self.change_selections(None, window, cx, |s| {
10252                s.select_anchors(entry.selections.to_vec())
10253            });
10254            self.select_next_state = entry.select_next_state;
10255            self.select_prev_state = entry.select_prev_state;
10256            self.add_selections_state = entry.add_selections_state;
10257            self.request_autoscroll(Autoscroll::newest(), cx);
10258        }
10259        self.selection_history.mode = SelectionHistoryMode::Normal;
10260    }
10261
10262    pub fn expand_excerpts(
10263        &mut self,
10264        action: &ExpandExcerpts,
10265        _: &mut Window,
10266        cx: &mut Context<Self>,
10267    ) {
10268        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10269    }
10270
10271    pub fn expand_excerpts_down(
10272        &mut self,
10273        action: &ExpandExcerptsDown,
10274        _: &mut Window,
10275        cx: &mut Context<Self>,
10276    ) {
10277        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10278    }
10279
10280    pub fn expand_excerpts_up(
10281        &mut self,
10282        action: &ExpandExcerptsUp,
10283        _: &mut Window,
10284        cx: &mut Context<Self>,
10285    ) {
10286        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10287    }
10288
10289    pub fn expand_excerpts_for_direction(
10290        &mut self,
10291        lines: u32,
10292        direction: ExpandExcerptDirection,
10293
10294        cx: &mut Context<Self>,
10295    ) {
10296        let selections = self.selections.disjoint_anchors();
10297
10298        let lines = if lines == 0 {
10299            EditorSettings::get_global(cx).expand_excerpt_lines
10300        } else {
10301            lines
10302        };
10303
10304        self.buffer.update(cx, |buffer, cx| {
10305            let snapshot = buffer.snapshot(cx);
10306            let mut excerpt_ids = selections
10307                .iter()
10308                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10309                .collect::<Vec<_>>();
10310            excerpt_ids.sort();
10311            excerpt_ids.dedup();
10312            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10313        })
10314    }
10315
10316    pub fn expand_excerpt(
10317        &mut self,
10318        excerpt: ExcerptId,
10319        direction: ExpandExcerptDirection,
10320        cx: &mut Context<Self>,
10321    ) {
10322        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10323        self.buffer.update(cx, |buffer, cx| {
10324            buffer.expand_excerpts([excerpt], lines, direction, cx)
10325        })
10326    }
10327
10328    pub fn go_to_singleton_buffer_point(
10329        &mut self,
10330        point: Point,
10331        window: &mut Window,
10332        cx: &mut Context<Self>,
10333    ) {
10334        self.go_to_singleton_buffer_range(point..point, window, cx);
10335    }
10336
10337    pub fn go_to_singleton_buffer_range(
10338        &mut self,
10339        range: Range<Point>,
10340        window: &mut Window,
10341        cx: &mut Context<Self>,
10342    ) {
10343        let multibuffer = self.buffer().read(cx);
10344        let Some(buffer) = multibuffer.as_singleton() else {
10345            return;
10346        };
10347        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10348            return;
10349        };
10350        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10351            return;
10352        };
10353        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10354            s.select_anchor_ranges([start..end])
10355        });
10356    }
10357
10358    fn go_to_diagnostic(
10359        &mut self,
10360        _: &GoToDiagnostic,
10361        window: &mut Window,
10362        cx: &mut Context<Self>,
10363    ) {
10364        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10365    }
10366
10367    fn go_to_prev_diagnostic(
10368        &mut self,
10369        _: &GoToPrevDiagnostic,
10370        window: &mut Window,
10371        cx: &mut Context<Self>,
10372    ) {
10373        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10374    }
10375
10376    pub fn go_to_diagnostic_impl(
10377        &mut self,
10378        direction: Direction,
10379        window: &mut Window,
10380        cx: &mut Context<Self>,
10381    ) {
10382        let buffer = self.buffer.read(cx).snapshot(cx);
10383        let selection = self.selections.newest::<usize>(cx);
10384
10385        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10386        if direction == Direction::Next {
10387            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10388                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10389                    return;
10390                };
10391                self.activate_diagnostics(
10392                    buffer_id,
10393                    popover.local_diagnostic.diagnostic.group_id,
10394                    window,
10395                    cx,
10396                );
10397                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10398                    let primary_range_start = active_diagnostics.primary_range.start;
10399                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10400                        let mut new_selection = s.newest_anchor().clone();
10401                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10402                        s.select_anchors(vec![new_selection.clone()]);
10403                    });
10404                    self.refresh_inline_completion(false, true, window, cx);
10405                }
10406                return;
10407            }
10408        }
10409
10410        let active_group_id = self
10411            .active_diagnostics
10412            .as_ref()
10413            .map(|active_group| active_group.group_id);
10414        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10415            active_diagnostics
10416                .primary_range
10417                .to_offset(&buffer)
10418                .to_inclusive()
10419        });
10420        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10421            if active_primary_range.contains(&selection.head()) {
10422                *active_primary_range.start()
10423            } else {
10424                selection.head()
10425            }
10426        } else {
10427            selection.head()
10428        };
10429
10430        let snapshot = self.snapshot(window, cx);
10431        let primary_diagnostics_before = buffer
10432            .diagnostics_in_range::<usize>(0..search_start)
10433            .filter(|entry| entry.diagnostic.is_primary)
10434            .filter(|entry| entry.range.start != entry.range.end)
10435            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10436            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10437            .collect::<Vec<_>>();
10438        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10439            primary_diagnostics_before
10440                .iter()
10441                .position(|entry| entry.diagnostic.group_id == active_group_id)
10442        });
10443
10444        let primary_diagnostics_after = buffer
10445            .diagnostics_in_range::<usize>(search_start..buffer.len())
10446            .filter(|entry| entry.diagnostic.is_primary)
10447            .filter(|entry| entry.range.start != entry.range.end)
10448            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10449            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10450            .collect::<Vec<_>>();
10451        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10452            primary_diagnostics_after
10453                .iter()
10454                .enumerate()
10455                .rev()
10456                .find_map(|(i, entry)| {
10457                    if entry.diagnostic.group_id == active_group_id {
10458                        Some(i)
10459                    } else {
10460                        None
10461                    }
10462                })
10463        });
10464
10465        let next_primary_diagnostic = match direction {
10466            Direction::Prev => primary_diagnostics_before
10467                .iter()
10468                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10469                .rev()
10470                .next(),
10471            Direction::Next => primary_diagnostics_after
10472                .iter()
10473                .skip(
10474                    last_same_group_diagnostic_after
10475                        .map(|index| index + 1)
10476                        .unwrap_or(0),
10477                )
10478                .next(),
10479        };
10480
10481        // Cycle around to the start of the buffer, potentially moving back to the start of
10482        // the currently active diagnostic.
10483        let cycle_around = || match direction {
10484            Direction::Prev => primary_diagnostics_after
10485                .iter()
10486                .rev()
10487                .chain(primary_diagnostics_before.iter().rev())
10488                .next(),
10489            Direction::Next => primary_diagnostics_before
10490                .iter()
10491                .chain(primary_diagnostics_after.iter())
10492                .next(),
10493        };
10494
10495        if let Some((primary_range, group_id)) = next_primary_diagnostic
10496            .or_else(cycle_around)
10497            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10498        {
10499            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10500                return;
10501            };
10502            self.activate_diagnostics(buffer_id, group_id, window, cx);
10503            if self.active_diagnostics.is_some() {
10504                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10505                    s.select(vec![Selection {
10506                        id: selection.id,
10507                        start: primary_range.start,
10508                        end: primary_range.start,
10509                        reversed: false,
10510                        goal: SelectionGoal::None,
10511                    }]);
10512                });
10513                self.refresh_inline_completion(false, true, window, cx);
10514            }
10515        }
10516    }
10517
10518    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10519        let snapshot = self.snapshot(window, cx);
10520        let selection = self.selections.newest::<Point>(cx);
10521        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10522    }
10523
10524    fn go_to_hunk_after_position(
10525        &mut self,
10526        snapshot: &EditorSnapshot,
10527        position: Point,
10528        window: &mut Window,
10529        cx: &mut Context<Editor>,
10530    ) -> Option<MultiBufferDiffHunk> {
10531        let mut hunk = snapshot
10532            .buffer_snapshot
10533            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10534            .find(|hunk| hunk.row_range.start.0 > position.row);
10535        if hunk.is_none() {
10536            hunk = snapshot
10537                .buffer_snapshot
10538                .diff_hunks_in_range(Point::zero()..position)
10539                .find(|hunk| hunk.row_range.end.0 < position.row)
10540        }
10541        if let Some(hunk) = &hunk {
10542            let destination = Point::new(hunk.row_range.start.0, 0);
10543            self.unfold_ranges(&[destination..destination], false, false, cx);
10544            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10545                s.select_ranges(vec![destination..destination]);
10546            });
10547        }
10548
10549        hunk
10550    }
10551
10552    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10553        let snapshot = self.snapshot(window, cx);
10554        let selection = self.selections.newest::<Point>(cx);
10555        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10556    }
10557
10558    fn go_to_hunk_before_position(
10559        &mut self,
10560        snapshot: &EditorSnapshot,
10561        position: Point,
10562        window: &mut Window,
10563        cx: &mut Context<Editor>,
10564    ) -> Option<MultiBufferDiffHunk> {
10565        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10566        if hunk.is_none() {
10567            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10568        }
10569        if let Some(hunk) = &hunk {
10570            let destination = Point::new(hunk.row_range.start.0, 0);
10571            self.unfold_ranges(&[destination..destination], false, false, cx);
10572            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10573                s.select_ranges(vec![destination..destination]);
10574            });
10575        }
10576
10577        hunk
10578    }
10579
10580    pub fn go_to_definition(
10581        &mut self,
10582        _: &GoToDefinition,
10583        window: &mut Window,
10584        cx: &mut Context<Self>,
10585    ) -> Task<Result<Navigated>> {
10586        let definition =
10587            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10588        cx.spawn_in(window, |editor, mut cx| async move {
10589            if definition.await? == Navigated::Yes {
10590                return Ok(Navigated::Yes);
10591            }
10592            match editor.update_in(&mut cx, |editor, window, cx| {
10593                editor.find_all_references(&FindAllReferences, window, cx)
10594            })? {
10595                Some(references) => references.await,
10596                None => Ok(Navigated::No),
10597            }
10598        })
10599    }
10600
10601    pub fn go_to_declaration(
10602        &mut self,
10603        _: &GoToDeclaration,
10604        window: &mut Window,
10605        cx: &mut Context<Self>,
10606    ) -> Task<Result<Navigated>> {
10607        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10608    }
10609
10610    pub fn go_to_declaration_split(
10611        &mut self,
10612        _: &GoToDeclaration,
10613        window: &mut Window,
10614        cx: &mut Context<Self>,
10615    ) -> Task<Result<Navigated>> {
10616        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10617    }
10618
10619    pub fn go_to_implementation(
10620        &mut self,
10621        _: &GoToImplementation,
10622        window: &mut Window,
10623        cx: &mut Context<Self>,
10624    ) -> Task<Result<Navigated>> {
10625        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10626    }
10627
10628    pub fn go_to_implementation_split(
10629        &mut self,
10630        _: &GoToImplementationSplit,
10631        window: &mut Window,
10632        cx: &mut Context<Self>,
10633    ) -> Task<Result<Navigated>> {
10634        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10635    }
10636
10637    pub fn go_to_type_definition(
10638        &mut self,
10639        _: &GoToTypeDefinition,
10640        window: &mut Window,
10641        cx: &mut Context<Self>,
10642    ) -> Task<Result<Navigated>> {
10643        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10644    }
10645
10646    pub fn go_to_definition_split(
10647        &mut self,
10648        _: &GoToDefinitionSplit,
10649        window: &mut Window,
10650        cx: &mut Context<Self>,
10651    ) -> Task<Result<Navigated>> {
10652        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10653    }
10654
10655    pub fn go_to_type_definition_split(
10656        &mut self,
10657        _: &GoToTypeDefinitionSplit,
10658        window: &mut Window,
10659        cx: &mut Context<Self>,
10660    ) -> Task<Result<Navigated>> {
10661        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10662    }
10663
10664    fn go_to_definition_of_kind(
10665        &mut self,
10666        kind: GotoDefinitionKind,
10667        split: bool,
10668        window: &mut Window,
10669        cx: &mut Context<Self>,
10670    ) -> Task<Result<Navigated>> {
10671        let Some(provider) = self.semantics_provider.clone() else {
10672            return Task::ready(Ok(Navigated::No));
10673        };
10674        let head = self.selections.newest::<usize>(cx).head();
10675        let buffer = self.buffer.read(cx);
10676        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10677            text_anchor
10678        } else {
10679            return Task::ready(Ok(Navigated::No));
10680        };
10681
10682        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10683            return Task::ready(Ok(Navigated::No));
10684        };
10685
10686        cx.spawn_in(window, |editor, mut cx| async move {
10687            let definitions = definitions.await?;
10688            let navigated = editor
10689                .update_in(&mut cx, |editor, window, cx| {
10690                    editor.navigate_to_hover_links(
10691                        Some(kind),
10692                        definitions
10693                            .into_iter()
10694                            .filter(|location| {
10695                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10696                            })
10697                            .map(HoverLink::Text)
10698                            .collect::<Vec<_>>(),
10699                        split,
10700                        window,
10701                        cx,
10702                    )
10703                })?
10704                .await?;
10705            anyhow::Ok(navigated)
10706        })
10707    }
10708
10709    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10710        let selection = self.selections.newest_anchor();
10711        let head = selection.head();
10712        let tail = selection.tail();
10713
10714        let Some((buffer, start_position)) =
10715            self.buffer.read(cx).text_anchor_for_position(head, cx)
10716        else {
10717            return;
10718        };
10719
10720        let end_position = if head != tail {
10721            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10722                return;
10723            };
10724            Some(pos)
10725        } else {
10726            None
10727        };
10728
10729        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10730            let url = if let Some(end_pos) = end_position {
10731                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10732            } else {
10733                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10734            };
10735
10736            if let Some(url) = url {
10737                editor.update(&mut cx, |_, cx| {
10738                    cx.open_url(&url);
10739                })
10740            } else {
10741                Ok(())
10742            }
10743        });
10744
10745        url_finder.detach();
10746    }
10747
10748    pub fn open_selected_filename(
10749        &mut self,
10750        _: &OpenSelectedFilename,
10751        window: &mut Window,
10752        cx: &mut Context<Self>,
10753    ) {
10754        let Some(workspace) = self.workspace() else {
10755            return;
10756        };
10757
10758        let position = self.selections.newest_anchor().head();
10759
10760        let Some((buffer, buffer_position)) =
10761            self.buffer.read(cx).text_anchor_for_position(position, cx)
10762        else {
10763            return;
10764        };
10765
10766        let project = self.project.clone();
10767
10768        cx.spawn_in(window, |_, mut cx| async move {
10769            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10770
10771            if let Some((_, path)) = result {
10772                workspace
10773                    .update_in(&mut cx, |workspace, window, cx| {
10774                        workspace.open_resolved_path(path, window, cx)
10775                    })?
10776                    .await?;
10777            }
10778            anyhow::Ok(())
10779        })
10780        .detach();
10781    }
10782
10783    pub(crate) fn navigate_to_hover_links(
10784        &mut self,
10785        kind: Option<GotoDefinitionKind>,
10786        mut definitions: Vec<HoverLink>,
10787        split: bool,
10788        window: &mut Window,
10789        cx: &mut Context<Editor>,
10790    ) -> Task<Result<Navigated>> {
10791        // If there is one definition, just open it directly
10792        if definitions.len() == 1 {
10793            let definition = definitions.pop().unwrap();
10794
10795            enum TargetTaskResult {
10796                Location(Option<Location>),
10797                AlreadyNavigated,
10798            }
10799
10800            let target_task = match definition {
10801                HoverLink::Text(link) => {
10802                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10803                }
10804                HoverLink::InlayHint(lsp_location, server_id) => {
10805                    let computation =
10806                        self.compute_target_location(lsp_location, server_id, window, cx);
10807                    cx.background_executor().spawn(async move {
10808                        let location = computation.await?;
10809                        Ok(TargetTaskResult::Location(location))
10810                    })
10811                }
10812                HoverLink::Url(url) => {
10813                    cx.open_url(&url);
10814                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10815                }
10816                HoverLink::File(path) => {
10817                    if let Some(workspace) = self.workspace() {
10818                        cx.spawn_in(window, |_, mut cx| async move {
10819                            workspace
10820                                .update_in(&mut cx, |workspace, window, cx| {
10821                                    workspace.open_resolved_path(path, window, cx)
10822                                })?
10823                                .await
10824                                .map(|_| TargetTaskResult::AlreadyNavigated)
10825                        })
10826                    } else {
10827                        Task::ready(Ok(TargetTaskResult::Location(None)))
10828                    }
10829                }
10830            };
10831            cx.spawn_in(window, |editor, mut cx| async move {
10832                let target = match target_task.await.context("target resolution task")? {
10833                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10834                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10835                    TargetTaskResult::Location(Some(target)) => target,
10836                };
10837
10838                editor.update_in(&mut cx, |editor, window, cx| {
10839                    let Some(workspace) = editor.workspace() else {
10840                        return Navigated::No;
10841                    };
10842                    let pane = workspace.read(cx).active_pane().clone();
10843
10844                    let range = target.range.to_point(target.buffer.read(cx));
10845                    let range = editor.range_for_match(&range);
10846                    let range = collapse_multiline_range(range);
10847
10848                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10849                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10850                    } else {
10851                        window.defer(cx, move |window, cx| {
10852                            let target_editor: Entity<Self> =
10853                                workspace.update(cx, |workspace, cx| {
10854                                    let pane = if split {
10855                                        workspace.adjacent_pane(window, cx)
10856                                    } else {
10857                                        workspace.active_pane().clone()
10858                                    };
10859
10860                                    workspace.open_project_item(
10861                                        pane,
10862                                        target.buffer.clone(),
10863                                        true,
10864                                        true,
10865                                        window,
10866                                        cx,
10867                                    )
10868                                });
10869                            target_editor.update(cx, |target_editor, cx| {
10870                                // When selecting a definition in a different buffer, disable the nav history
10871                                // to avoid creating a history entry at the previous cursor location.
10872                                pane.update(cx, |pane, _| pane.disable_history());
10873                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10874                                pane.update(cx, |pane, _| pane.enable_history());
10875                            });
10876                        });
10877                    }
10878                    Navigated::Yes
10879                })
10880            })
10881        } else if !definitions.is_empty() {
10882            cx.spawn_in(window, |editor, mut cx| async move {
10883                let (title, location_tasks, workspace) = editor
10884                    .update_in(&mut cx, |editor, window, cx| {
10885                        let tab_kind = match kind {
10886                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10887                            _ => "Definitions",
10888                        };
10889                        let title = definitions
10890                            .iter()
10891                            .find_map(|definition| match definition {
10892                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10893                                    let buffer = origin.buffer.read(cx);
10894                                    format!(
10895                                        "{} for {}",
10896                                        tab_kind,
10897                                        buffer
10898                                            .text_for_range(origin.range.clone())
10899                                            .collect::<String>()
10900                                    )
10901                                }),
10902                                HoverLink::InlayHint(_, _) => None,
10903                                HoverLink::Url(_) => None,
10904                                HoverLink::File(_) => None,
10905                            })
10906                            .unwrap_or(tab_kind.to_string());
10907                        let location_tasks = definitions
10908                            .into_iter()
10909                            .map(|definition| match definition {
10910                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10911                                HoverLink::InlayHint(lsp_location, server_id) => editor
10912                                    .compute_target_location(lsp_location, server_id, window, cx),
10913                                HoverLink::Url(_) => Task::ready(Ok(None)),
10914                                HoverLink::File(_) => Task::ready(Ok(None)),
10915                            })
10916                            .collect::<Vec<_>>();
10917                        (title, location_tasks, editor.workspace().clone())
10918                    })
10919                    .context("location tasks preparation")?;
10920
10921                let locations = future::join_all(location_tasks)
10922                    .await
10923                    .into_iter()
10924                    .filter_map(|location| location.transpose())
10925                    .collect::<Result<_>>()
10926                    .context("location tasks")?;
10927
10928                let Some(workspace) = workspace else {
10929                    return Ok(Navigated::No);
10930                };
10931                let opened = workspace
10932                    .update_in(&mut cx, |workspace, window, cx| {
10933                        Self::open_locations_in_multibuffer(
10934                            workspace,
10935                            locations,
10936                            title,
10937                            split,
10938                            MultibufferSelectionMode::First,
10939                            window,
10940                            cx,
10941                        )
10942                    })
10943                    .ok();
10944
10945                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10946            })
10947        } else {
10948            Task::ready(Ok(Navigated::No))
10949        }
10950    }
10951
10952    fn compute_target_location(
10953        &self,
10954        lsp_location: lsp::Location,
10955        server_id: LanguageServerId,
10956        window: &mut Window,
10957        cx: &mut Context<Self>,
10958    ) -> Task<anyhow::Result<Option<Location>>> {
10959        let Some(project) = self.project.clone() else {
10960            return Task::ready(Ok(None));
10961        };
10962
10963        cx.spawn_in(window, move |editor, mut cx| async move {
10964            let location_task = editor.update(&mut cx, |_, cx| {
10965                project.update(cx, |project, cx| {
10966                    let language_server_name = project
10967                        .language_server_statuses(cx)
10968                        .find(|(id, _)| server_id == *id)
10969                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10970                    language_server_name.map(|language_server_name| {
10971                        project.open_local_buffer_via_lsp(
10972                            lsp_location.uri.clone(),
10973                            server_id,
10974                            language_server_name,
10975                            cx,
10976                        )
10977                    })
10978                })
10979            })?;
10980            let location = match location_task {
10981                Some(task) => Some({
10982                    let target_buffer_handle = task.await.context("open local buffer")?;
10983                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10984                        let target_start = target_buffer
10985                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10986                        let target_end = target_buffer
10987                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10988                        target_buffer.anchor_after(target_start)
10989                            ..target_buffer.anchor_before(target_end)
10990                    })?;
10991                    Location {
10992                        buffer: target_buffer_handle,
10993                        range,
10994                    }
10995                }),
10996                None => None,
10997            };
10998            Ok(location)
10999        })
11000    }
11001
11002    pub fn find_all_references(
11003        &mut self,
11004        _: &FindAllReferences,
11005        window: &mut Window,
11006        cx: &mut Context<Self>,
11007    ) -> Option<Task<Result<Navigated>>> {
11008        let selection = self.selections.newest::<usize>(cx);
11009        let multi_buffer = self.buffer.read(cx);
11010        let head = selection.head();
11011
11012        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11013        let head_anchor = multi_buffer_snapshot.anchor_at(
11014            head,
11015            if head < selection.tail() {
11016                Bias::Right
11017            } else {
11018                Bias::Left
11019            },
11020        );
11021
11022        match self
11023            .find_all_references_task_sources
11024            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11025        {
11026            Ok(_) => {
11027                log::info!(
11028                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11029                );
11030                return None;
11031            }
11032            Err(i) => {
11033                self.find_all_references_task_sources.insert(i, head_anchor);
11034            }
11035        }
11036
11037        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11038        let workspace = self.workspace()?;
11039        let project = workspace.read(cx).project().clone();
11040        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11041        Some(cx.spawn_in(window, |editor, mut cx| async move {
11042            let _cleanup = defer({
11043                let mut cx = cx.clone();
11044                move || {
11045                    let _ = editor.update(&mut cx, |editor, _| {
11046                        if let Ok(i) =
11047                            editor
11048                                .find_all_references_task_sources
11049                                .binary_search_by(|anchor| {
11050                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11051                                })
11052                        {
11053                            editor.find_all_references_task_sources.remove(i);
11054                        }
11055                    });
11056                }
11057            });
11058
11059            let locations = references.await?;
11060            if locations.is_empty() {
11061                return anyhow::Ok(Navigated::No);
11062            }
11063
11064            workspace.update_in(&mut cx, |workspace, window, cx| {
11065                let title = locations
11066                    .first()
11067                    .as_ref()
11068                    .map(|location| {
11069                        let buffer = location.buffer.read(cx);
11070                        format!(
11071                            "References to `{}`",
11072                            buffer
11073                                .text_for_range(location.range.clone())
11074                                .collect::<String>()
11075                        )
11076                    })
11077                    .unwrap();
11078                Self::open_locations_in_multibuffer(
11079                    workspace,
11080                    locations,
11081                    title,
11082                    false,
11083                    MultibufferSelectionMode::First,
11084                    window,
11085                    cx,
11086                );
11087                Navigated::Yes
11088            })
11089        }))
11090    }
11091
11092    /// Opens a multibuffer with the given project locations in it
11093    pub fn open_locations_in_multibuffer(
11094        workspace: &mut Workspace,
11095        mut locations: Vec<Location>,
11096        title: String,
11097        split: bool,
11098        multibuffer_selection_mode: MultibufferSelectionMode,
11099        window: &mut Window,
11100        cx: &mut Context<Workspace>,
11101    ) {
11102        // If there are multiple definitions, open them in a multibuffer
11103        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11104        let mut locations = locations.into_iter().peekable();
11105        let mut ranges = Vec::new();
11106        let capability = workspace.project().read(cx).capability();
11107
11108        let excerpt_buffer = cx.new(|cx| {
11109            let mut multibuffer = MultiBuffer::new(capability);
11110            while let Some(location) = locations.next() {
11111                let buffer = location.buffer.read(cx);
11112                let mut ranges_for_buffer = Vec::new();
11113                let range = location.range.to_offset(buffer);
11114                ranges_for_buffer.push(range.clone());
11115
11116                while let Some(next_location) = locations.peek() {
11117                    if next_location.buffer == location.buffer {
11118                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11119                        locations.next();
11120                    } else {
11121                        break;
11122                    }
11123                }
11124
11125                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11126                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11127                    location.buffer.clone(),
11128                    ranges_for_buffer,
11129                    DEFAULT_MULTIBUFFER_CONTEXT,
11130                    cx,
11131                ))
11132            }
11133
11134            multibuffer.with_title(title)
11135        });
11136
11137        let editor = cx.new(|cx| {
11138            Editor::for_multibuffer(
11139                excerpt_buffer,
11140                Some(workspace.project().clone()),
11141                true,
11142                window,
11143                cx,
11144            )
11145        });
11146        editor.update(cx, |editor, cx| {
11147            match multibuffer_selection_mode {
11148                MultibufferSelectionMode::First => {
11149                    if let Some(first_range) = ranges.first() {
11150                        editor.change_selections(None, window, cx, |selections| {
11151                            selections.clear_disjoint();
11152                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11153                        });
11154                    }
11155                    editor.highlight_background::<Self>(
11156                        &ranges,
11157                        |theme| theme.editor_highlighted_line_background,
11158                        cx,
11159                    );
11160                }
11161                MultibufferSelectionMode::All => {
11162                    editor.change_selections(None, window, cx, |selections| {
11163                        selections.clear_disjoint();
11164                        selections.select_anchor_ranges(ranges);
11165                    });
11166                }
11167            }
11168            editor.register_buffers_with_language_servers(cx);
11169        });
11170
11171        let item = Box::new(editor);
11172        let item_id = item.item_id();
11173
11174        if split {
11175            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11176        } else {
11177            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11178                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11179                    pane.close_current_preview_item(window, cx)
11180                } else {
11181                    None
11182                }
11183            });
11184            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11185        }
11186        workspace.active_pane().update(cx, |pane, cx| {
11187            pane.set_preview_item_id(Some(item_id), cx);
11188        });
11189    }
11190
11191    pub fn rename(
11192        &mut self,
11193        _: &Rename,
11194        window: &mut Window,
11195        cx: &mut Context<Self>,
11196    ) -> Option<Task<Result<()>>> {
11197        use language::ToOffset as _;
11198
11199        let provider = self.semantics_provider.clone()?;
11200        let selection = self.selections.newest_anchor().clone();
11201        let (cursor_buffer, cursor_buffer_position) = self
11202            .buffer
11203            .read(cx)
11204            .text_anchor_for_position(selection.head(), cx)?;
11205        let (tail_buffer, cursor_buffer_position_end) = self
11206            .buffer
11207            .read(cx)
11208            .text_anchor_for_position(selection.tail(), cx)?;
11209        if tail_buffer != cursor_buffer {
11210            return None;
11211        }
11212
11213        let snapshot = cursor_buffer.read(cx).snapshot();
11214        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11215        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11216        let prepare_rename = provider
11217            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11218            .unwrap_or_else(|| Task::ready(Ok(None)));
11219        drop(snapshot);
11220
11221        Some(cx.spawn_in(window, |this, mut cx| async move {
11222            let rename_range = if let Some(range) = prepare_rename.await? {
11223                Some(range)
11224            } else {
11225                this.update(&mut cx, |this, cx| {
11226                    let buffer = this.buffer.read(cx).snapshot(cx);
11227                    let mut buffer_highlights = this
11228                        .document_highlights_for_position(selection.head(), &buffer)
11229                        .filter(|highlight| {
11230                            highlight.start.excerpt_id == selection.head().excerpt_id
11231                                && highlight.end.excerpt_id == selection.head().excerpt_id
11232                        });
11233                    buffer_highlights
11234                        .next()
11235                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11236                })?
11237            };
11238            if let Some(rename_range) = rename_range {
11239                this.update_in(&mut cx, |this, window, cx| {
11240                    let snapshot = cursor_buffer.read(cx).snapshot();
11241                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11242                    let cursor_offset_in_rename_range =
11243                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11244                    let cursor_offset_in_rename_range_end =
11245                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11246
11247                    this.take_rename(false, window, cx);
11248                    let buffer = this.buffer.read(cx).read(cx);
11249                    let cursor_offset = selection.head().to_offset(&buffer);
11250                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11251                    let rename_end = rename_start + rename_buffer_range.len();
11252                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11253                    let mut old_highlight_id = None;
11254                    let old_name: Arc<str> = buffer
11255                        .chunks(rename_start..rename_end, true)
11256                        .map(|chunk| {
11257                            if old_highlight_id.is_none() {
11258                                old_highlight_id = chunk.syntax_highlight_id;
11259                            }
11260                            chunk.text
11261                        })
11262                        .collect::<String>()
11263                        .into();
11264
11265                    drop(buffer);
11266
11267                    // Position the selection in the rename editor so that it matches the current selection.
11268                    this.show_local_selections = false;
11269                    let rename_editor = cx.new(|cx| {
11270                        let mut editor = Editor::single_line(window, cx);
11271                        editor.buffer.update(cx, |buffer, cx| {
11272                            buffer.edit([(0..0, old_name.clone())], None, cx)
11273                        });
11274                        let rename_selection_range = match cursor_offset_in_rename_range
11275                            .cmp(&cursor_offset_in_rename_range_end)
11276                        {
11277                            Ordering::Equal => {
11278                                editor.select_all(&SelectAll, window, cx);
11279                                return editor;
11280                            }
11281                            Ordering::Less => {
11282                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11283                            }
11284                            Ordering::Greater => {
11285                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11286                            }
11287                        };
11288                        if rename_selection_range.end > old_name.len() {
11289                            editor.select_all(&SelectAll, window, cx);
11290                        } else {
11291                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11292                                s.select_ranges([rename_selection_range]);
11293                            });
11294                        }
11295                        editor
11296                    });
11297                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11298                        if e == &EditorEvent::Focused {
11299                            cx.emit(EditorEvent::FocusedIn)
11300                        }
11301                    })
11302                    .detach();
11303
11304                    let write_highlights =
11305                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11306                    let read_highlights =
11307                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11308                    let ranges = write_highlights
11309                        .iter()
11310                        .flat_map(|(_, ranges)| ranges.iter())
11311                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11312                        .cloned()
11313                        .collect();
11314
11315                    this.highlight_text::<Rename>(
11316                        ranges,
11317                        HighlightStyle {
11318                            fade_out: Some(0.6),
11319                            ..Default::default()
11320                        },
11321                        cx,
11322                    );
11323                    let rename_focus_handle = rename_editor.focus_handle(cx);
11324                    window.focus(&rename_focus_handle);
11325                    let block_id = this.insert_blocks(
11326                        [BlockProperties {
11327                            style: BlockStyle::Flex,
11328                            placement: BlockPlacement::Below(range.start),
11329                            height: 1,
11330                            render: Arc::new({
11331                                let rename_editor = rename_editor.clone();
11332                                move |cx: &mut BlockContext| {
11333                                    let mut text_style = cx.editor_style.text.clone();
11334                                    if let Some(highlight_style) = old_highlight_id
11335                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11336                                    {
11337                                        text_style = text_style.highlight(highlight_style);
11338                                    }
11339                                    div()
11340                                        .block_mouse_down()
11341                                        .pl(cx.anchor_x)
11342                                        .child(EditorElement::new(
11343                                            &rename_editor,
11344                                            EditorStyle {
11345                                                background: cx.theme().system().transparent,
11346                                                local_player: cx.editor_style.local_player,
11347                                                text: text_style,
11348                                                scrollbar_width: cx.editor_style.scrollbar_width,
11349                                                syntax: cx.editor_style.syntax.clone(),
11350                                                status: cx.editor_style.status.clone(),
11351                                                inlay_hints_style: HighlightStyle {
11352                                                    font_weight: Some(FontWeight::BOLD),
11353                                                    ..make_inlay_hints_style(cx.app)
11354                                                },
11355                                                inline_completion_styles: make_suggestion_styles(
11356                                                    cx.app,
11357                                                ),
11358                                                ..EditorStyle::default()
11359                                            },
11360                                        ))
11361                                        .into_any_element()
11362                                }
11363                            }),
11364                            priority: 0,
11365                        }],
11366                        Some(Autoscroll::fit()),
11367                        cx,
11368                    )[0];
11369                    this.pending_rename = Some(RenameState {
11370                        range,
11371                        old_name,
11372                        editor: rename_editor,
11373                        block_id,
11374                    });
11375                })?;
11376            }
11377
11378            Ok(())
11379        }))
11380    }
11381
11382    pub fn confirm_rename(
11383        &mut self,
11384        _: &ConfirmRename,
11385        window: &mut Window,
11386        cx: &mut Context<Self>,
11387    ) -> Option<Task<Result<()>>> {
11388        let rename = self.take_rename(false, window, cx)?;
11389        let workspace = self.workspace()?.downgrade();
11390        let (buffer, start) = self
11391            .buffer
11392            .read(cx)
11393            .text_anchor_for_position(rename.range.start, cx)?;
11394        let (end_buffer, _) = self
11395            .buffer
11396            .read(cx)
11397            .text_anchor_for_position(rename.range.end, cx)?;
11398        if buffer != end_buffer {
11399            return None;
11400        }
11401
11402        let old_name = rename.old_name;
11403        let new_name = rename.editor.read(cx).text(cx);
11404
11405        let rename = self.semantics_provider.as_ref()?.perform_rename(
11406            &buffer,
11407            start,
11408            new_name.clone(),
11409            cx,
11410        )?;
11411
11412        Some(cx.spawn_in(window, |editor, mut cx| async move {
11413            let project_transaction = rename.await?;
11414            Self::open_project_transaction(
11415                &editor,
11416                workspace,
11417                project_transaction,
11418                format!("Rename: {}{}", old_name, new_name),
11419                cx.clone(),
11420            )
11421            .await?;
11422
11423            editor.update(&mut cx, |editor, cx| {
11424                editor.refresh_document_highlights(cx);
11425            })?;
11426            Ok(())
11427        }))
11428    }
11429
11430    fn take_rename(
11431        &mut self,
11432        moving_cursor: bool,
11433        window: &mut Window,
11434        cx: &mut Context<Self>,
11435    ) -> Option<RenameState> {
11436        let rename = self.pending_rename.take()?;
11437        if rename.editor.focus_handle(cx).is_focused(window) {
11438            window.focus(&self.focus_handle);
11439        }
11440
11441        self.remove_blocks(
11442            [rename.block_id].into_iter().collect(),
11443            Some(Autoscroll::fit()),
11444            cx,
11445        );
11446        self.clear_highlights::<Rename>(cx);
11447        self.show_local_selections = true;
11448
11449        if moving_cursor {
11450            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11451                editor.selections.newest::<usize>(cx).head()
11452            });
11453
11454            // Update the selection to match the position of the selection inside
11455            // the rename editor.
11456            let snapshot = self.buffer.read(cx).read(cx);
11457            let rename_range = rename.range.to_offset(&snapshot);
11458            let cursor_in_editor = snapshot
11459                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11460                .min(rename_range.end);
11461            drop(snapshot);
11462
11463            self.change_selections(None, window, cx, |s| {
11464                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11465            });
11466        } else {
11467            self.refresh_document_highlights(cx);
11468        }
11469
11470        Some(rename)
11471    }
11472
11473    pub fn pending_rename(&self) -> Option<&RenameState> {
11474        self.pending_rename.as_ref()
11475    }
11476
11477    fn format(
11478        &mut self,
11479        _: &Format,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482    ) -> Option<Task<Result<()>>> {
11483        let project = match &self.project {
11484            Some(project) => project.clone(),
11485            None => return None,
11486        };
11487
11488        Some(self.perform_format(
11489            project,
11490            FormatTrigger::Manual,
11491            FormatTarget::Buffers,
11492            window,
11493            cx,
11494        ))
11495    }
11496
11497    fn format_selections(
11498        &mut self,
11499        _: &FormatSelections,
11500        window: &mut Window,
11501        cx: &mut Context<Self>,
11502    ) -> Option<Task<Result<()>>> {
11503        let project = match &self.project {
11504            Some(project) => project.clone(),
11505            None => return None,
11506        };
11507
11508        let ranges = self
11509            .selections
11510            .all_adjusted(cx)
11511            .into_iter()
11512            .map(|selection| selection.range())
11513            .collect_vec();
11514
11515        Some(self.perform_format(
11516            project,
11517            FormatTrigger::Manual,
11518            FormatTarget::Ranges(ranges),
11519            window,
11520            cx,
11521        ))
11522    }
11523
11524    fn perform_format(
11525        &mut self,
11526        project: Entity<Project>,
11527        trigger: FormatTrigger,
11528        target: FormatTarget,
11529        window: &mut Window,
11530        cx: &mut Context<Self>,
11531    ) -> Task<Result<()>> {
11532        let buffer = self.buffer.clone();
11533        let (buffers, target) = match target {
11534            FormatTarget::Buffers => {
11535                let mut buffers = buffer.read(cx).all_buffers();
11536                if trigger == FormatTrigger::Save {
11537                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11538                }
11539                (buffers, LspFormatTarget::Buffers)
11540            }
11541            FormatTarget::Ranges(selection_ranges) => {
11542                let multi_buffer = buffer.read(cx);
11543                let snapshot = multi_buffer.read(cx);
11544                let mut buffers = HashSet::default();
11545                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11546                    BTreeMap::new();
11547                for selection_range in selection_ranges {
11548                    for (buffer, buffer_range, _) in
11549                        snapshot.range_to_buffer_ranges(selection_range)
11550                    {
11551                        let buffer_id = buffer.remote_id();
11552                        let start = buffer.anchor_before(buffer_range.start);
11553                        let end = buffer.anchor_after(buffer_range.end);
11554                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11555                        buffer_id_to_ranges
11556                            .entry(buffer_id)
11557                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11558                            .or_insert_with(|| vec![start..end]);
11559                    }
11560                }
11561                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11562            }
11563        };
11564
11565        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11566        let format = project.update(cx, |project, cx| {
11567            project.format(buffers, target, true, trigger, cx)
11568        });
11569
11570        cx.spawn_in(window, |_, mut cx| async move {
11571            let transaction = futures::select_biased! {
11572                () = timeout => {
11573                    log::warn!("timed out waiting for formatting");
11574                    None
11575                }
11576                transaction = format.log_err().fuse() => transaction,
11577            };
11578
11579            buffer
11580                .update(&mut cx, |buffer, cx| {
11581                    if let Some(transaction) = transaction {
11582                        if !buffer.is_singleton() {
11583                            buffer.push_transaction(&transaction.0, cx);
11584                        }
11585                    }
11586
11587                    cx.notify();
11588                })
11589                .ok();
11590
11591            Ok(())
11592        })
11593    }
11594
11595    fn restart_language_server(
11596        &mut self,
11597        _: &RestartLanguageServer,
11598        _: &mut Window,
11599        cx: &mut Context<Self>,
11600    ) {
11601        if let Some(project) = self.project.clone() {
11602            self.buffer.update(cx, |multi_buffer, cx| {
11603                project.update(cx, |project, cx| {
11604                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11605                });
11606            })
11607        }
11608    }
11609
11610    fn cancel_language_server_work(
11611        workspace: &mut Workspace,
11612        _: &actions::CancelLanguageServerWork,
11613        _: &mut Window,
11614        cx: &mut Context<Workspace>,
11615    ) {
11616        let project = workspace.project();
11617        let buffers = workspace
11618            .active_item(cx)
11619            .and_then(|item| item.act_as::<Editor>(cx))
11620            .map_or(HashSet::default(), |editor| {
11621                editor.read(cx).buffer.read(cx).all_buffers()
11622            });
11623        project.update(cx, |project, cx| {
11624            project.cancel_language_server_work_for_buffers(buffers, cx);
11625        });
11626    }
11627
11628    fn show_character_palette(
11629        &mut self,
11630        _: &ShowCharacterPalette,
11631        window: &mut Window,
11632        _: &mut Context<Self>,
11633    ) {
11634        window.show_character_palette();
11635    }
11636
11637    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11638        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11639            let buffer = self.buffer.read(cx).snapshot(cx);
11640            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11641            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11642            let is_valid = buffer
11643                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11644                .any(|entry| {
11645                    entry.diagnostic.is_primary
11646                        && !entry.range.is_empty()
11647                        && entry.range.start == primary_range_start
11648                        && entry.diagnostic.message == active_diagnostics.primary_message
11649                });
11650
11651            if is_valid != active_diagnostics.is_valid {
11652                active_diagnostics.is_valid = is_valid;
11653                let mut new_styles = HashMap::default();
11654                for (block_id, diagnostic) in &active_diagnostics.blocks {
11655                    new_styles.insert(
11656                        *block_id,
11657                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11658                    );
11659                }
11660                self.display_map.update(cx, |display_map, _cx| {
11661                    display_map.replace_blocks(new_styles)
11662                });
11663            }
11664        }
11665    }
11666
11667    fn activate_diagnostics(
11668        &mut self,
11669        buffer_id: BufferId,
11670        group_id: usize,
11671        window: &mut Window,
11672        cx: &mut Context<Self>,
11673    ) {
11674        self.dismiss_diagnostics(cx);
11675        let snapshot = self.snapshot(window, cx);
11676        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11677            let buffer = self.buffer.read(cx).snapshot(cx);
11678
11679            let mut primary_range = None;
11680            let mut primary_message = None;
11681            let diagnostic_group = buffer
11682                .diagnostic_group(buffer_id, group_id)
11683                .filter_map(|entry| {
11684                    let start = entry.range.start;
11685                    let end = entry.range.end;
11686                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11687                        && (start.row == end.row
11688                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11689                    {
11690                        return None;
11691                    }
11692                    if entry.diagnostic.is_primary {
11693                        primary_range = Some(entry.range.clone());
11694                        primary_message = Some(entry.diagnostic.message.clone());
11695                    }
11696                    Some(entry)
11697                })
11698                .collect::<Vec<_>>();
11699            let primary_range = primary_range?;
11700            let primary_message = primary_message?;
11701
11702            let blocks = display_map
11703                .insert_blocks(
11704                    diagnostic_group.iter().map(|entry| {
11705                        let diagnostic = entry.diagnostic.clone();
11706                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11707                        BlockProperties {
11708                            style: BlockStyle::Fixed,
11709                            placement: BlockPlacement::Below(
11710                                buffer.anchor_after(entry.range.start),
11711                            ),
11712                            height: message_height,
11713                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11714                            priority: 0,
11715                        }
11716                    }),
11717                    cx,
11718                )
11719                .into_iter()
11720                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11721                .collect();
11722
11723            Some(ActiveDiagnosticGroup {
11724                primary_range: buffer.anchor_before(primary_range.start)
11725                    ..buffer.anchor_after(primary_range.end),
11726                primary_message,
11727                group_id,
11728                blocks,
11729                is_valid: true,
11730            })
11731        });
11732    }
11733
11734    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11735        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11736            self.display_map.update(cx, |display_map, cx| {
11737                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11738            });
11739            cx.notify();
11740        }
11741    }
11742
11743    pub fn set_selections_from_remote(
11744        &mut self,
11745        selections: Vec<Selection<Anchor>>,
11746        pending_selection: Option<Selection<Anchor>>,
11747        window: &mut Window,
11748        cx: &mut Context<Self>,
11749    ) {
11750        let old_cursor_position = self.selections.newest_anchor().head();
11751        self.selections.change_with(cx, |s| {
11752            s.select_anchors(selections);
11753            if let Some(pending_selection) = pending_selection {
11754                s.set_pending(pending_selection, SelectMode::Character);
11755            } else {
11756                s.clear_pending();
11757            }
11758        });
11759        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11760    }
11761
11762    fn push_to_selection_history(&mut self) {
11763        self.selection_history.push(SelectionHistoryEntry {
11764            selections: self.selections.disjoint_anchors(),
11765            select_next_state: self.select_next_state.clone(),
11766            select_prev_state: self.select_prev_state.clone(),
11767            add_selections_state: self.add_selections_state.clone(),
11768        });
11769    }
11770
11771    pub fn transact(
11772        &mut self,
11773        window: &mut Window,
11774        cx: &mut Context<Self>,
11775        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11776    ) -> Option<TransactionId> {
11777        self.start_transaction_at(Instant::now(), window, cx);
11778        update(self, window, cx);
11779        self.end_transaction_at(Instant::now(), cx)
11780    }
11781
11782    pub fn start_transaction_at(
11783        &mut self,
11784        now: Instant,
11785        window: &mut Window,
11786        cx: &mut Context<Self>,
11787    ) {
11788        self.end_selection(window, cx);
11789        if let Some(tx_id) = self
11790            .buffer
11791            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11792        {
11793            self.selection_history
11794                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11795            cx.emit(EditorEvent::TransactionBegun {
11796                transaction_id: tx_id,
11797            })
11798        }
11799    }
11800
11801    pub fn end_transaction_at(
11802        &mut self,
11803        now: Instant,
11804        cx: &mut Context<Self>,
11805    ) -> Option<TransactionId> {
11806        if let Some(transaction_id) = self
11807            .buffer
11808            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11809        {
11810            if let Some((_, end_selections)) =
11811                self.selection_history.transaction_mut(transaction_id)
11812            {
11813                *end_selections = Some(self.selections.disjoint_anchors());
11814            } else {
11815                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11816            }
11817
11818            cx.emit(EditorEvent::Edited { transaction_id });
11819            Some(transaction_id)
11820        } else {
11821            None
11822        }
11823    }
11824
11825    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11826        if self.selection_mark_mode {
11827            self.change_selections(None, window, cx, |s| {
11828                s.move_with(|_, sel| {
11829                    sel.collapse_to(sel.head(), SelectionGoal::None);
11830                });
11831            })
11832        }
11833        self.selection_mark_mode = true;
11834        cx.notify();
11835    }
11836
11837    pub fn swap_selection_ends(
11838        &mut self,
11839        _: &actions::SwapSelectionEnds,
11840        window: &mut Window,
11841        cx: &mut Context<Self>,
11842    ) {
11843        self.change_selections(None, window, cx, |s| {
11844            s.move_with(|_, sel| {
11845                if sel.start != sel.end {
11846                    sel.reversed = !sel.reversed
11847                }
11848            });
11849        });
11850        self.request_autoscroll(Autoscroll::newest(), cx);
11851        cx.notify();
11852    }
11853
11854    pub fn toggle_fold(
11855        &mut self,
11856        _: &actions::ToggleFold,
11857        window: &mut Window,
11858        cx: &mut Context<Self>,
11859    ) {
11860        if self.is_singleton(cx) {
11861            let selection = self.selections.newest::<Point>(cx);
11862
11863            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11864            let range = if selection.is_empty() {
11865                let point = selection.head().to_display_point(&display_map);
11866                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11867                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11868                    .to_point(&display_map);
11869                start..end
11870            } else {
11871                selection.range()
11872            };
11873            if display_map.folds_in_range(range).next().is_some() {
11874                self.unfold_lines(&Default::default(), window, cx)
11875            } else {
11876                self.fold(&Default::default(), window, cx)
11877            }
11878        } else {
11879            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11880            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11881                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11882                .map(|(snapshot, _, _)| snapshot.remote_id())
11883                .collect();
11884
11885            for buffer_id in buffer_ids {
11886                if self.is_buffer_folded(buffer_id, cx) {
11887                    self.unfold_buffer(buffer_id, cx);
11888                } else {
11889                    self.fold_buffer(buffer_id, cx);
11890                }
11891            }
11892        }
11893    }
11894
11895    pub fn toggle_fold_recursive(
11896        &mut self,
11897        _: &actions::ToggleFoldRecursive,
11898        window: &mut Window,
11899        cx: &mut Context<Self>,
11900    ) {
11901        let selection = self.selections.newest::<Point>(cx);
11902
11903        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11904        let range = if selection.is_empty() {
11905            let point = selection.head().to_display_point(&display_map);
11906            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11907            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11908                .to_point(&display_map);
11909            start..end
11910        } else {
11911            selection.range()
11912        };
11913        if display_map.folds_in_range(range).next().is_some() {
11914            self.unfold_recursive(&Default::default(), window, cx)
11915        } else {
11916            self.fold_recursive(&Default::default(), window, cx)
11917        }
11918    }
11919
11920    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11921        if self.is_singleton(cx) {
11922            let mut to_fold = Vec::new();
11923            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11924            let selections = self.selections.all_adjusted(cx);
11925
11926            for selection in selections {
11927                let range = selection.range().sorted();
11928                let buffer_start_row = range.start.row;
11929
11930                if range.start.row != range.end.row {
11931                    let mut found = false;
11932                    let mut row = range.start.row;
11933                    while row <= range.end.row {
11934                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11935                        {
11936                            found = true;
11937                            row = crease.range().end.row + 1;
11938                            to_fold.push(crease);
11939                        } else {
11940                            row += 1
11941                        }
11942                    }
11943                    if found {
11944                        continue;
11945                    }
11946                }
11947
11948                for row in (0..=range.start.row).rev() {
11949                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11950                        if crease.range().end.row >= buffer_start_row {
11951                            to_fold.push(crease);
11952                            if row <= range.start.row {
11953                                break;
11954                            }
11955                        }
11956                    }
11957                }
11958            }
11959
11960            self.fold_creases(to_fold, true, window, cx);
11961        } else {
11962            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11963
11964            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11965                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11966                .map(|(snapshot, _, _)| snapshot.remote_id())
11967                .collect();
11968            for buffer_id in buffer_ids {
11969                self.fold_buffer(buffer_id, cx);
11970            }
11971        }
11972    }
11973
11974    fn fold_at_level(
11975        &mut self,
11976        fold_at: &FoldAtLevel,
11977        window: &mut Window,
11978        cx: &mut Context<Self>,
11979    ) {
11980        if !self.buffer.read(cx).is_singleton() {
11981            return;
11982        }
11983
11984        let fold_at_level = fold_at.0;
11985        let snapshot = self.buffer.read(cx).snapshot(cx);
11986        let mut to_fold = Vec::new();
11987        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11988
11989        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11990            while start_row < end_row {
11991                match self
11992                    .snapshot(window, cx)
11993                    .crease_for_buffer_row(MultiBufferRow(start_row))
11994                {
11995                    Some(crease) => {
11996                        let nested_start_row = crease.range().start.row + 1;
11997                        let nested_end_row = crease.range().end.row;
11998
11999                        if current_level < fold_at_level {
12000                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12001                        } else if current_level == fold_at_level {
12002                            to_fold.push(crease);
12003                        }
12004
12005                        start_row = nested_end_row + 1;
12006                    }
12007                    None => start_row += 1,
12008                }
12009            }
12010        }
12011
12012        self.fold_creases(to_fold, true, window, cx);
12013    }
12014
12015    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12016        if self.buffer.read(cx).is_singleton() {
12017            let mut fold_ranges = Vec::new();
12018            let snapshot = self.buffer.read(cx).snapshot(cx);
12019
12020            for row in 0..snapshot.max_row().0 {
12021                if let Some(foldable_range) = self
12022                    .snapshot(window, cx)
12023                    .crease_for_buffer_row(MultiBufferRow(row))
12024                {
12025                    fold_ranges.push(foldable_range);
12026                }
12027            }
12028
12029            self.fold_creases(fold_ranges, true, window, cx);
12030        } else {
12031            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12032                editor
12033                    .update_in(&mut cx, |editor, _, cx| {
12034                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12035                            editor.fold_buffer(buffer_id, cx);
12036                        }
12037                    })
12038                    .ok();
12039            });
12040        }
12041    }
12042
12043    pub fn fold_function_bodies(
12044        &mut self,
12045        _: &actions::FoldFunctionBodies,
12046        window: &mut Window,
12047        cx: &mut Context<Self>,
12048    ) {
12049        let snapshot = self.buffer.read(cx).snapshot(cx);
12050
12051        let ranges = snapshot
12052            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12053            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12054            .collect::<Vec<_>>();
12055
12056        let creases = ranges
12057            .into_iter()
12058            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12059            .collect();
12060
12061        self.fold_creases(creases, true, window, cx);
12062    }
12063
12064    pub fn fold_recursive(
12065        &mut self,
12066        _: &actions::FoldRecursive,
12067        window: &mut Window,
12068        cx: &mut Context<Self>,
12069    ) {
12070        let mut to_fold = Vec::new();
12071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12072        let selections = self.selections.all_adjusted(cx);
12073
12074        for selection in selections {
12075            let range = selection.range().sorted();
12076            let buffer_start_row = range.start.row;
12077
12078            if range.start.row != range.end.row {
12079                let mut found = false;
12080                for row in range.start.row..=range.end.row {
12081                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12082                        found = true;
12083                        to_fold.push(crease);
12084                    }
12085                }
12086                if found {
12087                    continue;
12088                }
12089            }
12090
12091            for row in (0..=range.start.row).rev() {
12092                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12093                    if crease.range().end.row >= buffer_start_row {
12094                        to_fold.push(crease);
12095                    } else {
12096                        break;
12097                    }
12098                }
12099            }
12100        }
12101
12102        self.fold_creases(to_fold, true, window, cx);
12103    }
12104
12105    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12106        let buffer_row = fold_at.buffer_row;
12107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12108
12109        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12110            let autoscroll = self
12111                .selections
12112                .all::<Point>(cx)
12113                .iter()
12114                .any(|selection| crease.range().overlaps(&selection.range()));
12115
12116            self.fold_creases(vec![crease], autoscroll, window, cx);
12117        }
12118    }
12119
12120    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12121        if self.is_singleton(cx) {
12122            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12123            let buffer = &display_map.buffer_snapshot;
12124            let selections = self.selections.all::<Point>(cx);
12125            let ranges = selections
12126                .iter()
12127                .map(|s| {
12128                    let range = s.display_range(&display_map).sorted();
12129                    let mut start = range.start.to_point(&display_map);
12130                    let mut end = range.end.to_point(&display_map);
12131                    start.column = 0;
12132                    end.column = buffer.line_len(MultiBufferRow(end.row));
12133                    start..end
12134                })
12135                .collect::<Vec<_>>();
12136
12137            self.unfold_ranges(&ranges, true, true, cx);
12138        } else {
12139            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12140            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12141                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12142                .map(|(snapshot, _, _)| snapshot.remote_id())
12143                .collect();
12144            for buffer_id in buffer_ids {
12145                self.unfold_buffer(buffer_id, cx);
12146            }
12147        }
12148    }
12149
12150    pub fn unfold_recursive(
12151        &mut self,
12152        _: &UnfoldRecursive,
12153        _window: &mut Window,
12154        cx: &mut Context<Self>,
12155    ) {
12156        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12157        let selections = self.selections.all::<Point>(cx);
12158        let ranges = selections
12159            .iter()
12160            .map(|s| {
12161                let mut range = s.display_range(&display_map).sorted();
12162                *range.start.column_mut() = 0;
12163                *range.end.column_mut() = display_map.line_len(range.end.row());
12164                let start = range.start.to_point(&display_map);
12165                let end = range.end.to_point(&display_map);
12166                start..end
12167            })
12168            .collect::<Vec<_>>();
12169
12170        self.unfold_ranges(&ranges, true, true, cx);
12171    }
12172
12173    pub fn unfold_at(
12174        &mut self,
12175        unfold_at: &UnfoldAt,
12176        _window: &mut Window,
12177        cx: &mut Context<Self>,
12178    ) {
12179        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12180
12181        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12182            ..Point::new(
12183                unfold_at.buffer_row.0,
12184                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12185            );
12186
12187        let autoscroll = self
12188            .selections
12189            .all::<Point>(cx)
12190            .iter()
12191            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12192
12193        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12194    }
12195
12196    pub fn unfold_all(
12197        &mut self,
12198        _: &actions::UnfoldAll,
12199        _window: &mut Window,
12200        cx: &mut Context<Self>,
12201    ) {
12202        if self.buffer.read(cx).is_singleton() {
12203            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12204            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12205        } else {
12206            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12207                editor
12208                    .update(&mut cx, |editor, cx| {
12209                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12210                            editor.unfold_buffer(buffer_id, cx);
12211                        }
12212                    })
12213                    .ok();
12214            });
12215        }
12216    }
12217
12218    pub fn fold_selected_ranges(
12219        &mut self,
12220        _: &FoldSelectedRanges,
12221        window: &mut Window,
12222        cx: &mut Context<Self>,
12223    ) {
12224        let selections = self.selections.all::<Point>(cx);
12225        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12226        let line_mode = self.selections.line_mode;
12227        let ranges = selections
12228            .into_iter()
12229            .map(|s| {
12230                if line_mode {
12231                    let start = Point::new(s.start.row, 0);
12232                    let end = Point::new(
12233                        s.end.row,
12234                        display_map
12235                            .buffer_snapshot
12236                            .line_len(MultiBufferRow(s.end.row)),
12237                    );
12238                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12239                } else {
12240                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12241                }
12242            })
12243            .collect::<Vec<_>>();
12244        self.fold_creases(ranges, true, window, cx);
12245    }
12246
12247    pub fn fold_ranges<T: ToOffset + Clone>(
12248        &mut self,
12249        ranges: Vec<Range<T>>,
12250        auto_scroll: bool,
12251        window: &mut Window,
12252        cx: &mut Context<Self>,
12253    ) {
12254        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12255        let ranges = ranges
12256            .into_iter()
12257            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12258            .collect::<Vec<_>>();
12259        self.fold_creases(ranges, auto_scroll, window, cx);
12260    }
12261
12262    pub fn fold_creases<T: ToOffset + Clone>(
12263        &mut self,
12264        creases: Vec<Crease<T>>,
12265        auto_scroll: bool,
12266        window: &mut Window,
12267        cx: &mut Context<Self>,
12268    ) {
12269        if creases.is_empty() {
12270            return;
12271        }
12272
12273        let mut buffers_affected = HashSet::default();
12274        let multi_buffer = self.buffer().read(cx);
12275        for crease in &creases {
12276            if let Some((_, buffer, _)) =
12277                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12278            {
12279                buffers_affected.insert(buffer.read(cx).remote_id());
12280            };
12281        }
12282
12283        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12284
12285        if auto_scroll {
12286            self.request_autoscroll(Autoscroll::fit(), cx);
12287        }
12288
12289        cx.notify();
12290
12291        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12292            // Clear diagnostics block when folding a range that contains it.
12293            let snapshot = self.snapshot(window, cx);
12294            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12295                drop(snapshot);
12296                self.active_diagnostics = Some(active_diagnostics);
12297                self.dismiss_diagnostics(cx);
12298            } else {
12299                self.active_diagnostics = Some(active_diagnostics);
12300            }
12301        }
12302
12303        self.scrollbar_marker_state.dirty = true;
12304    }
12305
12306    /// Removes any folds whose ranges intersect any of the given ranges.
12307    pub fn unfold_ranges<T: ToOffset + Clone>(
12308        &mut self,
12309        ranges: &[Range<T>],
12310        inclusive: bool,
12311        auto_scroll: bool,
12312        cx: &mut Context<Self>,
12313    ) {
12314        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12315            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12316        });
12317    }
12318
12319    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12320        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12321            return;
12322        }
12323        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12324        self.display_map
12325            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12326        cx.emit(EditorEvent::BufferFoldToggled {
12327            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12328            folded: true,
12329        });
12330        cx.notify();
12331    }
12332
12333    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12334        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12335            return;
12336        }
12337        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12338        self.display_map.update(cx, |display_map, cx| {
12339            display_map.unfold_buffer(buffer_id, cx);
12340        });
12341        cx.emit(EditorEvent::BufferFoldToggled {
12342            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12343            folded: false,
12344        });
12345        cx.notify();
12346    }
12347
12348    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12349        self.display_map.read(cx).is_buffer_folded(buffer)
12350    }
12351
12352    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12353        self.display_map.read(cx).folded_buffers()
12354    }
12355
12356    /// Removes any folds with the given ranges.
12357    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12358        &mut self,
12359        ranges: &[Range<T>],
12360        type_id: TypeId,
12361        auto_scroll: bool,
12362        cx: &mut Context<Self>,
12363    ) {
12364        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12365            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12366        });
12367    }
12368
12369    fn remove_folds_with<T: ToOffset + Clone>(
12370        &mut self,
12371        ranges: &[Range<T>],
12372        auto_scroll: bool,
12373        cx: &mut Context<Self>,
12374        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12375    ) {
12376        if ranges.is_empty() {
12377            return;
12378        }
12379
12380        let mut buffers_affected = HashSet::default();
12381        let multi_buffer = self.buffer().read(cx);
12382        for range in ranges {
12383            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12384                buffers_affected.insert(buffer.read(cx).remote_id());
12385            };
12386        }
12387
12388        self.display_map.update(cx, update);
12389
12390        if auto_scroll {
12391            self.request_autoscroll(Autoscroll::fit(), cx);
12392        }
12393
12394        cx.notify();
12395        self.scrollbar_marker_state.dirty = true;
12396        self.active_indent_guides_state.dirty = true;
12397    }
12398
12399    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12400        self.display_map.read(cx).fold_placeholder.clone()
12401    }
12402
12403    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12404        self.buffer.update(cx, |buffer, cx| {
12405            buffer.set_all_diff_hunks_expanded(cx);
12406        });
12407    }
12408
12409    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12410        self.distinguish_unstaged_diff_hunks = true;
12411    }
12412
12413    pub fn expand_all_diff_hunks(
12414        &mut self,
12415        _: &ExpandAllHunkDiffs,
12416        _window: &mut Window,
12417        cx: &mut Context<Self>,
12418    ) {
12419        self.buffer.update(cx, |buffer, cx| {
12420            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12421        });
12422    }
12423
12424    pub fn toggle_selected_diff_hunks(
12425        &mut self,
12426        _: &ToggleSelectedDiffHunks,
12427        _window: &mut Window,
12428        cx: &mut Context<Self>,
12429    ) {
12430        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12431        self.toggle_diff_hunks_in_ranges(ranges, cx);
12432    }
12433
12434    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12435        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12436        self.buffer
12437            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12438    }
12439
12440    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12441        self.buffer.update(cx, |buffer, cx| {
12442            let ranges = vec![Anchor::min()..Anchor::max()];
12443            if !buffer.all_diff_hunks_expanded()
12444                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12445            {
12446                buffer.collapse_diff_hunks(ranges, cx);
12447                true
12448            } else {
12449                false
12450            }
12451        })
12452    }
12453
12454    fn toggle_diff_hunks_in_ranges(
12455        &mut self,
12456        ranges: Vec<Range<Anchor>>,
12457        cx: &mut Context<'_, Editor>,
12458    ) {
12459        self.buffer.update(cx, |buffer, cx| {
12460            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12461            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12462        })
12463    }
12464
12465    fn toggle_diff_hunks_in_ranges_narrow(
12466        &mut self,
12467        ranges: Vec<Range<Anchor>>,
12468        cx: &mut Context<'_, Editor>,
12469    ) {
12470        self.buffer.update(cx, |buffer, cx| {
12471            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12472            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12473        })
12474    }
12475
12476    pub(crate) fn apply_all_diff_hunks(
12477        &mut self,
12478        _: &ApplyAllDiffHunks,
12479        window: &mut Window,
12480        cx: &mut Context<Self>,
12481    ) {
12482        let buffers = self.buffer.read(cx).all_buffers();
12483        for branch_buffer in buffers {
12484            branch_buffer.update(cx, |branch_buffer, cx| {
12485                branch_buffer.merge_into_base(Vec::new(), cx);
12486            });
12487        }
12488
12489        if let Some(project) = self.project.clone() {
12490            self.save(true, project, window, cx).detach_and_log_err(cx);
12491        }
12492    }
12493
12494    pub(crate) fn apply_selected_diff_hunks(
12495        &mut self,
12496        _: &ApplyDiffHunk,
12497        window: &mut Window,
12498        cx: &mut Context<Self>,
12499    ) {
12500        let snapshot = self.snapshot(window, cx);
12501        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12502        let mut ranges_by_buffer = HashMap::default();
12503        self.transact(window, cx, |editor, _window, cx| {
12504            for hunk in hunks {
12505                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12506                    ranges_by_buffer
12507                        .entry(buffer.clone())
12508                        .or_insert_with(Vec::new)
12509                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12510                }
12511            }
12512
12513            for (buffer, ranges) in ranges_by_buffer {
12514                buffer.update(cx, |buffer, cx| {
12515                    buffer.merge_into_base(ranges, cx);
12516                });
12517            }
12518        });
12519
12520        if let Some(project) = self.project.clone() {
12521            self.save(true, project, window, cx).detach_and_log_err(cx);
12522        }
12523    }
12524
12525    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12526        if hovered != self.gutter_hovered {
12527            self.gutter_hovered = hovered;
12528            cx.notify();
12529        }
12530    }
12531
12532    pub fn insert_blocks(
12533        &mut self,
12534        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12535        autoscroll: Option<Autoscroll>,
12536        cx: &mut Context<Self>,
12537    ) -> Vec<CustomBlockId> {
12538        let blocks = self
12539            .display_map
12540            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12541        if let Some(autoscroll) = autoscroll {
12542            self.request_autoscroll(autoscroll, cx);
12543        }
12544        cx.notify();
12545        blocks
12546    }
12547
12548    pub fn resize_blocks(
12549        &mut self,
12550        heights: HashMap<CustomBlockId, u32>,
12551        autoscroll: Option<Autoscroll>,
12552        cx: &mut Context<Self>,
12553    ) {
12554        self.display_map
12555            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12556        if let Some(autoscroll) = autoscroll {
12557            self.request_autoscroll(autoscroll, cx);
12558        }
12559        cx.notify();
12560    }
12561
12562    pub fn replace_blocks(
12563        &mut self,
12564        renderers: HashMap<CustomBlockId, RenderBlock>,
12565        autoscroll: Option<Autoscroll>,
12566        cx: &mut Context<Self>,
12567    ) {
12568        self.display_map
12569            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12570        if let Some(autoscroll) = autoscroll {
12571            self.request_autoscroll(autoscroll, cx);
12572        }
12573        cx.notify();
12574    }
12575
12576    pub fn remove_blocks(
12577        &mut self,
12578        block_ids: HashSet<CustomBlockId>,
12579        autoscroll: Option<Autoscroll>,
12580        cx: &mut Context<Self>,
12581    ) {
12582        self.display_map.update(cx, |display_map, cx| {
12583            display_map.remove_blocks(block_ids, cx)
12584        });
12585        if let Some(autoscroll) = autoscroll {
12586            self.request_autoscroll(autoscroll, cx);
12587        }
12588        cx.notify();
12589    }
12590
12591    pub fn row_for_block(
12592        &self,
12593        block_id: CustomBlockId,
12594        cx: &mut Context<Self>,
12595    ) -> Option<DisplayRow> {
12596        self.display_map
12597            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12598    }
12599
12600    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12601        self.focused_block = Some(focused_block);
12602    }
12603
12604    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12605        self.focused_block.take()
12606    }
12607
12608    pub fn insert_creases(
12609        &mut self,
12610        creases: impl IntoIterator<Item = Crease<Anchor>>,
12611        cx: &mut Context<Self>,
12612    ) -> Vec<CreaseId> {
12613        self.display_map
12614            .update(cx, |map, cx| map.insert_creases(creases, cx))
12615    }
12616
12617    pub fn remove_creases(
12618        &mut self,
12619        ids: impl IntoIterator<Item = CreaseId>,
12620        cx: &mut Context<Self>,
12621    ) {
12622        self.display_map
12623            .update(cx, |map, cx| map.remove_creases(ids, cx));
12624    }
12625
12626    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12627        self.display_map
12628            .update(cx, |map, cx| map.snapshot(cx))
12629            .longest_row()
12630    }
12631
12632    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12633        self.display_map
12634            .update(cx, |map, cx| map.snapshot(cx))
12635            .max_point()
12636    }
12637
12638    pub fn text(&self, cx: &App) -> String {
12639        self.buffer.read(cx).read(cx).text()
12640    }
12641
12642    pub fn is_empty(&self, cx: &App) -> bool {
12643        self.buffer.read(cx).read(cx).is_empty()
12644    }
12645
12646    pub fn text_option(&self, cx: &App) -> Option<String> {
12647        let text = self.text(cx);
12648        let text = text.trim();
12649
12650        if text.is_empty() {
12651            return None;
12652        }
12653
12654        Some(text.to_string())
12655    }
12656
12657    pub fn set_text(
12658        &mut self,
12659        text: impl Into<Arc<str>>,
12660        window: &mut Window,
12661        cx: &mut Context<Self>,
12662    ) {
12663        self.transact(window, cx, |this, _, cx| {
12664            this.buffer
12665                .read(cx)
12666                .as_singleton()
12667                .expect("you can only call set_text on editors for singleton buffers")
12668                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12669        });
12670    }
12671
12672    pub fn display_text(&self, cx: &mut App) -> String {
12673        self.display_map
12674            .update(cx, |map, cx| map.snapshot(cx))
12675            .text()
12676    }
12677
12678    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12679        let mut wrap_guides = smallvec::smallvec![];
12680
12681        if self.show_wrap_guides == Some(false) {
12682            return wrap_guides;
12683        }
12684
12685        let settings = self.buffer.read(cx).settings_at(0, cx);
12686        if settings.show_wrap_guides {
12687            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12688                wrap_guides.push((soft_wrap as usize, true));
12689            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12690                wrap_guides.push((soft_wrap as usize, true));
12691            }
12692            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12693        }
12694
12695        wrap_guides
12696    }
12697
12698    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12699        let settings = self.buffer.read(cx).settings_at(0, cx);
12700        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12701        match mode {
12702            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12703                SoftWrap::None
12704            }
12705            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12706            language_settings::SoftWrap::PreferredLineLength => {
12707                SoftWrap::Column(settings.preferred_line_length)
12708            }
12709            language_settings::SoftWrap::Bounded => {
12710                SoftWrap::Bounded(settings.preferred_line_length)
12711            }
12712        }
12713    }
12714
12715    pub fn set_soft_wrap_mode(
12716        &mut self,
12717        mode: language_settings::SoftWrap,
12718
12719        cx: &mut Context<Self>,
12720    ) {
12721        self.soft_wrap_mode_override = Some(mode);
12722        cx.notify();
12723    }
12724
12725    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12726        self.text_style_refinement = Some(style);
12727    }
12728
12729    /// called by the Element so we know what style we were most recently rendered with.
12730    pub(crate) fn set_style(
12731        &mut self,
12732        style: EditorStyle,
12733        window: &mut Window,
12734        cx: &mut Context<Self>,
12735    ) {
12736        let rem_size = window.rem_size();
12737        self.display_map.update(cx, |map, cx| {
12738            map.set_font(
12739                style.text.font(),
12740                style.text.font_size.to_pixels(rem_size),
12741                cx,
12742            )
12743        });
12744        self.style = Some(style);
12745    }
12746
12747    pub fn style(&self) -> Option<&EditorStyle> {
12748        self.style.as_ref()
12749    }
12750
12751    // Called by the element. This method is not designed to be called outside of the editor
12752    // element's layout code because it does not notify when rewrapping is computed synchronously.
12753    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12754        self.display_map
12755            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12756    }
12757
12758    pub fn set_soft_wrap(&mut self) {
12759        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12760    }
12761
12762    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12763        if self.soft_wrap_mode_override.is_some() {
12764            self.soft_wrap_mode_override.take();
12765        } else {
12766            let soft_wrap = match self.soft_wrap_mode(cx) {
12767                SoftWrap::GitDiff => return,
12768                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12769                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12770                    language_settings::SoftWrap::None
12771                }
12772            };
12773            self.soft_wrap_mode_override = Some(soft_wrap);
12774        }
12775        cx.notify();
12776    }
12777
12778    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12779        let Some(workspace) = self.workspace() else {
12780            return;
12781        };
12782        let fs = workspace.read(cx).app_state().fs.clone();
12783        let current_show = TabBarSettings::get_global(cx).show;
12784        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12785            setting.show = Some(!current_show);
12786        });
12787    }
12788
12789    pub fn toggle_indent_guides(
12790        &mut self,
12791        _: &ToggleIndentGuides,
12792        _: &mut Window,
12793        cx: &mut Context<Self>,
12794    ) {
12795        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12796            self.buffer
12797                .read(cx)
12798                .settings_at(0, cx)
12799                .indent_guides
12800                .enabled
12801        });
12802        self.show_indent_guides = Some(!currently_enabled);
12803        cx.notify();
12804    }
12805
12806    fn should_show_indent_guides(&self) -> Option<bool> {
12807        self.show_indent_guides
12808    }
12809
12810    pub fn toggle_line_numbers(
12811        &mut self,
12812        _: &ToggleLineNumbers,
12813        _: &mut Window,
12814        cx: &mut Context<Self>,
12815    ) {
12816        let mut editor_settings = EditorSettings::get_global(cx).clone();
12817        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12818        EditorSettings::override_global(editor_settings, cx);
12819    }
12820
12821    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12822        self.use_relative_line_numbers
12823            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12824    }
12825
12826    pub fn toggle_relative_line_numbers(
12827        &mut self,
12828        _: &ToggleRelativeLineNumbers,
12829        _: &mut Window,
12830        cx: &mut Context<Self>,
12831    ) {
12832        let is_relative = self.should_use_relative_line_numbers(cx);
12833        self.set_relative_line_number(Some(!is_relative), cx)
12834    }
12835
12836    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12837        self.use_relative_line_numbers = is_relative;
12838        cx.notify();
12839    }
12840
12841    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12842        self.show_gutter = show_gutter;
12843        cx.notify();
12844    }
12845
12846    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12847        self.show_scrollbars = show_scrollbars;
12848        cx.notify();
12849    }
12850
12851    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12852        self.show_line_numbers = Some(show_line_numbers);
12853        cx.notify();
12854    }
12855
12856    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12857        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12858        cx.notify();
12859    }
12860
12861    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12862        self.show_code_actions = Some(show_code_actions);
12863        cx.notify();
12864    }
12865
12866    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12867        self.show_runnables = Some(show_runnables);
12868        cx.notify();
12869    }
12870
12871    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12872        if self.display_map.read(cx).masked != masked {
12873            self.display_map.update(cx, |map, _| map.masked = masked);
12874        }
12875        cx.notify()
12876    }
12877
12878    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12879        self.show_wrap_guides = Some(show_wrap_guides);
12880        cx.notify();
12881    }
12882
12883    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12884        self.show_indent_guides = Some(show_indent_guides);
12885        cx.notify();
12886    }
12887
12888    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12889        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12890            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12891                if let Some(dir) = file.abs_path(cx).parent() {
12892                    return Some(dir.to_owned());
12893                }
12894            }
12895
12896            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12897                return Some(project_path.path.to_path_buf());
12898            }
12899        }
12900
12901        None
12902    }
12903
12904    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12905        self.active_excerpt(cx)?
12906            .1
12907            .read(cx)
12908            .file()
12909            .and_then(|f| f.as_local())
12910    }
12911
12912    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12913        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12914            let buffer = buffer.read(cx);
12915            if let Some(project_path) = buffer.project_path(cx) {
12916                let project = self.project.as_ref()?.read(cx);
12917                project.absolute_path(&project_path, cx)
12918            } else {
12919                buffer
12920                    .file()
12921                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
12922            }
12923        })
12924    }
12925
12926    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12927        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12928            let project_path = buffer.read(cx).project_path(cx)?;
12929            let project = self.project.as_ref()?.read(cx);
12930            let entry = project.entry_for_path(&project_path, cx)?;
12931            let path = entry.path.to_path_buf();
12932            Some(path)
12933        })
12934    }
12935
12936    pub fn reveal_in_finder(
12937        &mut self,
12938        _: &RevealInFileManager,
12939        _window: &mut Window,
12940        cx: &mut Context<Self>,
12941    ) {
12942        if let Some(target) = self.target_file(cx) {
12943            cx.reveal_path(&target.abs_path(cx));
12944        }
12945    }
12946
12947    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12948        if let Some(path) = self.target_file_abs_path(cx) {
12949            if let Some(path) = path.to_str() {
12950                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12951            }
12952        }
12953    }
12954
12955    pub fn copy_relative_path(
12956        &mut self,
12957        _: &CopyRelativePath,
12958        _window: &mut Window,
12959        cx: &mut Context<Self>,
12960    ) {
12961        if let Some(path) = self.target_file_path(cx) {
12962            if let Some(path) = path.to_str() {
12963                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12964            }
12965        }
12966    }
12967
12968    pub fn copy_file_name_without_extension(
12969        &mut self,
12970        _: &CopyFileNameWithoutExtension,
12971        _: &mut Window,
12972        cx: &mut Context<Self>,
12973    ) {
12974        if let Some(file) = self.target_file(cx) {
12975            if let Some(file_stem) = file.path().file_stem() {
12976                if let Some(name) = file_stem.to_str() {
12977                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12978                }
12979            }
12980        }
12981    }
12982
12983    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
12984        if let Some(file) = self.target_file(cx) {
12985            if let Some(file_name) = file.path().file_name() {
12986                if let Some(name) = file_name.to_str() {
12987                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12988                }
12989            }
12990        }
12991    }
12992
12993    pub fn toggle_git_blame(
12994        &mut self,
12995        _: &ToggleGitBlame,
12996        window: &mut Window,
12997        cx: &mut Context<Self>,
12998    ) {
12999        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13000
13001        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13002            self.start_git_blame(true, window, cx);
13003        }
13004
13005        cx.notify();
13006    }
13007
13008    pub fn toggle_git_blame_inline(
13009        &mut self,
13010        _: &ToggleGitBlameInline,
13011        window: &mut Window,
13012        cx: &mut Context<Self>,
13013    ) {
13014        self.toggle_git_blame_inline_internal(true, window, cx);
13015        cx.notify();
13016    }
13017
13018    pub fn git_blame_inline_enabled(&self) -> bool {
13019        self.git_blame_inline_enabled
13020    }
13021
13022    pub fn toggle_selection_menu(
13023        &mut self,
13024        _: &ToggleSelectionMenu,
13025        _: &mut Window,
13026        cx: &mut Context<Self>,
13027    ) {
13028        self.show_selection_menu = self
13029            .show_selection_menu
13030            .map(|show_selections_menu| !show_selections_menu)
13031            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13032
13033        cx.notify();
13034    }
13035
13036    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13037        self.show_selection_menu
13038            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13039    }
13040
13041    fn start_git_blame(
13042        &mut self,
13043        user_triggered: bool,
13044        window: &mut Window,
13045        cx: &mut Context<Self>,
13046    ) {
13047        if let Some(project) = self.project.as_ref() {
13048            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13049                return;
13050            };
13051
13052            if buffer.read(cx).file().is_none() {
13053                return;
13054            }
13055
13056            let focused = self.focus_handle(cx).contains_focused(window, cx);
13057
13058            let project = project.clone();
13059            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13060            self.blame_subscription =
13061                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13062            self.blame = Some(blame);
13063        }
13064    }
13065
13066    fn toggle_git_blame_inline_internal(
13067        &mut self,
13068        user_triggered: bool,
13069        window: &mut Window,
13070        cx: &mut Context<Self>,
13071    ) {
13072        if self.git_blame_inline_enabled {
13073            self.git_blame_inline_enabled = false;
13074            self.show_git_blame_inline = false;
13075            self.show_git_blame_inline_delay_task.take();
13076        } else {
13077            self.git_blame_inline_enabled = true;
13078            self.start_git_blame_inline(user_triggered, window, cx);
13079        }
13080
13081        cx.notify();
13082    }
13083
13084    fn start_git_blame_inline(
13085        &mut self,
13086        user_triggered: bool,
13087        window: &mut Window,
13088        cx: &mut Context<Self>,
13089    ) {
13090        self.start_git_blame(user_triggered, window, cx);
13091
13092        if ProjectSettings::get_global(cx)
13093            .git
13094            .inline_blame_delay()
13095            .is_some()
13096        {
13097            self.start_inline_blame_timer(window, cx);
13098        } else {
13099            self.show_git_blame_inline = true
13100        }
13101    }
13102
13103    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13104        self.blame.as_ref()
13105    }
13106
13107    pub fn show_git_blame_gutter(&self) -> bool {
13108        self.show_git_blame_gutter
13109    }
13110
13111    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13112        self.show_git_blame_gutter && self.has_blame_entries(cx)
13113    }
13114
13115    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13116        self.show_git_blame_inline
13117            && self.focus_handle.is_focused(window)
13118            && !self.newest_selection_head_on_empty_line(cx)
13119            && self.has_blame_entries(cx)
13120    }
13121
13122    fn has_blame_entries(&self, cx: &App) -> bool {
13123        self.blame()
13124            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13125    }
13126
13127    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13128        let cursor_anchor = self.selections.newest_anchor().head();
13129
13130        let snapshot = self.buffer.read(cx).snapshot(cx);
13131        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13132
13133        snapshot.line_len(buffer_row) == 0
13134    }
13135
13136    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13137        let buffer_and_selection = maybe!({
13138            let selection = self.selections.newest::<Point>(cx);
13139            let selection_range = selection.range();
13140
13141            let multi_buffer = self.buffer().read(cx);
13142            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13143            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13144
13145            let (buffer, range, _) = if selection.reversed {
13146                buffer_ranges.first()
13147            } else {
13148                buffer_ranges.last()
13149            }?;
13150
13151            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13152                ..text::ToPoint::to_point(&range.end, &buffer).row;
13153            Some((
13154                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13155                selection,
13156            ))
13157        });
13158
13159        let Some((buffer, selection)) = buffer_and_selection else {
13160            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13161        };
13162
13163        let Some(project) = self.project.as_ref() else {
13164            return Task::ready(Err(anyhow!("editor does not have project")));
13165        };
13166
13167        project.update(cx, |project, cx| {
13168            project.get_permalink_to_line(&buffer, selection, cx)
13169        })
13170    }
13171
13172    pub fn copy_permalink_to_line(
13173        &mut self,
13174        _: &CopyPermalinkToLine,
13175        window: &mut Window,
13176        cx: &mut Context<Self>,
13177    ) {
13178        let permalink_task = self.get_permalink_to_line(cx);
13179        let workspace = self.workspace();
13180
13181        cx.spawn_in(window, |_, mut cx| async move {
13182            match permalink_task.await {
13183                Ok(permalink) => {
13184                    cx.update(|_, cx| {
13185                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13186                    })
13187                    .ok();
13188                }
13189                Err(err) => {
13190                    let message = format!("Failed to copy permalink: {err}");
13191
13192                    Err::<(), anyhow::Error>(err).log_err();
13193
13194                    if let Some(workspace) = workspace {
13195                        workspace
13196                            .update_in(&mut cx, |workspace, _, cx| {
13197                                struct CopyPermalinkToLine;
13198
13199                                workspace.show_toast(
13200                                    Toast::new(
13201                                        NotificationId::unique::<CopyPermalinkToLine>(),
13202                                        message,
13203                                    ),
13204                                    cx,
13205                                )
13206                            })
13207                            .ok();
13208                    }
13209                }
13210            }
13211        })
13212        .detach();
13213    }
13214
13215    pub fn copy_file_location(
13216        &mut self,
13217        _: &CopyFileLocation,
13218        _: &mut Window,
13219        cx: &mut Context<Self>,
13220    ) {
13221        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13222        if let Some(file) = self.target_file(cx) {
13223            if let Some(path) = file.path().to_str() {
13224                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13225            }
13226        }
13227    }
13228
13229    pub fn open_permalink_to_line(
13230        &mut self,
13231        _: &OpenPermalinkToLine,
13232        window: &mut Window,
13233        cx: &mut Context<Self>,
13234    ) {
13235        let permalink_task = self.get_permalink_to_line(cx);
13236        let workspace = self.workspace();
13237
13238        cx.spawn_in(window, |_, mut cx| async move {
13239            match permalink_task.await {
13240                Ok(permalink) => {
13241                    cx.update(|_, cx| {
13242                        cx.open_url(permalink.as_ref());
13243                    })
13244                    .ok();
13245                }
13246                Err(err) => {
13247                    let message = format!("Failed to open permalink: {err}");
13248
13249                    Err::<(), anyhow::Error>(err).log_err();
13250
13251                    if let Some(workspace) = workspace {
13252                        workspace
13253                            .update(&mut cx, |workspace, cx| {
13254                                struct OpenPermalinkToLine;
13255
13256                                workspace.show_toast(
13257                                    Toast::new(
13258                                        NotificationId::unique::<OpenPermalinkToLine>(),
13259                                        message,
13260                                    ),
13261                                    cx,
13262                                )
13263                            })
13264                            .ok();
13265                    }
13266                }
13267            }
13268        })
13269        .detach();
13270    }
13271
13272    pub fn insert_uuid_v4(
13273        &mut self,
13274        _: &InsertUuidV4,
13275        window: &mut Window,
13276        cx: &mut Context<Self>,
13277    ) {
13278        self.insert_uuid(UuidVersion::V4, window, cx);
13279    }
13280
13281    pub fn insert_uuid_v7(
13282        &mut self,
13283        _: &InsertUuidV7,
13284        window: &mut Window,
13285        cx: &mut Context<Self>,
13286    ) {
13287        self.insert_uuid(UuidVersion::V7, window, cx);
13288    }
13289
13290    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13291        self.transact(window, cx, |this, window, cx| {
13292            let edits = this
13293                .selections
13294                .all::<Point>(cx)
13295                .into_iter()
13296                .map(|selection| {
13297                    let uuid = match version {
13298                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13299                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13300                    };
13301
13302                    (selection.range(), uuid.to_string())
13303                });
13304            this.edit(edits, cx);
13305            this.refresh_inline_completion(true, false, window, cx);
13306        });
13307    }
13308
13309    pub fn open_selections_in_multibuffer(
13310        &mut self,
13311        _: &OpenSelectionsInMultibuffer,
13312        window: &mut Window,
13313        cx: &mut Context<Self>,
13314    ) {
13315        let multibuffer = self.buffer.read(cx);
13316
13317        let Some(buffer) = multibuffer.as_singleton() else {
13318            return;
13319        };
13320
13321        let Some(workspace) = self.workspace() else {
13322            return;
13323        };
13324
13325        let locations = self
13326            .selections
13327            .disjoint_anchors()
13328            .iter()
13329            .map(|range| Location {
13330                buffer: buffer.clone(),
13331                range: range.start.text_anchor..range.end.text_anchor,
13332            })
13333            .collect::<Vec<_>>();
13334
13335        let title = multibuffer.title(cx).to_string();
13336
13337        cx.spawn_in(window, |_, mut cx| async move {
13338            workspace.update_in(&mut cx, |workspace, window, cx| {
13339                Self::open_locations_in_multibuffer(
13340                    workspace,
13341                    locations,
13342                    format!("Selections for '{title}'"),
13343                    false,
13344                    MultibufferSelectionMode::All,
13345                    window,
13346                    cx,
13347                );
13348            })
13349        })
13350        .detach();
13351    }
13352
13353    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13354    /// last highlight added will be used.
13355    ///
13356    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13357    pub fn highlight_rows<T: 'static>(
13358        &mut self,
13359        range: Range<Anchor>,
13360        color: Hsla,
13361        should_autoscroll: bool,
13362        cx: &mut Context<Self>,
13363    ) {
13364        let snapshot = self.buffer().read(cx).snapshot(cx);
13365        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13366        let ix = row_highlights.binary_search_by(|highlight| {
13367            Ordering::Equal
13368                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13369                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13370        });
13371
13372        if let Err(mut ix) = ix {
13373            let index = post_inc(&mut self.highlight_order);
13374
13375            // If this range intersects with the preceding highlight, then merge it with
13376            // the preceding highlight. Otherwise insert a new highlight.
13377            let mut merged = false;
13378            if ix > 0 {
13379                let prev_highlight = &mut row_highlights[ix - 1];
13380                if prev_highlight
13381                    .range
13382                    .end
13383                    .cmp(&range.start, &snapshot)
13384                    .is_ge()
13385                {
13386                    ix -= 1;
13387                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13388                        prev_highlight.range.end = range.end;
13389                    }
13390                    merged = true;
13391                    prev_highlight.index = index;
13392                    prev_highlight.color = color;
13393                    prev_highlight.should_autoscroll = should_autoscroll;
13394                }
13395            }
13396
13397            if !merged {
13398                row_highlights.insert(
13399                    ix,
13400                    RowHighlight {
13401                        range: range.clone(),
13402                        index,
13403                        color,
13404                        should_autoscroll,
13405                    },
13406                );
13407            }
13408
13409            // If any of the following highlights intersect with this one, merge them.
13410            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13411                let highlight = &row_highlights[ix];
13412                if next_highlight
13413                    .range
13414                    .start
13415                    .cmp(&highlight.range.end, &snapshot)
13416                    .is_le()
13417                {
13418                    if next_highlight
13419                        .range
13420                        .end
13421                        .cmp(&highlight.range.end, &snapshot)
13422                        .is_gt()
13423                    {
13424                        row_highlights[ix].range.end = next_highlight.range.end;
13425                    }
13426                    row_highlights.remove(ix + 1);
13427                } else {
13428                    break;
13429                }
13430            }
13431        }
13432    }
13433
13434    /// Remove any highlighted row ranges of the given type that intersect the
13435    /// given ranges.
13436    pub fn remove_highlighted_rows<T: 'static>(
13437        &mut self,
13438        ranges_to_remove: Vec<Range<Anchor>>,
13439        cx: &mut Context<Self>,
13440    ) {
13441        let snapshot = self.buffer().read(cx).snapshot(cx);
13442        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13443        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13444        row_highlights.retain(|highlight| {
13445            while let Some(range_to_remove) = ranges_to_remove.peek() {
13446                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13447                    Ordering::Less | Ordering::Equal => {
13448                        ranges_to_remove.next();
13449                    }
13450                    Ordering::Greater => {
13451                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13452                            Ordering::Less | Ordering::Equal => {
13453                                return false;
13454                            }
13455                            Ordering::Greater => break,
13456                        }
13457                    }
13458                }
13459            }
13460
13461            true
13462        })
13463    }
13464
13465    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13466    pub fn clear_row_highlights<T: 'static>(&mut self) {
13467        self.highlighted_rows.remove(&TypeId::of::<T>());
13468    }
13469
13470    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13471    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13472        self.highlighted_rows
13473            .get(&TypeId::of::<T>())
13474            .map_or(&[] as &[_], |vec| vec.as_slice())
13475            .iter()
13476            .map(|highlight| (highlight.range.clone(), highlight.color))
13477    }
13478
13479    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13480    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13481    /// Allows to ignore certain kinds of highlights.
13482    pub fn highlighted_display_rows(
13483        &self,
13484        window: &mut Window,
13485        cx: &mut App,
13486    ) -> BTreeMap<DisplayRow, Background> {
13487        let snapshot = self.snapshot(window, cx);
13488        let mut used_highlight_orders = HashMap::default();
13489        self.highlighted_rows
13490            .iter()
13491            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13492            .fold(
13493                BTreeMap::<DisplayRow, Background>::new(),
13494                |mut unique_rows, highlight| {
13495                    let start = highlight.range.start.to_display_point(&snapshot);
13496                    let end = highlight.range.end.to_display_point(&snapshot);
13497                    let start_row = start.row().0;
13498                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13499                        && end.column() == 0
13500                    {
13501                        end.row().0.saturating_sub(1)
13502                    } else {
13503                        end.row().0
13504                    };
13505                    for row in start_row..=end_row {
13506                        let used_index =
13507                            used_highlight_orders.entry(row).or_insert(highlight.index);
13508                        if highlight.index >= *used_index {
13509                            *used_index = highlight.index;
13510                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13511                        }
13512                    }
13513                    unique_rows
13514                },
13515            )
13516    }
13517
13518    pub fn highlighted_display_row_for_autoscroll(
13519        &self,
13520        snapshot: &DisplaySnapshot,
13521    ) -> Option<DisplayRow> {
13522        self.highlighted_rows
13523            .values()
13524            .flat_map(|highlighted_rows| highlighted_rows.iter())
13525            .filter_map(|highlight| {
13526                if highlight.should_autoscroll {
13527                    Some(highlight.range.start.to_display_point(snapshot).row())
13528                } else {
13529                    None
13530                }
13531            })
13532            .min()
13533    }
13534
13535    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13536        self.highlight_background::<SearchWithinRange>(
13537            ranges,
13538            |colors| colors.editor_document_highlight_read_background,
13539            cx,
13540        )
13541    }
13542
13543    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13544        self.breadcrumb_header = Some(new_header);
13545    }
13546
13547    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13548        self.clear_background_highlights::<SearchWithinRange>(cx);
13549    }
13550
13551    pub fn highlight_background<T: 'static>(
13552        &mut self,
13553        ranges: &[Range<Anchor>],
13554        color_fetcher: fn(&ThemeColors) -> Hsla,
13555        cx: &mut Context<Self>,
13556    ) {
13557        self.background_highlights
13558            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13559        self.scrollbar_marker_state.dirty = true;
13560        cx.notify();
13561    }
13562
13563    pub fn clear_background_highlights<T: 'static>(
13564        &mut self,
13565        cx: &mut Context<Self>,
13566    ) -> Option<BackgroundHighlight> {
13567        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13568        if !text_highlights.1.is_empty() {
13569            self.scrollbar_marker_state.dirty = true;
13570            cx.notify();
13571        }
13572        Some(text_highlights)
13573    }
13574
13575    pub fn highlight_gutter<T: 'static>(
13576        &mut self,
13577        ranges: &[Range<Anchor>],
13578        color_fetcher: fn(&App) -> Hsla,
13579        cx: &mut Context<Self>,
13580    ) {
13581        self.gutter_highlights
13582            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13583        cx.notify();
13584    }
13585
13586    pub fn clear_gutter_highlights<T: 'static>(
13587        &mut self,
13588        cx: &mut Context<Self>,
13589    ) -> Option<GutterHighlight> {
13590        cx.notify();
13591        self.gutter_highlights.remove(&TypeId::of::<T>())
13592    }
13593
13594    #[cfg(feature = "test-support")]
13595    pub fn all_text_background_highlights(
13596        &self,
13597        window: &mut Window,
13598        cx: &mut Context<Self>,
13599    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13600        let snapshot = self.snapshot(window, cx);
13601        let buffer = &snapshot.buffer_snapshot;
13602        let start = buffer.anchor_before(0);
13603        let end = buffer.anchor_after(buffer.len());
13604        let theme = cx.theme().colors();
13605        self.background_highlights_in_range(start..end, &snapshot, theme)
13606    }
13607
13608    #[cfg(feature = "test-support")]
13609    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13610        let snapshot = self.buffer().read(cx).snapshot(cx);
13611
13612        let highlights = self
13613            .background_highlights
13614            .get(&TypeId::of::<items::BufferSearchHighlights>());
13615
13616        if let Some((_color, ranges)) = highlights {
13617            ranges
13618                .iter()
13619                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13620                .collect_vec()
13621        } else {
13622            vec![]
13623        }
13624    }
13625
13626    fn document_highlights_for_position<'a>(
13627        &'a self,
13628        position: Anchor,
13629        buffer: &'a MultiBufferSnapshot,
13630    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13631        let read_highlights = self
13632            .background_highlights
13633            .get(&TypeId::of::<DocumentHighlightRead>())
13634            .map(|h| &h.1);
13635        let write_highlights = self
13636            .background_highlights
13637            .get(&TypeId::of::<DocumentHighlightWrite>())
13638            .map(|h| &h.1);
13639        let left_position = position.bias_left(buffer);
13640        let right_position = position.bias_right(buffer);
13641        read_highlights
13642            .into_iter()
13643            .chain(write_highlights)
13644            .flat_map(move |ranges| {
13645                let start_ix = match ranges.binary_search_by(|probe| {
13646                    let cmp = probe.end.cmp(&left_position, buffer);
13647                    if cmp.is_ge() {
13648                        Ordering::Greater
13649                    } else {
13650                        Ordering::Less
13651                    }
13652                }) {
13653                    Ok(i) | Err(i) => i,
13654                };
13655
13656                ranges[start_ix..]
13657                    .iter()
13658                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13659            })
13660    }
13661
13662    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13663        self.background_highlights
13664            .get(&TypeId::of::<T>())
13665            .map_or(false, |(_, highlights)| !highlights.is_empty())
13666    }
13667
13668    pub fn background_highlights_in_range(
13669        &self,
13670        search_range: Range<Anchor>,
13671        display_snapshot: &DisplaySnapshot,
13672        theme: &ThemeColors,
13673    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13674        let mut results = Vec::new();
13675        for (color_fetcher, ranges) in self.background_highlights.values() {
13676            let color = color_fetcher(theme);
13677            let start_ix = match ranges.binary_search_by(|probe| {
13678                let cmp = probe
13679                    .end
13680                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13681                if cmp.is_gt() {
13682                    Ordering::Greater
13683                } else {
13684                    Ordering::Less
13685                }
13686            }) {
13687                Ok(i) | Err(i) => i,
13688            };
13689            for range in &ranges[start_ix..] {
13690                if range
13691                    .start
13692                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13693                    .is_ge()
13694                {
13695                    break;
13696                }
13697
13698                let start = range.start.to_display_point(display_snapshot);
13699                let end = range.end.to_display_point(display_snapshot);
13700                results.push((start..end, color))
13701            }
13702        }
13703        results
13704    }
13705
13706    pub fn background_highlight_row_ranges<T: 'static>(
13707        &self,
13708        search_range: Range<Anchor>,
13709        display_snapshot: &DisplaySnapshot,
13710        count: usize,
13711    ) -> Vec<RangeInclusive<DisplayPoint>> {
13712        let mut results = Vec::new();
13713        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13714            return vec![];
13715        };
13716
13717        let start_ix = match ranges.binary_search_by(|probe| {
13718            let cmp = probe
13719                .end
13720                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13721            if cmp.is_gt() {
13722                Ordering::Greater
13723            } else {
13724                Ordering::Less
13725            }
13726        }) {
13727            Ok(i) | Err(i) => i,
13728        };
13729        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13730            if let (Some(start_display), Some(end_display)) = (start, end) {
13731                results.push(
13732                    start_display.to_display_point(display_snapshot)
13733                        ..=end_display.to_display_point(display_snapshot),
13734                );
13735            }
13736        };
13737        let mut start_row: Option<Point> = None;
13738        let mut end_row: Option<Point> = None;
13739        if ranges.len() > count {
13740            return Vec::new();
13741        }
13742        for range in &ranges[start_ix..] {
13743            if range
13744                .start
13745                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13746                .is_ge()
13747            {
13748                break;
13749            }
13750            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13751            if let Some(current_row) = &end_row {
13752                if end.row == current_row.row {
13753                    continue;
13754                }
13755            }
13756            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13757            if start_row.is_none() {
13758                assert_eq!(end_row, None);
13759                start_row = Some(start);
13760                end_row = Some(end);
13761                continue;
13762            }
13763            if let Some(current_end) = end_row.as_mut() {
13764                if start.row > current_end.row + 1 {
13765                    push_region(start_row, end_row);
13766                    start_row = Some(start);
13767                    end_row = Some(end);
13768                } else {
13769                    // Merge two hunks.
13770                    *current_end = end;
13771                }
13772            } else {
13773                unreachable!();
13774            }
13775        }
13776        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13777        push_region(start_row, end_row);
13778        results
13779    }
13780
13781    pub fn gutter_highlights_in_range(
13782        &self,
13783        search_range: Range<Anchor>,
13784        display_snapshot: &DisplaySnapshot,
13785        cx: &App,
13786    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13787        let mut results = Vec::new();
13788        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13789            let color = color_fetcher(cx);
13790            let start_ix = match ranges.binary_search_by(|probe| {
13791                let cmp = probe
13792                    .end
13793                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13794                if cmp.is_gt() {
13795                    Ordering::Greater
13796                } else {
13797                    Ordering::Less
13798                }
13799            }) {
13800                Ok(i) | Err(i) => i,
13801            };
13802            for range in &ranges[start_ix..] {
13803                if range
13804                    .start
13805                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13806                    .is_ge()
13807                {
13808                    break;
13809                }
13810
13811                let start = range.start.to_display_point(display_snapshot);
13812                let end = range.end.to_display_point(display_snapshot);
13813                results.push((start..end, color))
13814            }
13815        }
13816        results
13817    }
13818
13819    /// Get the text ranges corresponding to the redaction query
13820    pub fn redacted_ranges(
13821        &self,
13822        search_range: Range<Anchor>,
13823        display_snapshot: &DisplaySnapshot,
13824        cx: &App,
13825    ) -> Vec<Range<DisplayPoint>> {
13826        display_snapshot
13827            .buffer_snapshot
13828            .redacted_ranges(search_range, |file| {
13829                if let Some(file) = file {
13830                    file.is_private()
13831                        && EditorSettings::get(
13832                            Some(SettingsLocation {
13833                                worktree_id: file.worktree_id(cx),
13834                                path: file.path().as_ref(),
13835                            }),
13836                            cx,
13837                        )
13838                        .redact_private_values
13839                } else {
13840                    false
13841                }
13842            })
13843            .map(|range| {
13844                range.start.to_display_point(display_snapshot)
13845                    ..range.end.to_display_point(display_snapshot)
13846            })
13847            .collect()
13848    }
13849
13850    pub fn highlight_text<T: 'static>(
13851        &mut self,
13852        ranges: Vec<Range<Anchor>>,
13853        style: HighlightStyle,
13854        cx: &mut Context<Self>,
13855    ) {
13856        self.display_map.update(cx, |map, _| {
13857            map.highlight_text(TypeId::of::<T>(), ranges, style)
13858        });
13859        cx.notify();
13860    }
13861
13862    pub(crate) fn highlight_inlays<T: 'static>(
13863        &mut self,
13864        highlights: Vec<InlayHighlight>,
13865        style: HighlightStyle,
13866        cx: &mut Context<Self>,
13867    ) {
13868        self.display_map.update(cx, |map, _| {
13869            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13870        });
13871        cx.notify();
13872    }
13873
13874    pub fn text_highlights<'a, T: 'static>(
13875        &'a self,
13876        cx: &'a App,
13877    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13878        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13879    }
13880
13881    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13882        let cleared = self
13883            .display_map
13884            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13885        if cleared {
13886            cx.notify();
13887        }
13888    }
13889
13890    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13891        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13892            && self.focus_handle.is_focused(window)
13893    }
13894
13895    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13896        self.show_cursor_when_unfocused = is_enabled;
13897        cx.notify();
13898    }
13899
13900    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13901        self.project
13902            .as_ref()
13903            .map(|project| project.read(cx).lsp_store())
13904    }
13905
13906    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13907        cx.notify();
13908    }
13909
13910    fn on_buffer_event(
13911        &mut self,
13912        multibuffer: &Entity<MultiBuffer>,
13913        event: &multi_buffer::Event,
13914        window: &mut Window,
13915        cx: &mut Context<Self>,
13916    ) {
13917        match event {
13918            multi_buffer::Event::Edited {
13919                singleton_buffer_edited,
13920                edited_buffer: buffer_edited,
13921            } => {
13922                self.scrollbar_marker_state.dirty = true;
13923                self.active_indent_guides_state.dirty = true;
13924                self.refresh_active_diagnostics(cx);
13925                self.refresh_code_actions(window, cx);
13926                if self.has_active_inline_completion() {
13927                    self.update_visible_inline_completion(window, cx);
13928                }
13929                if let Some(buffer) = buffer_edited {
13930                    let buffer_id = buffer.read(cx).remote_id();
13931                    if !self.registered_buffers.contains_key(&buffer_id) {
13932                        if let Some(lsp_store) = self.lsp_store(cx) {
13933                            lsp_store.update(cx, |lsp_store, cx| {
13934                                self.registered_buffers.insert(
13935                                    buffer_id,
13936                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13937                                );
13938                            })
13939                        }
13940                    }
13941                }
13942                cx.emit(EditorEvent::BufferEdited);
13943                cx.emit(SearchEvent::MatchesInvalidated);
13944                if *singleton_buffer_edited {
13945                    if let Some(project) = &self.project {
13946                        let project = project.read(cx);
13947                        #[allow(clippy::mutable_key_type)]
13948                        let languages_affected = multibuffer
13949                            .read(cx)
13950                            .all_buffers()
13951                            .into_iter()
13952                            .filter_map(|buffer| {
13953                                let buffer = buffer.read(cx);
13954                                let language = buffer.language()?;
13955                                if project.is_local()
13956                                    && project
13957                                        .language_servers_for_local_buffer(buffer, cx)
13958                                        .count()
13959                                        == 0
13960                                {
13961                                    None
13962                                } else {
13963                                    Some(language)
13964                                }
13965                            })
13966                            .cloned()
13967                            .collect::<HashSet<_>>();
13968                        if !languages_affected.is_empty() {
13969                            self.refresh_inlay_hints(
13970                                InlayHintRefreshReason::BufferEdited(languages_affected),
13971                                cx,
13972                            );
13973                        }
13974                    }
13975                }
13976
13977                let Some(project) = &self.project else { return };
13978                let (telemetry, is_via_ssh) = {
13979                    let project = project.read(cx);
13980                    let telemetry = project.client().telemetry().clone();
13981                    let is_via_ssh = project.is_via_ssh();
13982                    (telemetry, is_via_ssh)
13983                };
13984                refresh_linked_ranges(self, window, cx);
13985                telemetry.log_edit_event("editor", is_via_ssh);
13986            }
13987            multi_buffer::Event::ExcerptsAdded {
13988                buffer,
13989                predecessor,
13990                excerpts,
13991            } => {
13992                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13993                let buffer_id = buffer.read(cx).remote_id();
13994                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13995                    if let Some(project) = &self.project {
13996                        get_uncommitted_diff_for_buffer(
13997                            project,
13998                            [buffer.clone()],
13999                            self.buffer.clone(),
14000                            cx,
14001                        );
14002                    }
14003                }
14004                cx.emit(EditorEvent::ExcerptsAdded {
14005                    buffer: buffer.clone(),
14006                    predecessor: *predecessor,
14007                    excerpts: excerpts.clone(),
14008                });
14009                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14010            }
14011            multi_buffer::Event::ExcerptsRemoved { ids } => {
14012                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14013                let buffer = self.buffer.read(cx);
14014                self.registered_buffers
14015                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14016                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14017            }
14018            multi_buffer::Event::ExcerptsEdited { ids } => {
14019                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14020            }
14021            multi_buffer::Event::ExcerptsExpanded { ids } => {
14022                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14023                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14024            }
14025            multi_buffer::Event::Reparsed(buffer_id) => {
14026                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14027
14028                cx.emit(EditorEvent::Reparsed(*buffer_id));
14029            }
14030            multi_buffer::Event::DiffHunksToggled => {
14031                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14032            }
14033            multi_buffer::Event::LanguageChanged(buffer_id) => {
14034                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14035                cx.emit(EditorEvent::Reparsed(*buffer_id));
14036                cx.notify();
14037            }
14038            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14039            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14040            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14041                cx.emit(EditorEvent::TitleChanged)
14042            }
14043            // multi_buffer::Event::DiffBaseChanged => {
14044            //     self.scrollbar_marker_state.dirty = true;
14045            //     cx.emit(EditorEvent::DiffBaseChanged);
14046            //     cx.notify();
14047            // }
14048            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14049            multi_buffer::Event::DiagnosticsUpdated => {
14050                self.refresh_active_diagnostics(cx);
14051                self.scrollbar_marker_state.dirty = true;
14052                cx.notify();
14053            }
14054            _ => {}
14055        };
14056    }
14057
14058    fn on_display_map_changed(
14059        &mut self,
14060        _: Entity<DisplayMap>,
14061        _: &mut Window,
14062        cx: &mut Context<Self>,
14063    ) {
14064        cx.notify();
14065    }
14066
14067    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14068        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14069        self.refresh_inline_completion(true, false, window, cx);
14070        self.refresh_inlay_hints(
14071            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14072                self.selections.newest_anchor().head(),
14073                &self.buffer.read(cx).snapshot(cx),
14074                cx,
14075            )),
14076            cx,
14077        );
14078
14079        let old_cursor_shape = self.cursor_shape;
14080
14081        {
14082            let editor_settings = EditorSettings::get_global(cx);
14083            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14084            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14085            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14086        }
14087
14088        if old_cursor_shape != self.cursor_shape {
14089            cx.emit(EditorEvent::CursorShapeChanged);
14090        }
14091
14092        let project_settings = ProjectSettings::get_global(cx);
14093        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14094
14095        if self.mode == EditorMode::Full {
14096            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14097            if self.git_blame_inline_enabled != inline_blame_enabled {
14098                self.toggle_git_blame_inline_internal(false, window, cx);
14099            }
14100        }
14101
14102        cx.notify();
14103    }
14104
14105    pub fn set_searchable(&mut self, searchable: bool) {
14106        self.searchable = searchable;
14107    }
14108
14109    pub fn searchable(&self) -> bool {
14110        self.searchable
14111    }
14112
14113    fn open_proposed_changes_editor(
14114        &mut self,
14115        _: &OpenProposedChangesEditor,
14116        window: &mut Window,
14117        cx: &mut Context<Self>,
14118    ) {
14119        let Some(workspace) = self.workspace() else {
14120            cx.propagate();
14121            return;
14122        };
14123
14124        let selections = self.selections.all::<usize>(cx);
14125        let multi_buffer = self.buffer.read(cx);
14126        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14127        let mut new_selections_by_buffer = HashMap::default();
14128        for selection in selections {
14129            for (buffer, range, _) in
14130                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14131            {
14132                let mut range = range.to_point(buffer);
14133                range.start.column = 0;
14134                range.end.column = buffer.line_len(range.end.row);
14135                new_selections_by_buffer
14136                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14137                    .or_insert(Vec::new())
14138                    .push(range)
14139            }
14140        }
14141
14142        let proposed_changes_buffers = new_selections_by_buffer
14143            .into_iter()
14144            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14145            .collect::<Vec<_>>();
14146        let proposed_changes_editor = cx.new(|cx| {
14147            ProposedChangesEditor::new(
14148                "Proposed changes",
14149                proposed_changes_buffers,
14150                self.project.clone(),
14151                window,
14152                cx,
14153            )
14154        });
14155
14156        window.defer(cx, move |window, cx| {
14157            workspace.update(cx, |workspace, cx| {
14158                workspace.active_pane().update(cx, |pane, cx| {
14159                    pane.add_item(
14160                        Box::new(proposed_changes_editor),
14161                        true,
14162                        true,
14163                        None,
14164                        window,
14165                        cx,
14166                    );
14167                });
14168            });
14169        });
14170    }
14171
14172    pub fn open_excerpts_in_split(
14173        &mut self,
14174        _: &OpenExcerptsSplit,
14175        window: &mut Window,
14176        cx: &mut Context<Self>,
14177    ) {
14178        self.open_excerpts_common(None, true, window, cx)
14179    }
14180
14181    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14182        self.open_excerpts_common(None, false, window, cx)
14183    }
14184
14185    fn open_excerpts_common(
14186        &mut self,
14187        jump_data: Option<JumpData>,
14188        split: bool,
14189        window: &mut Window,
14190        cx: &mut Context<Self>,
14191    ) {
14192        let Some(workspace) = self.workspace() else {
14193            cx.propagate();
14194            return;
14195        };
14196
14197        if self.buffer.read(cx).is_singleton() {
14198            cx.propagate();
14199            return;
14200        }
14201
14202        let mut new_selections_by_buffer = HashMap::default();
14203        match &jump_data {
14204            Some(JumpData::MultiBufferPoint {
14205                excerpt_id,
14206                position,
14207                anchor,
14208                line_offset_from_top,
14209            }) => {
14210                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14211                if let Some(buffer) = multi_buffer_snapshot
14212                    .buffer_id_for_excerpt(*excerpt_id)
14213                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14214                {
14215                    let buffer_snapshot = buffer.read(cx).snapshot();
14216                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14217                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14218                    } else {
14219                        buffer_snapshot.clip_point(*position, Bias::Left)
14220                    };
14221                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14222                    new_selections_by_buffer.insert(
14223                        buffer,
14224                        (
14225                            vec![jump_to_offset..jump_to_offset],
14226                            Some(*line_offset_from_top),
14227                        ),
14228                    );
14229                }
14230            }
14231            Some(JumpData::MultiBufferRow {
14232                row,
14233                line_offset_from_top,
14234            }) => {
14235                let point = MultiBufferPoint::new(row.0, 0);
14236                if let Some((buffer, buffer_point, _)) =
14237                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14238                {
14239                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14240                    new_selections_by_buffer
14241                        .entry(buffer)
14242                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14243                        .0
14244                        .push(buffer_offset..buffer_offset)
14245                }
14246            }
14247            None => {
14248                let selections = self.selections.all::<usize>(cx);
14249                let multi_buffer = self.buffer.read(cx);
14250                for selection in selections {
14251                    for (buffer, mut range, _) in multi_buffer
14252                        .snapshot(cx)
14253                        .range_to_buffer_ranges(selection.range())
14254                    {
14255                        // When editing branch buffers, jump to the corresponding location
14256                        // in their base buffer.
14257                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14258                        let buffer = buffer_handle.read(cx);
14259                        if let Some(base_buffer) = buffer.base_buffer() {
14260                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14261                            buffer_handle = base_buffer;
14262                        }
14263
14264                        if selection.reversed {
14265                            mem::swap(&mut range.start, &mut range.end);
14266                        }
14267                        new_selections_by_buffer
14268                            .entry(buffer_handle)
14269                            .or_insert((Vec::new(), None))
14270                            .0
14271                            .push(range)
14272                    }
14273                }
14274            }
14275        }
14276
14277        if new_selections_by_buffer.is_empty() {
14278            return;
14279        }
14280
14281        // We defer the pane interaction because we ourselves are a workspace item
14282        // and activating a new item causes the pane to call a method on us reentrantly,
14283        // which panics if we're on the stack.
14284        window.defer(cx, move |window, cx| {
14285            workspace.update(cx, |workspace, cx| {
14286                let pane = if split {
14287                    workspace.adjacent_pane(window, cx)
14288                } else {
14289                    workspace.active_pane().clone()
14290                };
14291
14292                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14293                    let editor = buffer
14294                        .read(cx)
14295                        .file()
14296                        .is_none()
14297                        .then(|| {
14298                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14299                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14300                            // Instead, we try to activate the existing editor in the pane first.
14301                            let (editor, pane_item_index) =
14302                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14303                                    let editor = item.downcast::<Editor>()?;
14304                                    let singleton_buffer =
14305                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14306                                    if singleton_buffer == buffer {
14307                                        Some((editor, i))
14308                                    } else {
14309                                        None
14310                                    }
14311                                })?;
14312                            pane.update(cx, |pane, cx| {
14313                                pane.activate_item(pane_item_index, true, true, window, cx)
14314                            });
14315                            Some(editor)
14316                        })
14317                        .flatten()
14318                        .unwrap_or_else(|| {
14319                            workspace.open_project_item::<Self>(
14320                                pane.clone(),
14321                                buffer,
14322                                true,
14323                                true,
14324                                window,
14325                                cx,
14326                            )
14327                        });
14328
14329                    editor.update(cx, |editor, cx| {
14330                        let autoscroll = match scroll_offset {
14331                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14332                            None => Autoscroll::newest(),
14333                        };
14334                        let nav_history = editor.nav_history.take();
14335                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14336                            s.select_ranges(ranges);
14337                        });
14338                        editor.nav_history = nav_history;
14339                    });
14340                }
14341            })
14342        });
14343    }
14344
14345    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14346        let snapshot = self.buffer.read(cx).read(cx);
14347        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14348        Some(
14349            ranges
14350                .iter()
14351                .map(move |range| {
14352                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14353                })
14354                .collect(),
14355        )
14356    }
14357
14358    fn selection_replacement_ranges(
14359        &self,
14360        range: Range<OffsetUtf16>,
14361        cx: &mut App,
14362    ) -> Vec<Range<OffsetUtf16>> {
14363        let selections = self.selections.all::<OffsetUtf16>(cx);
14364        let newest_selection = selections
14365            .iter()
14366            .max_by_key(|selection| selection.id)
14367            .unwrap();
14368        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14369        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14370        let snapshot = self.buffer.read(cx).read(cx);
14371        selections
14372            .into_iter()
14373            .map(|mut selection| {
14374                selection.start.0 =
14375                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14376                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14377                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14378                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14379            })
14380            .collect()
14381    }
14382
14383    fn report_editor_event(
14384        &self,
14385        event_type: &'static str,
14386        file_extension: Option<String>,
14387        cx: &App,
14388    ) {
14389        if cfg!(any(test, feature = "test-support")) {
14390            return;
14391        }
14392
14393        let Some(project) = &self.project else { return };
14394
14395        // If None, we are in a file without an extension
14396        let file = self
14397            .buffer
14398            .read(cx)
14399            .as_singleton()
14400            .and_then(|b| b.read(cx).file());
14401        let file_extension = file_extension.or(file
14402            .as_ref()
14403            .and_then(|file| Path::new(file.file_name(cx)).extension())
14404            .and_then(|e| e.to_str())
14405            .map(|a| a.to_string()));
14406
14407        let vim_mode = cx
14408            .global::<SettingsStore>()
14409            .raw_user_settings()
14410            .get("vim_mode")
14411            == Some(&serde_json::Value::Bool(true));
14412
14413        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14414        let copilot_enabled = edit_predictions_provider
14415            == language::language_settings::EditPredictionProvider::Copilot;
14416        let copilot_enabled_for_language = self
14417            .buffer
14418            .read(cx)
14419            .settings_at(0, cx)
14420            .show_edit_predictions;
14421
14422        let project = project.read(cx);
14423        telemetry::event!(
14424            event_type,
14425            file_extension,
14426            vim_mode,
14427            copilot_enabled,
14428            copilot_enabled_for_language,
14429            edit_predictions_provider,
14430            is_via_ssh = project.is_via_ssh(),
14431        );
14432    }
14433
14434    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14435    /// with each line being an array of {text, highlight} objects.
14436    fn copy_highlight_json(
14437        &mut self,
14438        _: &CopyHighlightJson,
14439        window: &mut Window,
14440        cx: &mut Context<Self>,
14441    ) {
14442        #[derive(Serialize)]
14443        struct Chunk<'a> {
14444            text: String,
14445            highlight: Option<&'a str>,
14446        }
14447
14448        let snapshot = self.buffer.read(cx).snapshot(cx);
14449        let range = self
14450            .selected_text_range(false, window, cx)
14451            .and_then(|selection| {
14452                if selection.range.is_empty() {
14453                    None
14454                } else {
14455                    Some(selection.range)
14456                }
14457            })
14458            .unwrap_or_else(|| 0..snapshot.len());
14459
14460        let chunks = snapshot.chunks(range, true);
14461        let mut lines = Vec::new();
14462        let mut line: VecDeque<Chunk> = VecDeque::new();
14463
14464        let Some(style) = self.style.as_ref() else {
14465            return;
14466        };
14467
14468        for chunk in chunks {
14469            let highlight = chunk
14470                .syntax_highlight_id
14471                .and_then(|id| id.name(&style.syntax));
14472            let mut chunk_lines = chunk.text.split('\n').peekable();
14473            while let Some(text) = chunk_lines.next() {
14474                let mut merged_with_last_token = false;
14475                if let Some(last_token) = line.back_mut() {
14476                    if last_token.highlight == highlight {
14477                        last_token.text.push_str(text);
14478                        merged_with_last_token = true;
14479                    }
14480                }
14481
14482                if !merged_with_last_token {
14483                    line.push_back(Chunk {
14484                        text: text.into(),
14485                        highlight,
14486                    });
14487                }
14488
14489                if chunk_lines.peek().is_some() {
14490                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14491                        line.pop_front();
14492                    }
14493                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14494                        line.pop_back();
14495                    }
14496
14497                    lines.push(mem::take(&mut line));
14498                }
14499            }
14500        }
14501
14502        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14503            return;
14504        };
14505        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14506    }
14507
14508    pub fn open_context_menu(
14509        &mut self,
14510        _: &OpenContextMenu,
14511        window: &mut Window,
14512        cx: &mut Context<Self>,
14513    ) {
14514        self.request_autoscroll(Autoscroll::newest(), cx);
14515        let position = self.selections.newest_display(cx).start;
14516        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14517    }
14518
14519    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14520        &self.inlay_hint_cache
14521    }
14522
14523    pub fn replay_insert_event(
14524        &mut self,
14525        text: &str,
14526        relative_utf16_range: Option<Range<isize>>,
14527        window: &mut Window,
14528        cx: &mut Context<Self>,
14529    ) {
14530        if !self.input_enabled {
14531            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14532            return;
14533        }
14534        if let Some(relative_utf16_range) = relative_utf16_range {
14535            let selections = self.selections.all::<OffsetUtf16>(cx);
14536            self.change_selections(None, window, cx, |s| {
14537                let new_ranges = selections.into_iter().map(|range| {
14538                    let start = OffsetUtf16(
14539                        range
14540                            .head()
14541                            .0
14542                            .saturating_add_signed(relative_utf16_range.start),
14543                    );
14544                    let end = OffsetUtf16(
14545                        range
14546                            .head()
14547                            .0
14548                            .saturating_add_signed(relative_utf16_range.end),
14549                    );
14550                    start..end
14551                });
14552                s.select_ranges(new_ranges);
14553            });
14554        }
14555
14556        self.handle_input(text, window, cx);
14557    }
14558
14559    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14560        let Some(provider) = self.semantics_provider.as_ref() else {
14561            return false;
14562        };
14563
14564        let mut supports = false;
14565        self.buffer().read(cx).for_each_buffer(|buffer| {
14566            supports |= provider.supports_inlay_hints(buffer, cx);
14567        });
14568        supports
14569    }
14570
14571    pub fn is_focused(&self, window: &Window) -> bool {
14572        self.focus_handle.is_focused(window)
14573    }
14574
14575    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14576        cx.emit(EditorEvent::Focused);
14577
14578        if let Some(descendant) = self
14579            .last_focused_descendant
14580            .take()
14581            .and_then(|descendant| descendant.upgrade())
14582        {
14583            window.focus(&descendant);
14584        } else {
14585            if let Some(blame) = self.blame.as_ref() {
14586                blame.update(cx, GitBlame::focus)
14587            }
14588
14589            self.blink_manager.update(cx, BlinkManager::enable);
14590            self.show_cursor_names(window, cx);
14591            self.buffer.update(cx, |buffer, cx| {
14592                buffer.finalize_last_transaction(cx);
14593                if self.leader_peer_id.is_none() {
14594                    buffer.set_active_selections(
14595                        &self.selections.disjoint_anchors(),
14596                        self.selections.line_mode,
14597                        self.cursor_shape,
14598                        cx,
14599                    );
14600                }
14601            });
14602        }
14603    }
14604
14605    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14606        cx.emit(EditorEvent::FocusedIn)
14607    }
14608
14609    fn handle_focus_out(
14610        &mut self,
14611        event: FocusOutEvent,
14612        _window: &mut Window,
14613        _cx: &mut Context<Self>,
14614    ) {
14615        if event.blurred != self.focus_handle {
14616            self.last_focused_descendant = Some(event.blurred);
14617        }
14618    }
14619
14620    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14621        self.blink_manager.update(cx, BlinkManager::disable);
14622        self.buffer
14623            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14624
14625        if let Some(blame) = self.blame.as_ref() {
14626            blame.update(cx, GitBlame::blur)
14627        }
14628        if !self.hover_state.focused(window, cx) {
14629            hide_hover(self, cx);
14630        }
14631
14632        self.hide_context_menu(window, cx);
14633        self.discard_inline_completion(false, cx);
14634        cx.emit(EditorEvent::Blurred);
14635        cx.notify();
14636    }
14637
14638    pub fn register_action<A: Action>(
14639        &mut self,
14640        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14641    ) -> Subscription {
14642        let id = self.next_editor_action_id.post_inc();
14643        let listener = Arc::new(listener);
14644        self.editor_actions.borrow_mut().insert(
14645            id,
14646            Box::new(move |window, _| {
14647                let listener = listener.clone();
14648                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14649                    let action = action.downcast_ref().unwrap();
14650                    if phase == DispatchPhase::Bubble {
14651                        listener(action, window, cx)
14652                    }
14653                })
14654            }),
14655        );
14656
14657        let editor_actions = self.editor_actions.clone();
14658        Subscription::new(move || {
14659            editor_actions.borrow_mut().remove(&id);
14660        })
14661    }
14662
14663    pub fn file_header_size(&self) -> u32 {
14664        FILE_HEADER_HEIGHT
14665    }
14666
14667    pub fn revert(
14668        &mut self,
14669        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14670        window: &mut Window,
14671        cx: &mut Context<Self>,
14672    ) {
14673        self.buffer().update(cx, |multi_buffer, cx| {
14674            for (buffer_id, changes) in revert_changes {
14675                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14676                    buffer.update(cx, |buffer, cx| {
14677                        buffer.edit(
14678                            changes.into_iter().map(|(range, text)| {
14679                                (range, text.to_string().map(Arc::<str>::from))
14680                            }),
14681                            None,
14682                            cx,
14683                        );
14684                    });
14685                }
14686            }
14687        });
14688        self.change_selections(None, window, cx, |selections| selections.refresh());
14689    }
14690
14691    pub fn to_pixel_point(
14692        &self,
14693        source: multi_buffer::Anchor,
14694        editor_snapshot: &EditorSnapshot,
14695        window: &mut Window,
14696    ) -> Option<gpui::Point<Pixels>> {
14697        let source_point = source.to_display_point(editor_snapshot);
14698        self.display_to_pixel_point(source_point, editor_snapshot, window)
14699    }
14700
14701    pub fn display_to_pixel_point(
14702        &self,
14703        source: DisplayPoint,
14704        editor_snapshot: &EditorSnapshot,
14705        window: &mut Window,
14706    ) -> Option<gpui::Point<Pixels>> {
14707        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14708        let text_layout_details = self.text_layout_details(window);
14709        let scroll_top = text_layout_details
14710            .scroll_anchor
14711            .scroll_position(editor_snapshot)
14712            .y;
14713
14714        if source.row().as_f32() < scroll_top.floor() {
14715            return None;
14716        }
14717        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14718        let source_y = line_height * (source.row().as_f32() - scroll_top);
14719        Some(gpui::Point::new(source_x, source_y))
14720    }
14721
14722    pub fn has_visible_completions_menu(&self) -> bool {
14723        !self.edit_prediction_preview_is_active()
14724            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14725                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14726            })
14727    }
14728
14729    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14730        self.addons
14731            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14732    }
14733
14734    pub fn unregister_addon<T: Addon>(&mut self) {
14735        self.addons.remove(&std::any::TypeId::of::<T>());
14736    }
14737
14738    pub fn addon<T: Addon>(&self) -> Option<&T> {
14739        let type_id = std::any::TypeId::of::<T>();
14740        self.addons
14741            .get(&type_id)
14742            .and_then(|item| item.to_any().downcast_ref::<T>())
14743    }
14744
14745    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14746        let text_layout_details = self.text_layout_details(window);
14747        let style = &text_layout_details.editor_style;
14748        let font_id = window.text_system().resolve_font(&style.text.font());
14749        let font_size = style.text.font_size.to_pixels(window.rem_size());
14750        let line_height = style.text.line_height_in_pixels(window.rem_size());
14751        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14752
14753        gpui::Size::new(em_width, line_height)
14754    }
14755}
14756
14757fn get_uncommitted_diff_for_buffer(
14758    project: &Entity<Project>,
14759    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14760    buffer: Entity<MultiBuffer>,
14761    cx: &mut App,
14762) {
14763    let mut tasks = Vec::new();
14764    project.update(cx, |project, cx| {
14765        for buffer in buffers {
14766            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14767        }
14768    });
14769    cx.spawn(|mut cx| async move {
14770        let diffs = futures::future::join_all(tasks).await;
14771        buffer
14772            .update(&mut cx, |buffer, cx| {
14773                for diff in diffs.into_iter().flatten() {
14774                    buffer.add_diff(diff, cx);
14775                }
14776            })
14777            .ok();
14778    })
14779    .detach();
14780}
14781
14782fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14783    let tab_size = tab_size.get() as usize;
14784    let mut width = offset;
14785
14786    for ch in text.chars() {
14787        width += if ch == '\t' {
14788            tab_size - (width % tab_size)
14789        } else {
14790            1
14791        };
14792    }
14793
14794    width - offset
14795}
14796
14797#[cfg(test)]
14798mod tests {
14799    use super::*;
14800
14801    #[test]
14802    fn test_string_size_with_expanded_tabs() {
14803        let nz = |val| NonZeroU32::new(val).unwrap();
14804        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14805        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14806        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14807        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14808        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14809        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14810        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14811        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14812    }
14813}
14814
14815/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14816struct WordBreakingTokenizer<'a> {
14817    input: &'a str,
14818}
14819
14820impl<'a> WordBreakingTokenizer<'a> {
14821    fn new(input: &'a str) -> Self {
14822        Self { input }
14823    }
14824}
14825
14826fn is_char_ideographic(ch: char) -> bool {
14827    use unicode_script::Script::*;
14828    use unicode_script::UnicodeScript;
14829    matches!(ch.script(), Han | Tangut | Yi)
14830}
14831
14832fn is_grapheme_ideographic(text: &str) -> bool {
14833    text.chars().any(is_char_ideographic)
14834}
14835
14836fn is_grapheme_whitespace(text: &str) -> bool {
14837    text.chars().any(|x| x.is_whitespace())
14838}
14839
14840fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14841    text.chars().next().map_or(false, |ch| {
14842        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14843    })
14844}
14845
14846#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14847struct WordBreakToken<'a> {
14848    token: &'a str,
14849    grapheme_len: usize,
14850    is_whitespace: bool,
14851}
14852
14853impl<'a> Iterator for WordBreakingTokenizer<'a> {
14854    /// Yields a span, the count of graphemes in the token, and whether it was
14855    /// whitespace. Note that it also breaks at word boundaries.
14856    type Item = WordBreakToken<'a>;
14857
14858    fn next(&mut self) -> Option<Self::Item> {
14859        use unicode_segmentation::UnicodeSegmentation;
14860        if self.input.is_empty() {
14861            return None;
14862        }
14863
14864        let mut iter = self.input.graphemes(true).peekable();
14865        let mut offset = 0;
14866        let mut graphemes = 0;
14867        if let Some(first_grapheme) = iter.next() {
14868            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14869            offset += first_grapheme.len();
14870            graphemes += 1;
14871            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14872                if let Some(grapheme) = iter.peek().copied() {
14873                    if should_stay_with_preceding_ideograph(grapheme) {
14874                        offset += grapheme.len();
14875                        graphemes += 1;
14876                    }
14877                }
14878            } else {
14879                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14880                let mut next_word_bound = words.peek().copied();
14881                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14882                    next_word_bound = words.next();
14883                }
14884                while let Some(grapheme) = iter.peek().copied() {
14885                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14886                        break;
14887                    };
14888                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14889                        break;
14890                    };
14891                    offset += grapheme.len();
14892                    graphemes += 1;
14893                    iter.next();
14894                }
14895            }
14896            let token = &self.input[..offset];
14897            self.input = &self.input[offset..];
14898            if is_whitespace {
14899                Some(WordBreakToken {
14900                    token: " ",
14901                    grapheme_len: 1,
14902                    is_whitespace: true,
14903                })
14904            } else {
14905                Some(WordBreakToken {
14906                    token,
14907                    grapheme_len: graphemes,
14908                    is_whitespace: false,
14909                })
14910            }
14911        } else {
14912            None
14913        }
14914    }
14915}
14916
14917#[test]
14918fn test_word_breaking_tokenizer() {
14919    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14920        ("", &[]),
14921        ("  ", &[(" ", 1, true)]),
14922        ("Ʒ", &[("Ʒ", 1, false)]),
14923        ("Ǽ", &[("Ǽ", 1, false)]),
14924        ("", &[("", 1, false)]),
14925        ("⋑⋑", &[("⋑⋑", 2, false)]),
14926        (
14927            "原理,进而",
14928            &[
14929                ("", 1, false),
14930                ("理,", 2, false),
14931                ("", 1, false),
14932                ("", 1, false),
14933            ],
14934        ),
14935        (
14936            "hello world",
14937            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14938        ),
14939        (
14940            "hello, world",
14941            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14942        ),
14943        (
14944            "  hello world",
14945            &[
14946                (" ", 1, true),
14947                ("hello", 5, false),
14948                (" ", 1, true),
14949                ("world", 5, false),
14950            ],
14951        ),
14952        (
14953            "这是什么 \n 钢笔",
14954            &[
14955                ("", 1, false),
14956                ("", 1, false),
14957                ("", 1, false),
14958                ("", 1, false),
14959                (" ", 1, true),
14960                ("", 1, false),
14961                ("", 1, false),
14962            ],
14963        ),
14964        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14965    ];
14966
14967    for (input, result) in tests {
14968        assert_eq!(
14969            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14970            result
14971                .iter()
14972                .copied()
14973                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14974                    token,
14975                    grapheme_len,
14976                    is_whitespace,
14977                })
14978                .collect::<Vec<_>>()
14979        );
14980    }
14981}
14982
14983fn wrap_with_prefix(
14984    line_prefix: String,
14985    unwrapped_text: String,
14986    wrap_column: usize,
14987    tab_size: NonZeroU32,
14988) -> String {
14989    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14990    let mut wrapped_text = String::new();
14991    let mut current_line = line_prefix.clone();
14992
14993    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14994    let mut current_line_len = line_prefix_len;
14995    for WordBreakToken {
14996        token,
14997        grapheme_len,
14998        is_whitespace,
14999    } in tokenizer
15000    {
15001        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15002            wrapped_text.push_str(current_line.trim_end());
15003            wrapped_text.push('\n');
15004            current_line.truncate(line_prefix.len());
15005            current_line_len = line_prefix_len;
15006            if !is_whitespace {
15007                current_line.push_str(token);
15008                current_line_len += grapheme_len;
15009            }
15010        } else if !is_whitespace {
15011            current_line.push_str(token);
15012            current_line_len += grapheme_len;
15013        } else if current_line_len != line_prefix_len {
15014            current_line.push(' ');
15015            current_line_len += 1;
15016        }
15017    }
15018
15019    if !current_line.is_empty() {
15020        wrapped_text.push_str(&current_line);
15021    }
15022    wrapped_text
15023}
15024
15025#[test]
15026fn test_wrap_with_prefix() {
15027    assert_eq!(
15028        wrap_with_prefix(
15029            "# ".to_string(),
15030            "abcdefg".to_string(),
15031            4,
15032            NonZeroU32::new(4).unwrap()
15033        ),
15034        "# abcdefg"
15035    );
15036    assert_eq!(
15037        wrap_with_prefix(
15038            "".to_string(),
15039            "\thello world".to_string(),
15040            8,
15041            NonZeroU32::new(4).unwrap()
15042        ),
15043        "hello\nworld"
15044    );
15045    assert_eq!(
15046        wrap_with_prefix(
15047            "// ".to_string(),
15048            "xx \nyy zz aa bb cc".to_string(),
15049            12,
15050            NonZeroU32::new(4).unwrap()
15051        ),
15052        "// xx yy zz\n// aa bb cc"
15053    );
15054    assert_eq!(
15055        wrap_with_prefix(
15056            String::new(),
15057            "这是什么 \n 钢笔".to_string(),
15058            3,
15059            NonZeroU32::new(4).unwrap()
15060        ),
15061        "这是什\n么 钢\n"
15062    );
15063}
15064
15065pub trait CollaborationHub {
15066    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15067    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15068    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15069}
15070
15071impl CollaborationHub for Entity<Project> {
15072    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15073        self.read(cx).collaborators()
15074    }
15075
15076    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15077        self.read(cx).user_store().read(cx).participant_indices()
15078    }
15079
15080    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15081        let this = self.read(cx);
15082        let user_ids = this.collaborators().values().map(|c| c.user_id);
15083        this.user_store().read_with(cx, |user_store, cx| {
15084            user_store.participant_names(user_ids, cx)
15085        })
15086    }
15087}
15088
15089pub trait SemanticsProvider {
15090    fn hover(
15091        &self,
15092        buffer: &Entity<Buffer>,
15093        position: text::Anchor,
15094        cx: &mut App,
15095    ) -> Option<Task<Vec<project::Hover>>>;
15096
15097    fn inlay_hints(
15098        &self,
15099        buffer_handle: Entity<Buffer>,
15100        range: Range<text::Anchor>,
15101        cx: &mut App,
15102    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15103
15104    fn resolve_inlay_hint(
15105        &self,
15106        hint: InlayHint,
15107        buffer_handle: Entity<Buffer>,
15108        server_id: LanguageServerId,
15109        cx: &mut App,
15110    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15111
15112    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15113
15114    fn document_highlights(
15115        &self,
15116        buffer: &Entity<Buffer>,
15117        position: text::Anchor,
15118        cx: &mut App,
15119    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15120
15121    fn definitions(
15122        &self,
15123        buffer: &Entity<Buffer>,
15124        position: text::Anchor,
15125        kind: GotoDefinitionKind,
15126        cx: &mut App,
15127    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15128
15129    fn range_for_rename(
15130        &self,
15131        buffer: &Entity<Buffer>,
15132        position: text::Anchor,
15133        cx: &mut App,
15134    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15135
15136    fn perform_rename(
15137        &self,
15138        buffer: &Entity<Buffer>,
15139        position: text::Anchor,
15140        new_name: String,
15141        cx: &mut App,
15142    ) -> Option<Task<Result<ProjectTransaction>>>;
15143}
15144
15145pub trait CompletionProvider {
15146    fn completions(
15147        &self,
15148        buffer: &Entity<Buffer>,
15149        buffer_position: text::Anchor,
15150        trigger: CompletionContext,
15151        window: &mut Window,
15152        cx: &mut Context<Editor>,
15153    ) -> Task<Result<Vec<Completion>>>;
15154
15155    fn resolve_completions(
15156        &self,
15157        buffer: Entity<Buffer>,
15158        completion_indices: Vec<usize>,
15159        completions: Rc<RefCell<Box<[Completion]>>>,
15160        cx: &mut Context<Editor>,
15161    ) -> Task<Result<bool>>;
15162
15163    fn apply_additional_edits_for_completion(
15164        &self,
15165        _buffer: Entity<Buffer>,
15166        _completions: Rc<RefCell<Box<[Completion]>>>,
15167        _completion_index: usize,
15168        _push_to_history: bool,
15169        _cx: &mut Context<Editor>,
15170    ) -> Task<Result<Option<language::Transaction>>> {
15171        Task::ready(Ok(None))
15172    }
15173
15174    fn is_completion_trigger(
15175        &self,
15176        buffer: &Entity<Buffer>,
15177        position: language::Anchor,
15178        text: &str,
15179        trigger_in_words: bool,
15180        cx: &mut Context<Editor>,
15181    ) -> bool;
15182
15183    fn sort_completions(&self) -> bool {
15184        true
15185    }
15186}
15187
15188pub trait CodeActionProvider {
15189    fn id(&self) -> Arc<str>;
15190
15191    fn code_actions(
15192        &self,
15193        buffer: &Entity<Buffer>,
15194        range: Range<text::Anchor>,
15195        window: &mut Window,
15196        cx: &mut App,
15197    ) -> Task<Result<Vec<CodeAction>>>;
15198
15199    fn apply_code_action(
15200        &self,
15201        buffer_handle: Entity<Buffer>,
15202        action: CodeAction,
15203        excerpt_id: ExcerptId,
15204        push_to_history: bool,
15205        window: &mut Window,
15206        cx: &mut App,
15207    ) -> Task<Result<ProjectTransaction>>;
15208}
15209
15210impl CodeActionProvider for Entity<Project> {
15211    fn id(&self) -> Arc<str> {
15212        "project".into()
15213    }
15214
15215    fn code_actions(
15216        &self,
15217        buffer: &Entity<Buffer>,
15218        range: Range<text::Anchor>,
15219        _window: &mut Window,
15220        cx: &mut App,
15221    ) -> Task<Result<Vec<CodeAction>>> {
15222        self.update(cx, |project, cx| {
15223            project.code_actions(buffer, range, None, cx)
15224        })
15225    }
15226
15227    fn apply_code_action(
15228        &self,
15229        buffer_handle: Entity<Buffer>,
15230        action: CodeAction,
15231        _excerpt_id: ExcerptId,
15232        push_to_history: bool,
15233        _window: &mut Window,
15234        cx: &mut App,
15235    ) -> Task<Result<ProjectTransaction>> {
15236        self.update(cx, |project, cx| {
15237            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15238        })
15239    }
15240}
15241
15242fn snippet_completions(
15243    project: &Project,
15244    buffer: &Entity<Buffer>,
15245    buffer_position: text::Anchor,
15246    cx: &mut App,
15247) -> Task<Result<Vec<Completion>>> {
15248    let language = buffer.read(cx).language_at(buffer_position);
15249    let language_name = language.as_ref().map(|language| language.lsp_id());
15250    let snippet_store = project.snippets().read(cx);
15251    let snippets = snippet_store.snippets_for(language_name, cx);
15252
15253    if snippets.is_empty() {
15254        return Task::ready(Ok(vec![]));
15255    }
15256    let snapshot = buffer.read(cx).text_snapshot();
15257    let chars: String = snapshot
15258        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15259        .collect();
15260
15261    let scope = language.map(|language| language.default_scope());
15262    let executor = cx.background_executor().clone();
15263
15264    cx.background_executor().spawn(async move {
15265        let classifier = CharClassifier::new(scope).for_completion(true);
15266        let mut last_word = chars
15267            .chars()
15268            .take_while(|c| classifier.is_word(*c))
15269            .collect::<String>();
15270        last_word = last_word.chars().rev().collect();
15271
15272        if last_word.is_empty() {
15273            return Ok(vec![]);
15274        }
15275
15276        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15277        let to_lsp = |point: &text::Anchor| {
15278            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15279            point_to_lsp(end)
15280        };
15281        let lsp_end = to_lsp(&buffer_position);
15282
15283        let candidates = snippets
15284            .iter()
15285            .enumerate()
15286            .flat_map(|(ix, snippet)| {
15287                snippet
15288                    .prefix
15289                    .iter()
15290                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15291            })
15292            .collect::<Vec<StringMatchCandidate>>();
15293
15294        let mut matches = fuzzy::match_strings(
15295            &candidates,
15296            &last_word,
15297            last_word.chars().any(|c| c.is_uppercase()),
15298            100,
15299            &Default::default(),
15300            executor,
15301        )
15302        .await;
15303
15304        // Remove all candidates where the query's start does not match the start of any word in the candidate
15305        if let Some(query_start) = last_word.chars().next() {
15306            matches.retain(|string_match| {
15307                split_words(&string_match.string).any(|word| {
15308                    // Check that the first codepoint of the word as lowercase matches the first
15309                    // codepoint of the query as lowercase
15310                    word.chars()
15311                        .flat_map(|codepoint| codepoint.to_lowercase())
15312                        .zip(query_start.to_lowercase())
15313                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15314                })
15315            });
15316        }
15317
15318        let matched_strings = matches
15319            .into_iter()
15320            .map(|m| m.string)
15321            .collect::<HashSet<_>>();
15322
15323        let result: Vec<Completion> = snippets
15324            .into_iter()
15325            .filter_map(|snippet| {
15326                let matching_prefix = snippet
15327                    .prefix
15328                    .iter()
15329                    .find(|prefix| matched_strings.contains(*prefix))?;
15330                let start = as_offset - last_word.len();
15331                let start = snapshot.anchor_before(start);
15332                let range = start..buffer_position;
15333                let lsp_start = to_lsp(&start);
15334                let lsp_range = lsp::Range {
15335                    start: lsp_start,
15336                    end: lsp_end,
15337                };
15338                Some(Completion {
15339                    old_range: range,
15340                    new_text: snippet.body.clone(),
15341                    resolved: false,
15342                    label: CodeLabel {
15343                        text: matching_prefix.clone(),
15344                        runs: vec![],
15345                        filter_range: 0..matching_prefix.len(),
15346                    },
15347                    server_id: LanguageServerId(usize::MAX),
15348                    documentation: snippet
15349                        .description
15350                        .clone()
15351                        .map(CompletionDocumentation::SingleLine),
15352                    lsp_completion: lsp::CompletionItem {
15353                        label: snippet.prefix.first().unwrap().clone(),
15354                        kind: Some(CompletionItemKind::SNIPPET),
15355                        label_details: snippet.description.as_ref().map(|description| {
15356                            lsp::CompletionItemLabelDetails {
15357                                detail: Some(description.clone()),
15358                                description: None,
15359                            }
15360                        }),
15361                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15362                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15363                            lsp::InsertReplaceEdit {
15364                                new_text: snippet.body.clone(),
15365                                insert: lsp_range,
15366                                replace: lsp_range,
15367                            },
15368                        )),
15369                        filter_text: Some(snippet.body.clone()),
15370                        sort_text: Some(char::MAX.to_string()),
15371                        ..Default::default()
15372                    },
15373                    confirm: None,
15374                })
15375            })
15376            .collect();
15377
15378        Ok(result)
15379    })
15380}
15381
15382impl CompletionProvider for Entity<Project> {
15383    fn completions(
15384        &self,
15385        buffer: &Entity<Buffer>,
15386        buffer_position: text::Anchor,
15387        options: CompletionContext,
15388        _window: &mut Window,
15389        cx: &mut Context<Editor>,
15390    ) -> Task<Result<Vec<Completion>>> {
15391        self.update(cx, |project, cx| {
15392            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15393            let project_completions = project.completions(buffer, buffer_position, options, cx);
15394            cx.background_executor().spawn(async move {
15395                let mut completions = project_completions.await?;
15396                let snippets_completions = snippets.await?;
15397                completions.extend(snippets_completions);
15398                Ok(completions)
15399            })
15400        })
15401    }
15402
15403    fn resolve_completions(
15404        &self,
15405        buffer: Entity<Buffer>,
15406        completion_indices: Vec<usize>,
15407        completions: Rc<RefCell<Box<[Completion]>>>,
15408        cx: &mut Context<Editor>,
15409    ) -> Task<Result<bool>> {
15410        self.update(cx, |project, cx| {
15411            project.lsp_store().update(cx, |lsp_store, cx| {
15412                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15413            })
15414        })
15415    }
15416
15417    fn apply_additional_edits_for_completion(
15418        &self,
15419        buffer: Entity<Buffer>,
15420        completions: Rc<RefCell<Box<[Completion]>>>,
15421        completion_index: usize,
15422        push_to_history: bool,
15423        cx: &mut Context<Editor>,
15424    ) -> Task<Result<Option<language::Transaction>>> {
15425        self.update(cx, |project, cx| {
15426            project.lsp_store().update(cx, |lsp_store, cx| {
15427                lsp_store.apply_additional_edits_for_completion(
15428                    buffer,
15429                    completions,
15430                    completion_index,
15431                    push_to_history,
15432                    cx,
15433                )
15434            })
15435        })
15436    }
15437
15438    fn is_completion_trigger(
15439        &self,
15440        buffer: &Entity<Buffer>,
15441        position: language::Anchor,
15442        text: &str,
15443        trigger_in_words: bool,
15444        cx: &mut Context<Editor>,
15445    ) -> bool {
15446        let mut chars = text.chars();
15447        let char = if let Some(char) = chars.next() {
15448            char
15449        } else {
15450            return false;
15451        };
15452        if chars.next().is_some() {
15453            return false;
15454        }
15455
15456        let buffer = buffer.read(cx);
15457        let snapshot = buffer.snapshot();
15458        if !snapshot.settings_at(position, cx).show_completions_on_input {
15459            return false;
15460        }
15461        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15462        if trigger_in_words && classifier.is_word(char) {
15463            return true;
15464        }
15465
15466        buffer.completion_triggers().contains(text)
15467    }
15468}
15469
15470impl SemanticsProvider for Entity<Project> {
15471    fn hover(
15472        &self,
15473        buffer: &Entity<Buffer>,
15474        position: text::Anchor,
15475        cx: &mut App,
15476    ) -> Option<Task<Vec<project::Hover>>> {
15477        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15478    }
15479
15480    fn document_highlights(
15481        &self,
15482        buffer: &Entity<Buffer>,
15483        position: text::Anchor,
15484        cx: &mut App,
15485    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15486        Some(self.update(cx, |project, cx| {
15487            project.document_highlights(buffer, position, cx)
15488        }))
15489    }
15490
15491    fn definitions(
15492        &self,
15493        buffer: &Entity<Buffer>,
15494        position: text::Anchor,
15495        kind: GotoDefinitionKind,
15496        cx: &mut App,
15497    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15498        Some(self.update(cx, |project, cx| match kind {
15499            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15500            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15501            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15502            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15503        }))
15504    }
15505
15506    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15507        // TODO: make this work for remote projects
15508        self.read(cx)
15509            .language_servers_for_local_buffer(buffer.read(cx), cx)
15510            .any(
15511                |(_, server)| match server.capabilities().inlay_hint_provider {
15512                    Some(lsp::OneOf::Left(enabled)) => enabled,
15513                    Some(lsp::OneOf::Right(_)) => true,
15514                    None => false,
15515                },
15516            )
15517    }
15518
15519    fn inlay_hints(
15520        &self,
15521        buffer_handle: Entity<Buffer>,
15522        range: Range<text::Anchor>,
15523        cx: &mut App,
15524    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15525        Some(self.update(cx, |project, cx| {
15526            project.inlay_hints(buffer_handle, range, cx)
15527        }))
15528    }
15529
15530    fn resolve_inlay_hint(
15531        &self,
15532        hint: InlayHint,
15533        buffer_handle: Entity<Buffer>,
15534        server_id: LanguageServerId,
15535        cx: &mut App,
15536    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15537        Some(self.update(cx, |project, cx| {
15538            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15539        }))
15540    }
15541
15542    fn range_for_rename(
15543        &self,
15544        buffer: &Entity<Buffer>,
15545        position: text::Anchor,
15546        cx: &mut App,
15547    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15548        Some(self.update(cx, |project, cx| {
15549            let buffer = buffer.clone();
15550            let task = project.prepare_rename(buffer.clone(), position, cx);
15551            cx.spawn(|_, mut cx| async move {
15552                Ok(match task.await? {
15553                    PrepareRenameResponse::Success(range) => Some(range),
15554                    PrepareRenameResponse::InvalidPosition => None,
15555                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15556                        // Fallback on using TreeSitter info to determine identifier range
15557                        buffer.update(&mut cx, |buffer, _| {
15558                            let snapshot = buffer.snapshot();
15559                            let (range, kind) = snapshot.surrounding_word(position);
15560                            if kind != Some(CharKind::Word) {
15561                                return None;
15562                            }
15563                            Some(
15564                                snapshot.anchor_before(range.start)
15565                                    ..snapshot.anchor_after(range.end),
15566                            )
15567                        })?
15568                    }
15569                })
15570            })
15571        }))
15572    }
15573
15574    fn perform_rename(
15575        &self,
15576        buffer: &Entity<Buffer>,
15577        position: text::Anchor,
15578        new_name: String,
15579        cx: &mut App,
15580    ) -> Option<Task<Result<ProjectTransaction>>> {
15581        Some(self.update(cx, |project, cx| {
15582            project.perform_rename(buffer.clone(), position, new_name, cx)
15583        }))
15584    }
15585}
15586
15587fn inlay_hint_settings(
15588    location: Anchor,
15589    snapshot: &MultiBufferSnapshot,
15590    cx: &mut Context<Editor>,
15591) -> InlayHintSettings {
15592    let file = snapshot.file_at(location);
15593    let language = snapshot.language_at(location).map(|l| l.name());
15594    language_settings(language, file, cx).inlay_hints
15595}
15596
15597fn consume_contiguous_rows(
15598    contiguous_row_selections: &mut Vec<Selection<Point>>,
15599    selection: &Selection<Point>,
15600    display_map: &DisplaySnapshot,
15601    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15602) -> (MultiBufferRow, MultiBufferRow) {
15603    contiguous_row_selections.push(selection.clone());
15604    let start_row = MultiBufferRow(selection.start.row);
15605    let mut end_row = ending_row(selection, display_map);
15606
15607    while let Some(next_selection) = selections.peek() {
15608        if next_selection.start.row <= end_row.0 {
15609            end_row = ending_row(next_selection, display_map);
15610            contiguous_row_selections.push(selections.next().unwrap().clone());
15611        } else {
15612            break;
15613        }
15614    }
15615    (start_row, end_row)
15616}
15617
15618fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15619    if next_selection.end.column > 0 || next_selection.is_empty() {
15620        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15621    } else {
15622        MultiBufferRow(next_selection.end.row)
15623    }
15624}
15625
15626impl EditorSnapshot {
15627    pub fn remote_selections_in_range<'a>(
15628        &'a self,
15629        range: &'a Range<Anchor>,
15630        collaboration_hub: &dyn CollaborationHub,
15631        cx: &'a App,
15632    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15633        let participant_names = collaboration_hub.user_names(cx);
15634        let participant_indices = collaboration_hub.user_participant_indices(cx);
15635        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15636        let collaborators_by_replica_id = collaborators_by_peer_id
15637            .iter()
15638            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15639            .collect::<HashMap<_, _>>();
15640        self.buffer_snapshot
15641            .selections_in_range(range, false)
15642            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15643                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15644                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15645                let user_name = participant_names.get(&collaborator.user_id).cloned();
15646                Some(RemoteSelection {
15647                    replica_id,
15648                    selection,
15649                    cursor_shape,
15650                    line_mode,
15651                    participant_index,
15652                    peer_id: collaborator.peer_id,
15653                    user_name,
15654                })
15655            })
15656    }
15657
15658    pub fn hunks_for_ranges(
15659        &self,
15660        ranges: impl Iterator<Item = Range<Point>>,
15661    ) -> Vec<MultiBufferDiffHunk> {
15662        let mut hunks = Vec::new();
15663        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15664            HashMap::default();
15665        for query_range in ranges {
15666            let query_rows =
15667                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15668            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15669                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15670            ) {
15671                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15672                // when the caret is just above or just below the deleted hunk.
15673                let allow_adjacent = hunk.status().is_removed();
15674                let related_to_selection = if allow_adjacent {
15675                    hunk.row_range.overlaps(&query_rows)
15676                        || hunk.row_range.start == query_rows.end
15677                        || hunk.row_range.end == query_rows.start
15678                } else {
15679                    hunk.row_range.overlaps(&query_rows)
15680                };
15681                if related_to_selection {
15682                    if !processed_buffer_rows
15683                        .entry(hunk.buffer_id)
15684                        .or_default()
15685                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15686                    {
15687                        continue;
15688                    }
15689                    hunks.push(hunk);
15690                }
15691            }
15692        }
15693
15694        hunks
15695    }
15696
15697    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15698        self.display_snapshot.buffer_snapshot.language_at(position)
15699    }
15700
15701    pub fn is_focused(&self) -> bool {
15702        self.is_focused
15703    }
15704
15705    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15706        self.placeholder_text.as_ref()
15707    }
15708
15709    pub fn scroll_position(&self) -> gpui::Point<f32> {
15710        self.scroll_anchor.scroll_position(&self.display_snapshot)
15711    }
15712
15713    fn gutter_dimensions(
15714        &self,
15715        font_id: FontId,
15716        font_size: Pixels,
15717        max_line_number_width: Pixels,
15718        cx: &App,
15719    ) -> Option<GutterDimensions> {
15720        if !self.show_gutter {
15721            return None;
15722        }
15723
15724        let descent = cx.text_system().descent(font_id, font_size);
15725        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15726        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15727
15728        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15729            matches!(
15730                ProjectSettings::get_global(cx).git.git_gutter,
15731                Some(GitGutterSetting::TrackedFiles)
15732            )
15733        });
15734        let gutter_settings = EditorSettings::get_global(cx).gutter;
15735        let show_line_numbers = self
15736            .show_line_numbers
15737            .unwrap_or(gutter_settings.line_numbers);
15738        let line_gutter_width = if show_line_numbers {
15739            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15740            let min_width_for_number_on_gutter = em_advance * 4.0;
15741            max_line_number_width.max(min_width_for_number_on_gutter)
15742        } else {
15743            0.0.into()
15744        };
15745
15746        let show_code_actions = self
15747            .show_code_actions
15748            .unwrap_or(gutter_settings.code_actions);
15749
15750        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15751
15752        let git_blame_entries_width =
15753            self.git_blame_gutter_max_author_length
15754                .map(|max_author_length| {
15755                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15756
15757                    /// The number of characters to dedicate to gaps and margins.
15758                    const SPACING_WIDTH: usize = 4;
15759
15760                    let max_char_count = max_author_length
15761                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15762                        + ::git::SHORT_SHA_LENGTH
15763                        + MAX_RELATIVE_TIMESTAMP.len()
15764                        + SPACING_WIDTH;
15765
15766                    em_advance * max_char_count
15767                });
15768
15769        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15770        left_padding += if show_code_actions || show_runnables {
15771            em_width * 3.0
15772        } else if show_git_gutter && show_line_numbers {
15773            em_width * 2.0
15774        } else if show_git_gutter || show_line_numbers {
15775            em_width
15776        } else {
15777            px(0.)
15778        };
15779
15780        let right_padding = if gutter_settings.folds && show_line_numbers {
15781            em_width * 4.0
15782        } else if gutter_settings.folds {
15783            em_width * 3.0
15784        } else if show_line_numbers {
15785            em_width
15786        } else {
15787            px(0.)
15788        };
15789
15790        Some(GutterDimensions {
15791            left_padding,
15792            right_padding,
15793            width: line_gutter_width + left_padding + right_padding,
15794            margin: -descent,
15795            git_blame_entries_width,
15796        })
15797    }
15798
15799    pub fn render_crease_toggle(
15800        &self,
15801        buffer_row: MultiBufferRow,
15802        row_contains_cursor: bool,
15803        editor: Entity<Editor>,
15804        window: &mut Window,
15805        cx: &mut App,
15806    ) -> Option<AnyElement> {
15807        let folded = self.is_line_folded(buffer_row);
15808        let mut is_foldable = false;
15809
15810        if let Some(crease) = self
15811            .crease_snapshot
15812            .query_row(buffer_row, &self.buffer_snapshot)
15813        {
15814            is_foldable = true;
15815            match crease {
15816                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15817                    if let Some(render_toggle) = render_toggle {
15818                        let toggle_callback =
15819                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15820                                if folded {
15821                                    editor.update(cx, |editor, cx| {
15822                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15823                                    });
15824                                } else {
15825                                    editor.update(cx, |editor, cx| {
15826                                        editor.unfold_at(
15827                                            &crate::UnfoldAt { buffer_row },
15828                                            window,
15829                                            cx,
15830                                        )
15831                                    });
15832                                }
15833                            });
15834                        return Some((render_toggle)(
15835                            buffer_row,
15836                            folded,
15837                            toggle_callback,
15838                            window,
15839                            cx,
15840                        ));
15841                    }
15842                }
15843            }
15844        }
15845
15846        is_foldable |= self.starts_indent(buffer_row);
15847
15848        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15849            Some(
15850                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15851                    .toggle_state(folded)
15852                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15853                        if folded {
15854                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15855                        } else {
15856                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15857                        }
15858                    }))
15859                    .into_any_element(),
15860            )
15861        } else {
15862            None
15863        }
15864    }
15865
15866    pub fn render_crease_trailer(
15867        &self,
15868        buffer_row: MultiBufferRow,
15869        window: &mut Window,
15870        cx: &mut App,
15871    ) -> Option<AnyElement> {
15872        let folded = self.is_line_folded(buffer_row);
15873        if let Crease::Inline { render_trailer, .. } = self
15874            .crease_snapshot
15875            .query_row(buffer_row, &self.buffer_snapshot)?
15876        {
15877            let render_trailer = render_trailer.as_ref()?;
15878            Some(render_trailer(buffer_row, folded, window, cx))
15879        } else {
15880            None
15881        }
15882    }
15883}
15884
15885impl Deref for EditorSnapshot {
15886    type Target = DisplaySnapshot;
15887
15888    fn deref(&self) -> &Self::Target {
15889        &self.display_snapshot
15890    }
15891}
15892
15893#[derive(Clone, Debug, PartialEq, Eq)]
15894pub enum EditorEvent {
15895    InputIgnored {
15896        text: Arc<str>,
15897    },
15898    InputHandled {
15899        utf16_range_to_replace: Option<Range<isize>>,
15900        text: Arc<str>,
15901    },
15902    ExcerptsAdded {
15903        buffer: Entity<Buffer>,
15904        predecessor: ExcerptId,
15905        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15906    },
15907    ExcerptsRemoved {
15908        ids: Vec<ExcerptId>,
15909    },
15910    BufferFoldToggled {
15911        ids: Vec<ExcerptId>,
15912        folded: bool,
15913    },
15914    ExcerptsEdited {
15915        ids: Vec<ExcerptId>,
15916    },
15917    ExcerptsExpanded {
15918        ids: Vec<ExcerptId>,
15919    },
15920    BufferEdited,
15921    Edited {
15922        transaction_id: clock::Lamport,
15923    },
15924    Reparsed(BufferId),
15925    Focused,
15926    FocusedIn,
15927    Blurred,
15928    DirtyChanged,
15929    Saved,
15930    TitleChanged,
15931    DiffBaseChanged,
15932    SelectionsChanged {
15933        local: bool,
15934    },
15935    ScrollPositionChanged {
15936        local: bool,
15937        autoscroll: bool,
15938    },
15939    Closed,
15940    TransactionUndone {
15941        transaction_id: clock::Lamport,
15942    },
15943    TransactionBegun {
15944        transaction_id: clock::Lamport,
15945    },
15946    Reloaded,
15947    CursorShapeChanged,
15948}
15949
15950impl EventEmitter<EditorEvent> for Editor {}
15951
15952impl Focusable for Editor {
15953    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15954        self.focus_handle.clone()
15955    }
15956}
15957
15958impl Render for Editor {
15959    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15960        let settings = ThemeSettings::get_global(cx);
15961
15962        let mut text_style = match self.mode {
15963            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15964                color: cx.theme().colors().editor_foreground,
15965                font_family: settings.ui_font.family.clone(),
15966                font_features: settings.ui_font.features.clone(),
15967                font_fallbacks: settings.ui_font.fallbacks.clone(),
15968                font_size: rems(0.875).into(),
15969                font_weight: settings.ui_font.weight,
15970                line_height: relative(settings.buffer_line_height.value()),
15971                ..Default::default()
15972            },
15973            EditorMode::Full => TextStyle {
15974                color: cx.theme().colors().editor_foreground,
15975                font_family: settings.buffer_font.family.clone(),
15976                font_features: settings.buffer_font.features.clone(),
15977                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15978                font_size: settings.buffer_font_size().into(),
15979                font_weight: settings.buffer_font.weight,
15980                line_height: relative(settings.buffer_line_height.value()),
15981                ..Default::default()
15982            },
15983        };
15984        if let Some(text_style_refinement) = &self.text_style_refinement {
15985            text_style.refine(text_style_refinement)
15986        }
15987
15988        let background = match self.mode {
15989            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15990            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15991            EditorMode::Full => cx.theme().colors().editor_background,
15992        };
15993
15994        EditorElement::new(
15995            &cx.entity(),
15996            EditorStyle {
15997                background,
15998                local_player: cx.theme().players().local(),
15999                text: text_style,
16000                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16001                syntax: cx.theme().syntax().clone(),
16002                status: cx.theme().status().clone(),
16003                inlay_hints_style: make_inlay_hints_style(cx),
16004                inline_completion_styles: make_suggestion_styles(cx),
16005                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16006            },
16007        )
16008    }
16009}
16010
16011impl EntityInputHandler for Editor {
16012    fn text_for_range(
16013        &mut self,
16014        range_utf16: Range<usize>,
16015        adjusted_range: &mut Option<Range<usize>>,
16016        _: &mut Window,
16017        cx: &mut Context<Self>,
16018    ) -> Option<String> {
16019        let snapshot = self.buffer.read(cx).read(cx);
16020        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16021        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16022        if (start.0..end.0) != range_utf16 {
16023            adjusted_range.replace(start.0..end.0);
16024        }
16025        Some(snapshot.text_for_range(start..end).collect())
16026    }
16027
16028    fn selected_text_range(
16029        &mut self,
16030        ignore_disabled_input: bool,
16031        _: &mut Window,
16032        cx: &mut Context<Self>,
16033    ) -> Option<UTF16Selection> {
16034        // Prevent the IME menu from appearing when holding down an alphabetic key
16035        // while input is disabled.
16036        if !ignore_disabled_input && !self.input_enabled {
16037            return None;
16038        }
16039
16040        let selection = self.selections.newest::<OffsetUtf16>(cx);
16041        let range = selection.range();
16042
16043        Some(UTF16Selection {
16044            range: range.start.0..range.end.0,
16045            reversed: selection.reversed,
16046        })
16047    }
16048
16049    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16050        let snapshot = self.buffer.read(cx).read(cx);
16051        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16052        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16053    }
16054
16055    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16056        self.clear_highlights::<InputComposition>(cx);
16057        self.ime_transaction.take();
16058    }
16059
16060    fn replace_text_in_range(
16061        &mut self,
16062        range_utf16: Option<Range<usize>>,
16063        text: &str,
16064        window: &mut Window,
16065        cx: &mut Context<Self>,
16066    ) {
16067        if !self.input_enabled {
16068            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16069            return;
16070        }
16071
16072        self.transact(window, cx, |this, window, cx| {
16073            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16074                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16075                Some(this.selection_replacement_ranges(range_utf16, cx))
16076            } else {
16077                this.marked_text_ranges(cx)
16078            };
16079
16080            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16081                let newest_selection_id = this.selections.newest_anchor().id;
16082                this.selections
16083                    .all::<OffsetUtf16>(cx)
16084                    .iter()
16085                    .zip(ranges_to_replace.iter())
16086                    .find_map(|(selection, range)| {
16087                        if selection.id == newest_selection_id {
16088                            Some(
16089                                (range.start.0 as isize - selection.head().0 as isize)
16090                                    ..(range.end.0 as isize - selection.head().0 as isize),
16091                            )
16092                        } else {
16093                            None
16094                        }
16095                    })
16096            });
16097
16098            cx.emit(EditorEvent::InputHandled {
16099                utf16_range_to_replace: range_to_replace,
16100                text: text.into(),
16101            });
16102
16103            if let Some(new_selected_ranges) = new_selected_ranges {
16104                this.change_selections(None, window, cx, |selections| {
16105                    selections.select_ranges(new_selected_ranges)
16106                });
16107                this.backspace(&Default::default(), window, cx);
16108            }
16109
16110            this.handle_input(text, window, cx);
16111        });
16112
16113        if let Some(transaction) = self.ime_transaction {
16114            self.buffer.update(cx, |buffer, cx| {
16115                buffer.group_until_transaction(transaction, cx);
16116            });
16117        }
16118
16119        self.unmark_text(window, cx);
16120    }
16121
16122    fn replace_and_mark_text_in_range(
16123        &mut self,
16124        range_utf16: Option<Range<usize>>,
16125        text: &str,
16126        new_selected_range_utf16: Option<Range<usize>>,
16127        window: &mut Window,
16128        cx: &mut Context<Self>,
16129    ) {
16130        if !self.input_enabled {
16131            return;
16132        }
16133
16134        let transaction = self.transact(window, cx, |this, window, cx| {
16135            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16136                let snapshot = this.buffer.read(cx).read(cx);
16137                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16138                    for marked_range in &mut marked_ranges {
16139                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16140                        marked_range.start.0 += relative_range_utf16.start;
16141                        marked_range.start =
16142                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16143                        marked_range.end =
16144                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16145                    }
16146                }
16147                Some(marked_ranges)
16148            } else if let Some(range_utf16) = range_utf16 {
16149                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16150                Some(this.selection_replacement_ranges(range_utf16, cx))
16151            } else {
16152                None
16153            };
16154
16155            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16156                let newest_selection_id = this.selections.newest_anchor().id;
16157                this.selections
16158                    .all::<OffsetUtf16>(cx)
16159                    .iter()
16160                    .zip(ranges_to_replace.iter())
16161                    .find_map(|(selection, range)| {
16162                        if selection.id == newest_selection_id {
16163                            Some(
16164                                (range.start.0 as isize - selection.head().0 as isize)
16165                                    ..(range.end.0 as isize - selection.head().0 as isize),
16166                            )
16167                        } else {
16168                            None
16169                        }
16170                    })
16171            });
16172
16173            cx.emit(EditorEvent::InputHandled {
16174                utf16_range_to_replace: range_to_replace,
16175                text: text.into(),
16176            });
16177
16178            if let Some(ranges) = ranges_to_replace {
16179                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16180            }
16181
16182            let marked_ranges = {
16183                let snapshot = this.buffer.read(cx).read(cx);
16184                this.selections
16185                    .disjoint_anchors()
16186                    .iter()
16187                    .map(|selection| {
16188                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16189                    })
16190                    .collect::<Vec<_>>()
16191            };
16192
16193            if text.is_empty() {
16194                this.unmark_text(window, cx);
16195            } else {
16196                this.highlight_text::<InputComposition>(
16197                    marked_ranges.clone(),
16198                    HighlightStyle {
16199                        underline: Some(UnderlineStyle {
16200                            thickness: px(1.),
16201                            color: None,
16202                            wavy: false,
16203                        }),
16204                        ..Default::default()
16205                    },
16206                    cx,
16207                );
16208            }
16209
16210            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16211            let use_autoclose = this.use_autoclose;
16212            let use_auto_surround = this.use_auto_surround;
16213            this.set_use_autoclose(false);
16214            this.set_use_auto_surround(false);
16215            this.handle_input(text, window, cx);
16216            this.set_use_autoclose(use_autoclose);
16217            this.set_use_auto_surround(use_auto_surround);
16218
16219            if let Some(new_selected_range) = new_selected_range_utf16 {
16220                let snapshot = this.buffer.read(cx).read(cx);
16221                let new_selected_ranges = marked_ranges
16222                    .into_iter()
16223                    .map(|marked_range| {
16224                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16225                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16226                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16227                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16228                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16229                    })
16230                    .collect::<Vec<_>>();
16231
16232                drop(snapshot);
16233                this.change_selections(None, window, cx, |selections| {
16234                    selections.select_ranges(new_selected_ranges)
16235                });
16236            }
16237        });
16238
16239        self.ime_transaction = self.ime_transaction.or(transaction);
16240        if let Some(transaction) = self.ime_transaction {
16241            self.buffer.update(cx, |buffer, cx| {
16242                buffer.group_until_transaction(transaction, cx);
16243            });
16244        }
16245
16246        if self.text_highlights::<InputComposition>(cx).is_none() {
16247            self.ime_transaction.take();
16248        }
16249    }
16250
16251    fn bounds_for_range(
16252        &mut self,
16253        range_utf16: Range<usize>,
16254        element_bounds: gpui::Bounds<Pixels>,
16255        window: &mut Window,
16256        cx: &mut Context<Self>,
16257    ) -> Option<gpui::Bounds<Pixels>> {
16258        let text_layout_details = self.text_layout_details(window);
16259        let gpui::Size {
16260            width: em_width,
16261            height: line_height,
16262        } = self.character_size(window);
16263
16264        let snapshot = self.snapshot(window, cx);
16265        let scroll_position = snapshot.scroll_position();
16266        let scroll_left = scroll_position.x * em_width;
16267
16268        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16269        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16270            + self.gutter_dimensions.width
16271            + self.gutter_dimensions.margin;
16272        let y = line_height * (start.row().as_f32() - scroll_position.y);
16273
16274        Some(Bounds {
16275            origin: element_bounds.origin + point(x, y),
16276            size: size(em_width, line_height),
16277        })
16278    }
16279
16280    fn character_index_for_point(
16281        &mut self,
16282        point: gpui::Point<Pixels>,
16283        _window: &mut Window,
16284        _cx: &mut Context<Self>,
16285    ) -> Option<usize> {
16286        let position_map = self.last_position_map.as_ref()?;
16287        if !position_map.text_hitbox.contains(&point) {
16288            return None;
16289        }
16290        let display_point = position_map.point_for_position(point).previous_valid;
16291        let anchor = position_map
16292            .snapshot
16293            .display_point_to_anchor(display_point, Bias::Left);
16294        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16295        Some(utf16_offset.0)
16296    }
16297}
16298
16299trait SelectionExt {
16300    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16301    fn spanned_rows(
16302        &self,
16303        include_end_if_at_line_start: bool,
16304        map: &DisplaySnapshot,
16305    ) -> Range<MultiBufferRow>;
16306}
16307
16308impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16309    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16310        let start = self
16311            .start
16312            .to_point(&map.buffer_snapshot)
16313            .to_display_point(map);
16314        let end = self
16315            .end
16316            .to_point(&map.buffer_snapshot)
16317            .to_display_point(map);
16318        if self.reversed {
16319            end..start
16320        } else {
16321            start..end
16322        }
16323    }
16324
16325    fn spanned_rows(
16326        &self,
16327        include_end_if_at_line_start: bool,
16328        map: &DisplaySnapshot,
16329    ) -> Range<MultiBufferRow> {
16330        let start = self.start.to_point(&map.buffer_snapshot);
16331        let mut end = self.end.to_point(&map.buffer_snapshot);
16332        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16333            end.row -= 1;
16334        }
16335
16336        let buffer_start = map.prev_line_boundary(start).0;
16337        let buffer_end = map.next_line_boundary(end).0;
16338        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16339    }
16340}
16341
16342impl<T: InvalidationRegion> InvalidationStack<T> {
16343    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16344    where
16345        S: Clone + ToOffset,
16346    {
16347        while let Some(region) = self.last() {
16348            let all_selections_inside_invalidation_ranges =
16349                if selections.len() == region.ranges().len() {
16350                    selections
16351                        .iter()
16352                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16353                        .all(|(selection, invalidation_range)| {
16354                            let head = selection.head().to_offset(buffer);
16355                            invalidation_range.start <= head && invalidation_range.end >= head
16356                        })
16357                } else {
16358                    false
16359                };
16360
16361            if all_selections_inside_invalidation_ranges {
16362                break;
16363            } else {
16364                self.pop();
16365            }
16366        }
16367    }
16368}
16369
16370impl<T> Default for InvalidationStack<T> {
16371    fn default() -> Self {
16372        Self(Default::default())
16373    }
16374}
16375
16376impl<T> Deref for InvalidationStack<T> {
16377    type Target = Vec<T>;
16378
16379    fn deref(&self) -> &Self::Target {
16380        &self.0
16381    }
16382}
16383
16384impl<T> DerefMut for InvalidationStack<T> {
16385    fn deref_mut(&mut self) -> &mut Self::Target {
16386        &mut self.0
16387    }
16388}
16389
16390impl InvalidationRegion for SnippetState {
16391    fn ranges(&self) -> &[Range<Anchor>] {
16392        &self.ranges[self.active_index]
16393    }
16394}
16395
16396pub fn diagnostic_block_renderer(
16397    diagnostic: Diagnostic,
16398    max_message_rows: Option<u8>,
16399    allow_closing: bool,
16400    _is_valid: bool,
16401) -> RenderBlock {
16402    let (text_without_backticks, code_ranges) =
16403        highlight_diagnostic_message(&diagnostic, max_message_rows);
16404
16405    Arc::new(move |cx: &mut BlockContext| {
16406        let group_id: SharedString = cx.block_id.to_string().into();
16407
16408        let mut text_style = cx.window.text_style().clone();
16409        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16410        let theme_settings = ThemeSettings::get_global(cx);
16411        text_style.font_family = theme_settings.buffer_font.family.clone();
16412        text_style.font_style = theme_settings.buffer_font.style;
16413        text_style.font_features = theme_settings.buffer_font.features.clone();
16414        text_style.font_weight = theme_settings.buffer_font.weight;
16415
16416        let multi_line_diagnostic = diagnostic.message.contains('\n');
16417
16418        let buttons = |diagnostic: &Diagnostic| {
16419            if multi_line_diagnostic {
16420                v_flex()
16421            } else {
16422                h_flex()
16423            }
16424            .when(allow_closing, |div| {
16425                div.children(diagnostic.is_primary.then(|| {
16426                    IconButton::new("close-block", IconName::XCircle)
16427                        .icon_color(Color::Muted)
16428                        .size(ButtonSize::Compact)
16429                        .style(ButtonStyle::Transparent)
16430                        .visible_on_hover(group_id.clone())
16431                        .on_click(move |_click, window, cx| {
16432                            window.dispatch_action(Box::new(Cancel), cx)
16433                        })
16434                        .tooltip(|window, cx| {
16435                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16436                        })
16437                }))
16438            })
16439            .child(
16440                IconButton::new("copy-block", IconName::Copy)
16441                    .icon_color(Color::Muted)
16442                    .size(ButtonSize::Compact)
16443                    .style(ButtonStyle::Transparent)
16444                    .visible_on_hover(group_id.clone())
16445                    .on_click({
16446                        let message = diagnostic.message.clone();
16447                        move |_click, _, cx| {
16448                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16449                        }
16450                    })
16451                    .tooltip(Tooltip::text("Copy diagnostic message")),
16452            )
16453        };
16454
16455        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16456            AvailableSpace::min_size(),
16457            cx.window,
16458            cx.app,
16459        );
16460
16461        h_flex()
16462            .id(cx.block_id)
16463            .group(group_id.clone())
16464            .relative()
16465            .size_full()
16466            .block_mouse_down()
16467            .pl(cx.gutter_dimensions.width)
16468            .w(cx.max_width - cx.gutter_dimensions.full_width())
16469            .child(
16470                div()
16471                    .flex()
16472                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16473                    .flex_shrink(),
16474            )
16475            .child(buttons(&diagnostic))
16476            .child(div().flex().flex_shrink_0().child(
16477                StyledText::new(text_without_backticks.clone()).with_highlights(
16478                    &text_style,
16479                    code_ranges.iter().map(|range| {
16480                        (
16481                            range.clone(),
16482                            HighlightStyle {
16483                                font_weight: Some(FontWeight::BOLD),
16484                                ..Default::default()
16485                            },
16486                        )
16487                    }),
16488                ),
16489            ))
16490            .into_any_element()
16491    })
16492}
16493
16494fn inline_completion_edit_text(
16495    current_snapshot: &BufferSnapshot,
16496    edits: &[(Range<Anchor>, String)],
16497    edit_preview: &EditPreview,
16498    include_deletions: bool,
16499    cx: &App,
16500) -> HighlightedText {
16501    let edits = edits
16502        .iter()
16503        .map(|(anchor, text)| {
16504            (
16505                anchor.start.text_anchor..anchor.end.text_anchor,
16506                text.clone(),
16507            )
16508        })
16509        .collect::<Vec<_>>();
16510
16511    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16512}
16513
16514pub fn highlight_diagnostic_message(
16515    diagnostic: &Diagnostic,
16516    mut max_message_rows: Option<u8>,
16517) -> (SharedString, Vec<Range<usize>>) {
16518    let mut text_without_backticks = String::new();
16519    let mut code_ranges = Vec::new();
16520
16521    if let Some(source) = &diagnostic.source {
16522        text_without_backticks.push_str(source);
16523        code_ranges.push(0..source.len());
16524        text_without_backticks.push_str(": ");
16525    }
16526
16527    let mut prev_offset = 0;
16528    let mut in_code_block = false;
16529    let has_row_limit = max_message_rows.is_some();
16530    let mut newline_indices = diagnostic
16531        .message
16532        .match_indices('\n')
16533        .filter(|_| has_row_limit)
16534        .map(|(ix, _)| ix)
16535        .fuse()
16536        .peekable();
16537
16538    for (quote_ix, _) in diagnostic
16539        .message
16540        .match_indices('`')
16541        .chain([(diagnostic.message.len(), "")])
16542    {
16543        let mut first_newline_ix = None;
16544        let mut last_newline_ix = None;
16545        while let Some(newline_ix) = newline_indices.peek() {
16546            if *newline_ix < quote_ix {
16547                if first_newline_ix.is_none() {
16548                    first_newline_ix = Some(*newline_ix);
16549                }
16550                last_newline_ix = Some(*newline_ix);
16551
16552                if let Some(rows_left) = &mut max_message_rows {
16553                    if *rows_left == 0 {
16554                        break;
16555                    } else {
16556                        *rows_left -= 1;
16557                    }
16558                }
16559                let _ = newline_indices.next();
16560            } else {
16561                break;
16562            }
16563        }
16564        let prev_len = text_without_backticks.len();
16565        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16566        text_without_backticks.push_str(new_text);
16567        if in_code_block {
16568            code_ranges.push(prev_len..text_without_backticks.len());
16569        }
16570        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16571        in_code_block = !in_code_block;
16572        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16573            text_without_backticks.push_str("...");
16574            break;
16575        }
16576    }
16577
16578    (text_without_backticks.into(), code_ranges)
16579}
16580
16581fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16582    match severity {
16583        DiagnosticSeverity::ERROR => colors.error,
16584        DiagnosticSeverity::WARNING => colors.warning,
16585        DiagnosticSeverity::INFORMATION => colors.info,
16586        DiagnosticSeverity::HINT => colors.info,
16587        _ => colors.ignored,
16588    }
16589}
16590
16591pub fn styled_runs_for_code_label<'a>(
16592    label: &'a CodeLabel,
16593    syntax_theme: &'a theme::SyntaxTheme,
16594) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16595    let fade_out = HighlightStyle {
16596        fade_out: Some(0.35),
16597        ..Default::default()
16598    };
16599
16600    let mut prev_end = label.filter_range.end;
16601    label
16602        .runs
16603        .iter()
16604        .enumerate()
16605        .flat_map(move |(ix, (range, highlight_id))| {
16606            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16607                style
16608            } else {
16609                return Default::default();
16610            };
16611            let mut muted_style = style;
16612            muted_style.highlight(fade_out);
16613
16614            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16615            if range.start >= label.filter_range.end {
16616                if range.start > prev_end {
16617                    runs.push((prev_end..range.start, fade_out));
16618                }
16619                runs.push((range.clone(), muted_style));
16620            } else if range.end <= label.filter_range.end {
16621                runs.push((range.clone(), style));
16622            } else {
16623                runs.push((range.start..label.filter_range.end, style));
16624                runs.push((label.filter_range.end..range.end, muted_style));
16625            }
16626            prev_end = cmp::max(prev_end, range.end);
16627
16628            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16629                runs.push((prev_end..label.text.len(), fade_out));
16630            }
16631
16632            runs
16633        })
16634}
16635
16636pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16637    let mut prev_index = 0;
16638    let mut prev_codepoint: Option<char> = None;
16639    text.char_indices()
16640        .chain([(text.len(), '\0')])
16641        .filter_map(move |(index, codepoint)| {
16642            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16643            let is_boundary = index == text.len()
16644                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16645                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16646            if is_boundary {
16647                let chunk = &text[prev_index..index];
16648                prev_index = index;
16649                Some(chunk)
16650            } else {
16651                None
16652            }
16653        })
16654}
16655
16656pub trait RangeToAnchorExt: Sized {
16657    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16658
16659    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16660        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16661        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16662    }
16663}
16664
16665impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16666    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16667        let start_offset = self.start.to_offset(snapshot);
16668        let end_offset = self.end.to_offset(snapshot);
16669        if start_offset == end_offset {
16670            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16671        } else {
16672            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16673        }
16674    }
16675}
16676
16677pub trait RowExt {
16678    fn as_f32(&self) -> f32;
16679
16680    fn next_row(&self) -> Self;
16681
16682    fn previous_row(&self) -> Self;
16683
16684    fn minus(&self, other: Self) -> u32;
16685}
16686
16687impl RowExt for DisplayRow {
16688    fn as_f32(&self) -> f32 {
16689        self.0 as f32
16690    }
16691
16692    fn next_row(&self) -> Self {
16693        Self(self.0 + 1)
16694    }
16695
16696    fn previous_row(&self) -> Self {
16697        Self(self.0.saturating_sub(1))
16698    }
16699
16700    fn minus(&self, other: Self) -> u32 {
16701        self.0 - other.0
16702    }
16703}
16704
16705impl RowExt for MultiBufferRow {
16706    fn as_f32(&self) -> f32 {
16707        self.0 as f32
16708    }
16709
16710    fn next_row(&self) -> Self {
16711        Self(self.0 + 1)
16712    }
16713
16714    fn previous_row(&self) -> Self {
16715        Self(self.0.saturating_sub(1))
16716    }
16717
16718    fn minus(&self, other: Self) -> u32 {
16719        self.0 - other.0
16720    }
16721}
16722
16723trait RowRangeExt {
16724    type Row;
16725
16726    fn len(&self) -> usize;
16727
16728    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16729}
16730
16731impl RowRangeExt for Range<MultiBufferRow> {
16732    type Row = MultiBufferRow;
16733
16734    fn len(&self) -> usize {
16735        (self.end.0 - self.start.0) as usize
16736    }
16737
16738    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16739        (self.start.0..self.end.0).map(MultiBufferRow)
16740    }
16741}
16742
16743impl RowRangeExt for Range<DisplayRow> {
16744    type Row = DisplayRow;
16745
16746    fn len(&self) -> usize {
16747        (self.end.0 - self.start.0) as usize
16748    }
16749
16750    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16751        (self.start.0..self.end.0).map(DisplayRow)
16752    }
16753}
16754
16755/// If select range has more than one line, we
16756/// just point the cursor to range.start.
16757fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16758    if range.start.row == range.end.row {
16759        range
16760    } else {
16761        range.start..range.start
16762    }
16763}
16764pub struct KillRing(ClipboardItem);
16765impl Global for KillRing {}
16766
16767const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16768
16769fn all_edits_insertions_or_deletions(
16770    edits: &Vec<(Range<Anchor>, String)>,
16771    snapshot: &MultiBufferSnapshot,
16772) -> bool {
16773    let mut all_insertions = true;
16774    let mut all_deletions = true;
16775
16776    for (range, new_text) in edits.iter() {
16777        let range_is_empty = range.to_offset(&snapshot).is_empty();
16778        let text_is_empty = new_text.is_empty();
16779
16780        if range_is_empty != text_is_empty {
16781            if range_is_empty {
16782                all_deletions = false;
16783            } else {
16784                all_insertions = false;
16785            }
16786        } else {
16787            return false;
16788        }
16789
16790        if !all_insertions && !all_deletions {
16791            return false;
16792        }
16793    }
16794    all_insertions || all_deletions
16795}