editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72
   73use code_context_menus::{
   74    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   75    CompletionsMenu, ContextMenuOrigin,
   76};
   77use git::blame::GitBlame;
   78use gpui::{
   79    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   80    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   81    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   82    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   83    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   84    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   85    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   86    WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
  100    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  101    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  128    ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  194pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  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
  507enum InlineCompletionHighlight {}
  508
  509pub enum MenuInlineCompletionsPolicy {
  510    Never,
  511    ByProvider,
  512}
  513
  514pub enum EditPredictionPreview {
  515    /// Modifier is not pressed
  516    Inactive,
  517    /// Modifier pressed
  518    Active {
  519        previous_scroll_position: Option<ScrollAnchor>,
  520    },
  521}
  522
  523#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  524struct EditorActionId(usize);
  525
  526impl EditorActionId {
  527    pub fn post_inc(&mut self) -> Self {
  528        let answer = self.0;
  529
  530        *self = Self(answer + 1);
  531
  532        Self(answer)
  533    }
  534}
  535
  536// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  537// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  538
  539type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  540type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  541
  542#[derive(Default)]
  543struct ScrollbarMarkerState {
  544    scrollbar_size: Size<Pixels>,
  545    dirty: bool,
  546    markers: Arc<[PaintQuad]>,
  547    pending_refresh: Option<Task<Result<()>>>,
  548}
  549
  550impl ScrollbarMarkerState {
  551    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  552        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  553    }
  554}
  555
  556#[derive(Clone, Debug)]
  557struct RunnableTasks {
  558    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  559    offset: MultiBufferOffset,
  560    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  561    column: u32,
  562    // Values of all named captures, including those starting with '_'
  563    extra_variables: HashMap<String, String>,
  564    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  565    context_range: Range<BufferOffset>,
  566}
  567
  568impl RunnableTasks {
  569    fn resolve<'a>(
  570        &'a self,
  571        cx: &'a task::TaskContext,
  572    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  573        self.templates.iter().filter_map(|(kind, template)| {
  574            template
  575                .resolve_task(&kind.to_id_base(), cx)
  576                .map(|task| (kind.clone(), task))
  577        })
  578    }
  579}
  580
  581#[derive(Clone)]
  582struct ResolvedTasks {
  583    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  584    position: Anchor,
  585}
  586#[derive(Copy, Clone, Debug)]
  587struct MultiBufferOffset(usize);
  588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  589struct BufferOffset(usize);
  590
  591// Addons allow storing per-editor state in other crates (e.g. Vim)
  592pub trait Addon: 'static {
  593    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  594
  595    fn render_buffer_header_controls(
  596        &self,
  597        _: &ExcerptInfo,
  598        _: &Window,
  599        _: &App,
  600    ) -> Option<AnyElement> {
  601        None
  602    }
  603
  604    fn to_any(&self) -> &dyn std::any::Any;
  605}
  606
  607#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  608pub enum IsVimMode {
  609    Yes,
  610    No,
  611}
  612
  613/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  614///
  615/// See the [module level documentation](self) for more information.
  616pub struct Editor {
  617    focus_handle: FocusHandle,
  618    last_focused_descendant: Option<WeakFocusHandle>,
  619    /// The text buffer being edited
  620    buffer: Entity<MultiBuffer>,
  621    /// Map of how text in the buffer should be displayed.
  622    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  623    pub display_map: Entity<DisplayMap>,
  624    pub selections: SelectionsCollection,
  625    pub scroll_manager: ScrollManager,
  626    /// When inline assist editors are linked, they all render cursors because
  627    /// typing enters text into each of them, even the ones that aren't focused.
  628    pub(crate) show_cursor_when_unfocused: bool,
  629    columnar_selection_tail: Option<Anchor>,
  630    add_selections_state: Option<AddSelectionsState>,
  631    select_next_state: Option<SelectNextState>,
  632    select_prev_state: Option<SelectNextState>,
  633    selection_history: SelectionHistory,
  634    autoclose_regions: Vec<AutocloseRegion>,
  635    snippet_stack: InvalidationStack<SnippetState>,
  636    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  637    ime_transaction: Option<TransactionId>,
  638    active_diagnostics: Option<ActiveDiagnosticGroup>,
  639    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  640
  641    // TODO: make this a access method
  642    pub project: Option<Entity<Project>>,
  643    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  644    completion_provider: Option<Box<dyn CompletionProvider>>,
  645    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  646    blink_manager: Entity<BlinkManager>,
  647    show_cursor_names: bool,
  648    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  649    pub show_local_selections: bool,
  650    mode: EditorMode,
  651    show_breadcrumbs: bool,
  652    show_gutter: bool,
  653    show_scrollbars: bool,
  654    show_line_numbers: Option<bool>,
  655    use_relative_line_numbers: Option<bool>,
  656    show_git_diff_gutter: Option<bool>,
  657    show_code_actions: Option<bool>,
  658    show_runnables: Option<bool>,
  659    show_wrap_guides: Option<bool>,
  660    show_indent_guides: Option<bool>,
  661    placeholder_text: Option<Arc<str>>,
  662    highlight_order: usize,
  663    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  664    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  665    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  666    scrollbar_marker_state: ScrollbarMarkerState,
  667    active_indent_guides_state: ActiveIndentGuidesState,
  668    nav_history: Option<ItemNavHistory>,
  669    context_menu: RefCell<Option<CodeContextMenu>>,
  670    mouse_context_menu: Option<MouseContextMenu>,
  671    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  672    signature_help_state: SignatureHelpState,
  673    auto_signature_help: Option<bool>,
  674    find_all_references_task_sources: Vec<Anchor>,
  675    next_completion_id: CompletionId,
  676    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  677    code_actions_task: Option<Task<Result<()>>>,
  678    document_highlights_task: Option<Task<()>>,
  679    linked_editing_range_task: Option<Task<Option<()>>>,
  680    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  681    pending_rename: Option<RenameState>,
  682    searchable: bool,
  683    cursor_shape: CursorShape,
  684    current_line_highlight: Option<CurrentLineHighlight>,
  685    collapse_matches: bool,
  686    autoindent_mode: Option<AutoindentMode>,
  687    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  688    input_enabled: bool,
  689    use_modal_editing: bool,
  690    read_only: bool,
  691    leader_peer_id: Option<PeerId>,
  692    remote_id: Option<ViewId>,
  693    hover_state: HoverState,
  694    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  695    gutter_hovered: bool,
  696    hovered_link_state: Option<HoveredLinkState>,
  697    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  698    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  699    active_inline_completion: Option<InlineCompletionState>,
  700    /// Used to prevent flickering as the user types while the menu is open
  701    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  702    edit_prediction_settings: EditPredictionSettings,
  703    inline_completions_hidden_for_vim_mode: bool,
  704    show_inline_completions_override: Option<bool>,
  705    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  706    edit_prediction_preview: EditPredictionPreview,
  707    edit_prediction_cursor_on_leading_whitespace: bool,
  708    edit_prediction_requires_modifier_in_leading_space: bool,
  709    inlay_hint_cache: InlayHintCache,
  710    next_inlay_id: usize,
  711    _subscriptions: Vec<Subscription>,
  712    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  713    gutter_dimensions: GutterDimensions,
  714    style: Option<EditorStyle>,
  715    text_style_refinement: Option<TextStyleRefinement>,
  716    next_editor_action_id: EditorActionId,
  717    editor_actions:
  718        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  719    use_autoclose: bool,
  720    use_auto_surround: bool,
  721    auto_replace_emoji_shortcode: bool,
  722    show_git_blame_gutter: bool,
  723    show_git_blame_inline: bool,
  724    show_git_blame_inline_delay_task: Option<Task<()>>,
  725    distinguish_unstaged_diff_hunks: bool,
  726    git_blame_inline_enabled: bool,
  727    serialize_dirty_buffers: bool,
  728    show_selection_menu: Option<bool>,
  729    blame: Option<Entity<GitBlame>>,
  730    blame_subscription: Option<Subscription>,
  731    custom_context_menu: Option<
  732        Box<
  733            dyn 'static
  734                + Fn(
  735                    &mut Self,
  736                    DisplayPoint,
  737                    &mut Window,
  738                    &mut Context<Self>,
  739                ) -> Option<Entity<ui::ContextMenu>>,
  740        >,
  741    >,
  742    last_bounds: Option<Bounds<Pixels>>,
  743    last_position_map: Option<Rc<PositionMap>>,
  744    expect_bounds_change: Option<Bounds<Pixels>>,
  745    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  746    tasks_update_task: Option<Task<()>>,
  747    in_project_search: bool,
  748    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  749    breadcrumb_header: Option<String>,
  750    focused_block: Option<FocusedBlock>,
  751    next_scroll_position: NextScrollCursorCenterTopBottom,
  752    addons: HashMap<TypeId, Box<dyn Addon>>,
  753    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  754    selection_mark_mode: bool,
  755    toggle_fold_multiple_buffers: Task<()>,
  756    _scroll_cursor_center_top_bottom_task: Task<()>,
  757}
  758
  759#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  760enum NextScrollCursorCenterTopBottom {
  761    #[default]
  762    Center,
  763    Top,
  764    Bottom,
  765}
  766
  767impl NextScrollCursorCenterTopBottom {
  768    fn next(&self) -> Self {
  769        match self {
  770            Self::Center => Self::Top,
  771            Self::Top => Self::Bottom,
  772            Self::Bottom => Self::Center,
  773        }
  774    }
  775}
  776
  777#[derive(Clone)]
  778pub struct EditorSnapshot {
  779    pub mode: EditorMode,
  780    show_gutter: bool,
  781    show_line_numbers: Option<bool>,
  782    show_git_diff_gutter: Option<bool>,
  783    show_code_actions: Option<bool>,
  784    show_runnables: Option<bool>,
  785    git_blame_gutter_max_author_length: Option<usize>,
  786    pub display_snapshot: DisplaySnapshot,
  787    pub placeholder_text: Option<Arc<str>>,
  788    is_focused: bool,
  789    scroll_anchor: ScrollAnchor,
  790    ongoing_scroll: OngoingScroll,
  791    current_line_highlight: CurrentLineHighlight,
  792    gutter_hovered: bool,
  793}
  794
  795const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  796
  797#[derive(Default, Debug, Clone, Copy)]
  798pub struct GutterDimensions {
  799    pub left_padding: Pixels,
  800    pub right_padding: Pixels,
  801    pub width: Pixels,
  802    pub margin: Pixels,
  803    pub git_blame_entries_width: Option<Pixels>,
  804}
  805
  806impl GutterDimensions {
  807    /// The full width of the space taken up by the gutter.
  808    pub fn full_width(&self) -> Pixels {
  809        self.margin + self.width
  810    }
  811
  812    /// The width of the space reserved for the fold indicators,
  813    /// use alongside 'justify_end' and `gutter_width` to
  814    /// right align content with the line numbers
  815    pub fn fold_area_width(&self) -> Pixels {
  816        self.margin + self.right_padding
  817    }
  818}
  819
  820#[derive(Debug)]
  821pub struct RemoteSelection {
  822    pub replica_id: ReplicaId,
  823    pub selection: Selection<Anchor>,
  824    pub cursor_shape: CursorShape,
  825    pub peer_id: PeerId,
  826    pub line_mode: bool,
  827    pub participant_index: Option<ParticipantIndex>,
  828    pub user_name: Option<SharedString>,
  829}
  830
  831#[derive(Clone, Debug)]
  832struct SelectionHistoryEntry {
  833    selections: Arc<[Selection<Anchor>]>,
  834    select_next_state: Option<SelectNextState>,
  835    select_prev_state: Option<SelectNextState>,
  836    add_selections_state: Option<AddSelectionsState>,
  837}
  838
  839enum SelectionHistoryMode {
  840    Normal,
  841    Undoing,
  842    Redoing,
  843}
  844
  845#[derive(Clone, PartialEq, Eq, Hash)]
  846struct HoveredCursor {
  847    replica_id: u16,
  848    selection_id: usize,
  849}
  850
  851impl Default for SelectionHistoryMode {
  852    fn default() -> Self {
  853        Self::Normal
  854    }
  855}
  856
  857#[derive(Default)]
  858struct SelectionHistory {
  859    #[allow(clippy::type_complexity)]
  860    selections_by_transaction:
  861        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  862    mode: SelectionHistoryMode,
  863    undo_stack: VecDeque<SelectionHistoryEntry>,
  864    redo_stack: VecDeque<SelectionHistoryEntry>,
  865}
  866
  867impl SelectionHistory {
  868    fn insert_transaction(
  869        &mut self,
  870        transaction_id: TransactionId,
  871        selections: Arc<[Selection<Anchor>]>,
  872    ) {
  873        self.selections_by_transaction
  874            .insert(transaction_id, (selections, None));
  875    }
  876
  877    #[allow(clippy::type_complexity)]
  878    fn transaction(
  879        &self,
  880        transaction_id: TransactionId,
  881    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  882        self.selections_by_transaction.get(&transaction_id)
  883    }
  884
  885    #[allow(clippy::type_complexity)]
  886    fn transaction_mut(
  887        &mut self,
  888        transaction_id: TransactionId,
  889    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  890        self.selections_by_transaction.get_mut(&transaction_id)
  891    }
  892
  893    fn push(&mut self, entry: SelectionHistoryEntry) {
  894        if !entry.selections.is_empty() {
  895            match self.mode {
  896                SelectionHistoryMode::Normal => {
  897                    self.push_undo(entry);
  898                    self.redo_stack.clear();
  899                }
  900                SelectionHistoryMode::Undoing => self.push_redo(entry),
  901                SelectionHistoryMode::Redoing => self.push_undo(entry),
  902            }
  903        }
  904    }
  905
  906    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  907        if self
  908            .undo_stack
  909            .back()
  910            .map_or(true, |e| e.selections != entry.selections)
  911        {
  912            self.undo_stack.push_back(entry);
  913            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  914                self.undo_stack.pop_front();
  915            }
  916        }
  917    }
  918
  919    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  920        if self
  921            .redo_stack
  922            .back()
  923            .map_or(true, |e| e.selections != entry.selections)
  924        {
  925            self.redo_stack.push_back(entry);
  926            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  927                self.redo_stack.pop_front();
  928            }
  929        }
  930    }
  931}
  932
  933struct RowHighlight {
  934    index: usize,
  935    range: Range<Anchor>,
  936    color: Hsla,
  937    should_autoscroll: bool,
  938}
  939
  940#[derive(Clone, Debug)]
  941struct AddSelectionsState {
  942    above: bool,
  943    stack: Vec<usize>,
  944}
  945
  946#[derive(Clone)]
  947struct SelectNextState {
  948    query: AhoCorasick,
  949    wordwise: bool,
  950    done: bool,
  951}
  952
  953impl std::fmt::Debug for SelectNextState {
  954    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  955        f.debug_struct(std::any::type_name::<Self>())
  956            .field("wordwise", &self.wordwise)
  957            .field("done", &self.done)
  958            .finish()
  959    }
  960}
  961
  962#[derive(Debug)]
  963struct AutocloseRegion {
  964    selection_id: usize,
  965    range: Range<Anchor>,
  966    pair: BracketPair,
  967}
  968
  969#[derive(Debug)]
  970struct SnippetState {
  971    ranges: Vec<Vec<Range<Anchor>>>,
  972    active_index: usize,
  973    choices: Vec<Option<Vec<String>>>,
  974}
  975
  976#[doc(hidden)]
  977pub struct RenameState {
  978    pub range: Range<Anchor>,
  979    pub old_name: Arc<str>,
  980    pub editor: Entity<Editor>,
  981    block_id: CustomBlockId,
  982}
  983
  984struct InvalidationStack<T>(Vec<T>);
  985
  986struct RegisteredInlineCompletionProvider {
  987    provider: Arc<dyn InlineCompletionProviderHandle>,
  988    _subscription: Subscription,
  989}
  990
  991#[derive(Debug)]
  992struct ActiveDiagnosticGroup {
  993    primary_range: Range<Anchor>,
  994    primary_message: String,
  995    group_id: usize,
  996    blocks: HashMap<CustomBlockId, Diagnostic>,
  997    is_valid: bool,
  998}
  999
 1000#[derive(Serialize, Deserialize, Clone, Debug)]
 1001pub struct ClipboardSelection {
 1002    pub len: usize,
 1003    pub is_entire_line: bool,
 1004    pub first_line_indent: u32,
 1005}
 1006
 1007#[derive(Debug)]
 1008pub(crate) struct NavigationData {
 1009    cursor_anchor: Anchor,
 1010    cursor_position: Point,
 1011    scroll_anchor: ScrollAnchor,
 1012    scroll_top_row: u32,
 1013}
 1014
 1015#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1016pub enum GotoDefinitionKind {
 1017    Symbol,
 1018    Declaration,
 1019    Type,
 1020    Implementation,
 1021}
 1022
 1023#[derive(Debug, Clone)]
 1024enum InlayHintRefreshReason {
 1025    Toggle(bool),
 1026    SettingsChange(InlayHintSettings),
 1027    NewLinesShown,
 1028    BufferEdited(HashSet<Arc<Language>>),
 1029    RefreshRequested,
 1030    ExcerptsRemoved(Vec<ExcerptId>),
 1031}
 1032
 1033impl InlayHintRefreshReason {
 1034    fn description(&self) -> &'static str {
 1035        match self {
 1036            Self::Toggle(_) => "toggle",
 1037            Self::SettingsChange(_) => "settings change",
 1038            Self::NewLinesShown => "new lines shown",
 1039            Self::BufferEdited(_) => "buffer edited",
 1040            Self::RefreshRequested => "refresh requested",
 1041            Self::ExcerptsRemoved(_) => "excerpts removed",
 1042        }
 1043    }
 1044}
 1045
 1046pub enum FormatTarget {
 1047    Buffers,
 1048    Ranges(Vec<Range<MultiBufferPoint>>),
 1049}
 1050
 1051pub(crate) struct FocusedBlock {
 1052    id: BlockId,
 1053    focus_handle: WeakFocusHandle,
 1054}
 1055
 1056#[derive(Clone)]
 1057enum JumpData {
 1058    MultiBufferRow {
 1059        row: MultiBufferRow,
 1060        line_offset_from_top: u32,
 1061    },
 1062    MultiBufferPoint {
 1063        excerpt_id: ExcerptId,
 1064        position: Point,
 1065        anchor: text::Anchor,
 1066        line_offset_from_top: u32,
 1067    },
 1068}
 1069
 1070pub enum MultibufferSelectionMode {
 1071    First,
 1072    All,
 1073}
 1074
 1075impl Editor {
 1076    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1077        let buffer = cx.new(|cx| Buffer::local("", cx));
 1078        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1079        Self::new(
 1080            EditorMode::SingleLine { auto_width: false },
 1081            buffer,
 1082            None,
 1083            false,
 1084            window,
 1085            cx,
 1086        )
 1087    }
 1088
 1089    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1090        let buffer = cx.new(|cx| Buffer::local("", cx));
 1091        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1092        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1093    }
 1094
 1095    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1096        let buffer = cx.new(|cx| Buffer::local("", cx));
 1097        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1098        Self::new(
 1099            EditorMode::SingleLine { auto_width: true },
 1100            buffer,
 1101            None,
 1102            false,
 1103            window,
 1104            cx,
 1105        )
 1106    }
 1107
 1108    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1109        let buffer = cx.new(|cx| Buffer::local("", cx));
 1110        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1111        Self::new(
 1112            EditorMode::AutoHeight { max_lines },
 1113            buffer,
 1114            None,
 1115            false,
 1116            window,
 1117            cx,
 1118        )
 1119    }
 1120
 1121    pub fn for_buffer(
 1122        buffer: Entity<Buffer>,
 1123        project: Option<Entity<Project>>,
 1124        window: &mut Window,
 1125        cx: &mut Context<Self>,
 1126    ) -> Self {
 1127        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1128        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1129    }
 1130
 1131    pub fn for_multibuffer(
 1132        buffer: Entity<MultiBuffer>,
 1133        project: Option<Entity<Project>>,
 1134        show_excerpt_controls: bool,
 1135        window: &mut Window,
 1136        cx: &mut Context<Self>,
 1137    ) -> Self {
 1138        Self::new(
 1139            EditorMode::Full,
 1140            buffer,
 1141            project,
 1142            show_excerpt_controls,
 1143            window,
 1144            cx,
 1145        )
 1146    }
 1147
 1148    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1149        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1150        let mut clone = Self::new(
 1151            self.mode,
 1152            self.buffer.clone(),
 1153            self.project.clone(),
 1154            show_excerpt_controls,
 1155            window,
 1156            cx,
 1157        );
 1158        self.display_map.update(cx, |display_map, cx| {
 1159            let snapshot = display_map.snapshot(cx);
 1160            clone.display_map.update(cx, |display_map, cx| {
 1161                display_map.set_state(&snapshot, cx);
 1162            });
 1163        });
 1164        clone.selections.clone_state(&self.selections);
 1165        clone.scroll_manager.clone_state(&self.scroll_manager);
 1166        clone.searchable = self.searchable;
 1167        clone
 1168    }
 1169
 1170    pub fn new(
 1171        mode: EditorMode,
 1172        buffer: Entity<MultiBuffer>,
 1173        project: Option<Entity<Project>>,
 1174        show_excerpt_controls: bool,
 1175        window: &mut Window,
 1176        cx: &mut Context<Self>,
 1177    ) -> Self {
 1178        let style = window.text_style();
 1179        let font_size = style.font_size.to_pixels(window.rem_size());
 1180        let editor = cx.entity().downgrade();
 1181        let fold_placeholder = FoldPlaceholder {
 1182            constrain_width: true,
 1183            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1184                let editor = editor.clone();
 1185                div()
 1186                    .id(fold_id)
 1187                    .bg(cx.theme().colors().ghost_element_background)
 1188                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1189                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1190                    .rounded_sm()
 1191                    .size_full()
 1192                    .cursor_pointer()
 1193                    .child("")
 1194                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1195                    .on_click(move |_, _window, cx| {
 1196                        editor
 1197                            .update(cx, |editor, cx| {
 1198                                editor.unfold_ranges(
 1199                                    &[fold_range.start..fold_range.end],
 1200                                    true,
 1201                                    false,
 1202                                    cx,
 1203                                );
 1204                                cx.stop_propagation();
 1205                            })
 1206                            .ok();
 1207                    })
 1208                    .into_any()
 1209            }),
 1210            merge_adjacent: true,
 1211            ..Default::default()
 1212        };
 1213        let display_map = cx.new(|cx| {
 1214            DisplayMap::new(
 1215                buffer.clone(),
 1216                style.font(),
 1217                font_size,
 1218                None,
 1219                show_excerpt_controls,
 1220                FILE_HEADER_HEIGHT,
 1221                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1222                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1223                fold_placeholder,
 1224                cx,
 1225            )
 1226        });
 1227
 1228        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1229
 1230        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1231
 1232        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1233            .then(|| language_settings::SoftWrap::None);
 1234
 1235        let mut project_subscriptions = Vec::new();
 1236        if mode == EditorMode::Full {
 1237            if let Some(project) = project.as_ref() {
 1238                if buffer.read(cx).is_singleton() {
 1239                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1240                        cx.emit(EditorEvent::TitleChanged);
 1241                    }));
 1242                }
 1243                project_subscriptions.push(cx.subscribe_in(
 1244                    project,
 1245                    window,
 1246                    |editor, _, event, window, cx| {
 1247                        if let project::Event::RefreshInlayHints = event {
 1248                            editor
 1249                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1250                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1251                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1252                                let focus_handle = editor.focus_handle(cx);
 1253                                if focus_handle.is_focused(window) {
 1254                                    let snapshot = buffer.read(cx).snapshot();
 1255                                    for (range, snippet) in snippet_edits {
 1256                                        let editor_range =
 1257                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1258                                        editor
 1259                                            .insert_snippet(
 1260                                                &[editor_range],
 1261                                                snippet.clone(),
 1262                                                window,
 1263                                                cx,
 1264                                            )
 1265                                            .ok();
 1266                                    }
 1267                                }
 1268                            }
 1269                        }
 1270                    },
 1271                ));
 1272                if let Some(task_inventory) = project
 1273                    .read(cx)
 1274                    .task_store()
 1275                    .read(cx)
 1276                    .task_inventory()
 1277                    .cloned()
 1278                {
 1279                    project_subscriptions.push(cx.observe_in(
 1280                        &task_inventory,
 1281                        window,
 1282                        |editor, _, window, cx| {
 1283                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1284                        },
 1285                    ));
 1286                }
 1287            }
 1288        }
 1289
 1290        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1291
 1292        let inlay_hint_settings =
 1293            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1294        let focus_handle = cx.focus_handle();
 1295        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1296            .detach();
 1297        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1298            .detach();
 1299        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1300            .detach();
 1301        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1302            .detach();
 1303
 1304        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1305            Some(false)
 1306        } else {
 1307            None
 1308        };
 1309
 1310        let mut code_action_providers = Vec::new();
 1311        if let Some(project) = project.clone() {
 1312            get_uncommitted_diff_for_buffer(
 1313                &project,
 1314                buffer.read(cx).all_buffers(),
 1315                buffer.clone(),
 1316                cx,
 1317            );
 1318            code_action_providers.push(Rc::new(project) as Rc<_>);
 1319        }
 1320
 1321        let mut this = Self {
 1322            focus_handle,
 1323            show_cursor_when_unfocused: false,
 1324            last_focused_descendant: None,
 1325            buffer: buffer.clone(),
 1326            display_map: display_map.clone(),
 1327            selections,
 1328            scroll_manager: ScrollManager::new(cx),
 1329            columnar_selection_tail: None,
 1330            add_selections_state: None,
 1331            select_next_state: None,
 1332            select_prev_state: None,
 1333            selection_history: Default::default(),
 1334            autoclose_regions: Default::default(),
 1335            snippet_stack: Default::default(),
 1336            select_larger_syntax_node_stack: Vec::new(),
 1337            ime_transaction: Default::default(),
 1338            active_diagnostics: None,
 1339            soft_wrap_mode_override,
 1340            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1341            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1342            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1343            project,
 1344            blink_manager: blink_manager.clone(),
 1345            show_local_selections: true,
 1346            show_scrollbars: true,
 1347            mode,
 1348            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1349            show_gutter: mode == EditorMode::Full,
 1350            show_line_numbers: None,
 1351            use_relative_line_numbers: None,
 1352            show_git_diff_gutter: None,
 1353            show_code_actions: None,
 1354            show_runnables: None,
 1355            show_wrap_guides: None,
 1356            show_indent_guides,
 1357            placeholder_text: None,
 1358            highlight_order: 0,
 1359            highlighted_rows: HashMap::default(),
 1360            background_highlights: Default::default(),
 1361            gutter_highlights: TreeMap::default(),
 1362            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1363            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1364            nav_history: None,
 1365            context_menu: RefCell::new(None),
 1366            mouse_context_menu: None,
 1367            completion_tasks: Default::default(),
 1368            signature_help_state: SignatureHelpState::default(),
 1369            auto_signature_help: None,
 1370            find_all_references_task_sources: Vec::new(),
 1371            next_completion_id: 0,
 1372            next_inlay_id: 0,
 1373            code_action_providers,
 1374            available_code_actions: Default::default(),
 1375            code_actions_task: Default::default(),
 1376            document_highlights_task: Default::default(),
 1377            linked_editing_range_task: Default::default(),
 1378            pending_rename: Default::default(),
 1379            searchable: true,
 1380            cursor_shape: EditorSettings::get_global(cx)
 1381                .cursor_shape
 1382                .unwrap_or_default(),
 1383            current_line_highlight: None,
 1384            autoindent_mode: Some(AutoindentMode::EachLine),
 1385            collapse_matches: false,
 1386            workspace: None,
 1387            input_enabled: true,
 1388            use_modal_editing: mode == EditorMode::Full,
 1389            read_only: false,
 1390            use_autoclose: true,
 1391            use_auto_surround: true,
 1392            auto_replace_emoji_shortcode: false,
 1393            leader_peer_id: None,
 1394            remote_id: None,
 1395            hover_state: Default::default(),
 1396            pending_mouse_down: None,
 1397            hovered_link_state: Default::default(),
 1398            edit_prediction_provider: None,
 1399            active_inline_completion: None,
 1400            stale_inline_completion_in_menu: None,
 1401            edit_prediction_preview: EditPredictionPreview::Inactive,
 1402            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1403
 1404            gutter_hovered: false,
 1405            pixel_position_of_newest_cursor: None,
 1406            last_bounds: None,
 1407            last_position_map: None,
 1408            expect_bounds_change: None,
 1409            gutter_dimensions: GutterDimensions::default(),
 1410            style: None,
 1411            show_cursor_names: false,
 1412            hovered_cursors: Default::default(),
 1413            next_editor_action_id: EditorActionId::default(),
 1414            editor_actions: Rc::default(),
 1415            inline_completions_hidden_for_vim_mode: false,
 1416            show_inline_completions_override: None,
 1417            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1418            edit_prediction_settings: EditPredictionSettings::Disabled,
 1419            edit_prediction_cursor_on_leading_whitespace: false,
 1420            edit_prediction_requires_modifier_in_leading_space: true,
 1421            custom_context_menu: None,
 1422            show_git_blame_gutter: false,
 1423            show_git_blame_inline: false,
 1424            distinguish_unstaged_diff_hunks: false,
 1425            show_selection_menu: None,
 1426            show_git_blame_inline_delay_task: None,
 1427            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1428            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1429                .session
 1430                .restore_unsaved_buffers,
 1431            blame: None,
 1432            blame_subscription: None,
 1433            tasks: Default::default(),
 1434            _subscriptions: vec![
 1435                cx.observe(&buffer, Self::on_buffer_changed),
 1436                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1437                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1438                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1439                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1440                cx.observe_window_activation(window, |editor, window, cx| {
 1441                    let active = window.is_window_active();
 1442                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1443                        if active {
 1444                            blink_manager.enable(cx);
 1445                        } else {
 1446                            blink_manager.disable(cx);
 1447                        }
 1448                    });
 1449                }),
 1450            ],
 1451            tasks_update_task: None,
 1452            linked_edit_ranges: Default::default(),
 1453            in_project_search: false,
 1454            previous_search_ranges: None,
 1455            breadcrumb_header: None,
 1456            focused_block: None,
 1457            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1458            addons: HashMap::default(),
 1459            registered_buffers: HashMap::default(),
 1460            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1461            selection_mark_mode: false,
 1462            toggle_fold_multiple_buffers: Task::ready(()),
 1463            text_style_refinement: None,
 1464        };
 1465        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1466        this._subscriptions.extend(project_subscriptions);
 1467
 1468        this.end_selection(window, cx);
 1469        this.scroll_manager.show_scrollbar(window, cx);
 1470
 1471        if mode == EditorMode::Full {
 1472            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1473            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1474
 1475            if this.git_blame_inline_enabled {
 1476                this.git_blame_inline_enabled = true;
 1477                this.start_git_blame_inline(false, window, cx);
 1478            }
 1479
 1480            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1481                if let Some(project) = this.project.as_ref() {
 1482                    let lsp_store = project.read(cx).lsp_store();
 1483                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1484                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1485                    });
 1486                    this.registered_buffers
 1487                        .insert(buffer.read(cx).remote_id(), handle);
 1488                }
 1489            }
 1490        }
 1491
 1492        this.report_editor_event("Editor Opened", None, cx);
 1493        this
 1494    }
 1495
 1496    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1497        self.mouse_context_menu
 1498            .as_ref()
 1499            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1500    }
 1501
 1502    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1503        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1504    }
 1505
 1506    fn key_context_internal(
 1507        &self,
 1508        has_active_edit_prediction: bool,
 1509        window: &Window,
 1510        cx: &App,
 1511    ) -> KeyContext {
 1512        let mut key_context = KeyContext::new_with_defaults();
 1513        key_context.add("Editor");
 1514        let mode = match self.mode {
 1515            EditorMode::SingleLine { .. } => "single_line",
 1516            EditorMode::AutoHeight { .. } => "auto_height",
 1517            EditorMode::Full => "full",
 1518        };
 1519
 1520        if EditorSettings::jupyter_enabled(cx) {
 1521            key_context.add("jupyter");
 1522        }
 1523
 1524        key_context.set("mode", mode);
 1525        if self.pending_rename.is_some() {
 1526            key_context.add("renaming");
 1527        }
 1528
 1529        match self.context_menu.borrow().as_ref() {
 1530            Some(CodeContextMenu::Completions(_)) => {
 1531                key_context.add("menu");
 1532                key_context.add("showing_completions");
 1533            }
 1534            Some(CodeContextMenu::CodeActions(_)) => {
 1535                key_context.add("menu");
 1536                key_context.add("showing_code_actions")
 1537            }
 1538            None => {}
 1539        }
 1540
 1541        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1542        if !self.focus_handle(cx).contains_focused(window, cx)
 1543            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1544        {
 1545            for addon in self.addons.values() {
 1546                addon.extend_key_context(&mut key_context, cx)
 1547            }
 1548        }
 1549
 1550        if let Some(extension) = self
 1551            .buffer
 1552            .read(cx)
 1553            .as_singleton()
 1554            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1555        {
 1556            key_context.set("extension", extension.to_string());
 1557        }
 1558
 1559        if has_active_edit_prediction {
 1560            if self.edit_prediction_in_conflict() {
 1561                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1562            } else {
 1563                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1564                key_context.add("copilot_suggestion");
 1565            }
 1566        }
 1567
 1568        if self.selection_mark_mode {
 1569            key_context.add("selection_mode");
 1570        }
 1571
 1572        key_context
 1573    }
 1574
 1575    pub fn edit_prediction_in_conflict(&self) -> bool {
 1576        if !self.show_edit_predictions_in_menu() {
 1577            return false;
 1578        }
 1579
 1580        let showing_completions = self
 1581            .context_menu
 1582            .borrow()
 1583            .as_ref()
 1584            .map_or(false, |context| {
 1585                matches!(context, CodeContextMenu::Completions(_))
 1586            });
 1587
 1588        showing_completions
 1589            || self.edit_prediction_requires_modifier()
 1590            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1591            // bindings to insert tab characters.
 1592            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1593    }
 1594
 1595    pub fn accept_edit_prediction_keybind(
 1596        &self,
 1597        window: &Window,
 1598        cx: &App,
 1599    ) -> AcceptEditPredictionBinding {
 1600        let key_context = self.key_context_internal(true, window, cx);
 1601        let in_conflict = self.edit_prediction_in_conflict();
 1602
 1603        AcceptEditPredictionBinding(
 1604            window
 1605                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1606                .into_iter()
 1607                .filter(|binding| {
 1608                    !in_conflict
 1609                        || binding
 1610                            .keystrokes()
 1611                            .first()
 1612                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1613                })
 1614                .rev()
 1615                .min_by_key(|binding| {
 1616                    binding
 1617                        .keystrokes()
 1618                        .first()
 1619                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1620                }),
 1621        )
 1622    }
 1623
 1624    pub fn new_file(
 1625        workspace: &mut Workspace,
 1626        _: &workspace::NewFile,
 1627        window: &mut Window,
 1628        cx: &mut Context<Workspace>,
 1629    ) {
 1630        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1631            "Failed to create buffer",
 1632            window,
 1633            cx,
 1634            |e, _, _| match e.error_code() {
 1635                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1636                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1637                e.error_tag("required").unwrap_or("the latest version")
 1638            )),
 1639                _ => None,
 1640            },
 1641        );
 1642    }
 1643
 1644    pub fn new_in_workspace(
 1645        workspace: &mut Workspace,
 1646        window: &mut Window,
 1647        cx: &mut Context<Workspace>,
 1648    ) -> Task<Result<Entity<Editor>>> {
 1649        let project = workspace.project().clone();
 1650        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1651
 1652        cx.spawn_in(window, |workspace, mut cx| async move {
 1653            let buffer = create.await?;
 1654            workspace.update_in(&mut cx, |workspace, window, cx| {
 1655                let editor =
 1656                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1657                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1658                editor
 1659            })
 1660        })
 1661    }
 1662
 1663    fn new_file_vertical(
 1664        workspace: &mut Workspace,
 1665        _: &workspace::NewFileSplitVertical,
 1666        window: &mut Window,
 1667        cx: &mut Context<Workspace>,
 1668    ) {
 1669        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1670    }
 1671
 1672    fn new_file_horizontal(
 1673        workspace: &mut Workspace,
 1674        _: &workspace::NewFileSplitHorizontal,
 1675        window: &mut Window,
 1676        cx: &mut Context<Workspace>,
 1677    ) {
 1678        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1679    }
 1680
 1681    fn new_file_in_direction(
 1682        workspace: &mut Workspace,
 1683        direction: SplitDirection,
 1684        window: &mut Window,
 1685        cx: &mut Context<Workspace>,
 1686    ) {
 1687        let project = workspace.project().clone();
 1688        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1689
 1690        cx.spawn_in(window, |workspace, mut cx| async move {
 1691            let buffer = create.await?;
 1692            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1693                workspace.split_item(
 1694                    direction,
 1695                    Box::new(
 1696                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1697                    ),
 1698                    window,
 1699                    cx,
 1700                )
 1701            })?;
 1702            anyhow::Ok(())
 1703        })
 1704        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1705            match e.error_code() {
 1706                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1707                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1708                e.error_tag("required").unwrap_or("the latest version")
 1709            )),
 1710                _ => None,
 1711            }
 1712        });
 1713    }
 1714
 1715    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1716        self.leader_peer_id
 1717    }
 1718
 1719    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1720        &self.buffer
 1721    }
 1722
 1723    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1724        self.workspace.as_ref()?.0.upgrade()
 1725    }
 1726
 1727    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1728        self.buffer().read(cx).title(cx)
 1729    }
 1730
 1731    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1732        let git_blame_gutter_max_author_length = self
 1733            .render_git_blame_gutter(cx)
 1734            .then(|| {
 1735                if let Some(blame) = self.blame.as_ref() {
 1736                    let max_author_length =
 1737                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1738                    Some(max_author_length)
 1739                } else {
 1740                    None
 1741                }
 1742            })
 1743            .flatten();
 1744
 1745        EditorSnapshot {
 1746            mode: self.mode,
 1747            show_gutter: self.show_gutter,
 1748            show_line_numbers: self.show_line_numbers,
 1749            show_git_diff_gutter: self.show_git_diff_gutter,
 1750            show_code_actions: self.show_code_actions,
 1751            show_runnables: self.show_runnables,
 1752            git_blame_gutter_max_author_length,
 1753            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1754            scroll_anchor: self.scroll_manager.anchor(),
 1755            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1756            placeholder_text: self.placeholder_text.clone(),
 1757            is_focused: self.focus_handle.is_focused(window),
 1758            current_line_highlight: self
 1759                .current_line_highlight
 1760                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1761            gutter_hovered: self.gutter_hovered,
 1762        }
 1763    }
 1764
 1765    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1766        self.buffer.read(cx).language_at(point, cx)
 1767    }
 1768
 1769    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1770        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1771    }
 1772
 1773    pub fn active_excerpt(
 1774        &self,
 1775        cx: &App,
 1776    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1777        self.buffer
 1778            .read(cx)
 1779            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1780    }
 1781
 1782    pub fn mode(&self) -> EditorMode {
 1783        self.mode
 1784    }
 1785
 1786    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1787        self.collaboration_hub.as_deref()
 1788    }
 1789
 1790    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1791        self.collaboration_hub = Some(hub);
 1792    }
 1793
 1794    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1795        self.in_project_search = in_project_search;
 1796    }
 1797
 1798    pub fn set_custom_context_menu(
 1799        &mut self,
 1800        f: impl 'static
 1801            + Fn(
 1802                &mut Self,
 1803                DisplayPoint,
 1804                &mut Window,
 1805                &mut Context<Self>,
 1806            ) -> Option<Entity<ui::ContextMenu>>,
 1807    ) {
 1808        self.custom_context_menu = Some(Box::new(f))
 1809    }
 1810
 1811    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1812        self.completion_provider = provider;
 1813    }
 1814
 1815    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1816        self.semantics_provider.clone()
 1817    }
 1818
 1819    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1820        self.semantics_provider = provider;
 1821    }
 1822
 1823    pub fn set_edit_prediction_provider<T>(
 1824        &mut self,
 1825        provider: Option<Entity<T>>,
 1826        window: &mut Window,
 1827        cx: &mut Context<Self>,
 1828    ) where
 1829        T: EditPredictionProvider,
 1830    {
 1831        self.edit_prediction_provider =
 1832            provider.map(|provider| RegisteredInlineCompletionProvider {
 1833                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1834                    if this.focus_handle.is_focused(window) {
 1835                        this.update_visible_inline_completion(window, cx);
 1836                    }
 1837                }),
 1838                provider: Arc::new(provider),
 1839            });
 1840        self.refresh_inline_completion(false, false, window, cx);
 1841    }
 1842
 1843    pub fn placeholder_text(&self) -> Option<&str> {
 1844        self.placeholder_text.as_deref()
 1845    }
 1846
 1847    pub fn set_placeholder_text(
 1848        &mut self,
 1849        placeholder_text: impl Into<Arc<str>>,
 1850        cx: &mut Context<Self>,
 1851    ) {
 1852        let placeholder_text = Some(placeholder_text.into());
 1853        if self.placeholder_text != placeholder_text {
 1854            self.placeholder_text = placeholder_text;
 1855            cx.notify();
 1856        }
 1857    }
 1858
 1859    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1860        self.cursor_shape = cursor_shape;
 1861
 1862        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1863        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1864
 1865        cx.notify();
 1866    }
 1867
 1868    pub fn set_current_line_highlight(
 1869        &mut self,
 1870        current_line_highlight: Option<CurrentLineHighlight>,
 1871    ) {
 1872        self.current_line_highlight = current_line_highlight;
 1873    }
 1874
 1875    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1876        self.collapse_matches = collapse_matches;
 1877    }
 1878
 1879    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1880        let buffers = self.buffer.read(cx).all_buffers();
 1881        let Some(lsp_store) = self.lsp_store(cx) else {
 1882            return;
 1883        };
 1884        lsp_store.update(cx, |lsp_store, cx| {
 1885            for buffer in buffers {
 1886                self.registered_buffers
 1887                    .entry(buffer.read(cx).remote_id())
 1888                    .or_insert_with(|| {
 1889                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1890                    });
 1891            }
 1892        })
 1893    }
 1894
 1895    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1896        if self.collapse_matches {
 1897            return range.start..range.start;
 1898        }
 1899        range.clone()
 1900    }
 1901
 1902    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1903        if self.display_map.read(cx).clip_at_line_ends != clip {
 1904            self.display_map
 1905                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1906        }
 1907    }
 1908
 1909    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1910        self.input_enabled = input_enabled;
 1911    }
 1912
 1913    pub fn set_inline_completions_hidden_for_vim_mode(
 1914        &mut self,
 1915        hidden: bool,
 1916        window: &mut Window,
 1917        cx: &mut Context<Self>,
 1918    ) {
 1919        if hidden != self.inline_completions_hidden_for_vim_mode {
 1920            self.inline_completions_hidden_for_vim_mode = hidden;
 1921            if hidden {
 1922                self.update_visible_inline_completion(window, cx);
 1923            } else {
 1924                self.refresh_inline_completion(true, false, window, cx);
 1925            }
 1926        }
 1927    }
 1928
 1929    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1930        self.menu_inline_completions_policy = value;
 1931    }
 1932
 1933    pub fn set_autoindent(&mut self, autoindent: bool) {
 1934        if autoindent {
 1935            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1936        } else {
 1937            self.autoindent_mode = None;
 1938        }
 1939    }
 1940
 1941    pub fn read_only(&self, cx: &App) -> bool {
 1942        self.read_only || self.buffer.read(cx).read_only()
 1943    }
 1944
 1945    pub fn set_read_only(&mut self, read_only: bool) {
 1946        self.read_only = read_only;
 1947    }
 1948
 1949    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1950        self.use_autoclose = autoclose;
 1951    }
 1952
 1953    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1954        self.use_auto_surround = auto_surround;
 1955    }
 1956
 1957    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1958        self.auto_replace_emoji_shortcode = auto_replace;
 1959    }
 1960
 1961    pub fn toggle_inline_completions(
 1962        &mut self,
 1963        _: &ToggleEditPrediction,
 1964        window: &mut Window,
 1965        cx: &mut Context<Self>,
 1966    ) {
 1967        if self.show_inline_completions_override.is_some() {
 1968            self.set_show_edit_predictions(None, window, cx);
 1969        } else {
 1970            let show_edit_predictions = !self.edit_predictions_enabled();
 1971            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1972        }
 1973    }
 1974
 1975    pub fn set_show_edit_predictions(
 1976        &mut self,
 1977        show_edit_predictions: Option<bool>,
 1978        window: &mut Window,
 1979        cx: &mut Context<Self>,
 1980    ) {
 1981        self.show_inline_completions_override = show_edit_predictions;
 1982        self.refresh_inline_completion(false, true, window, cx);
 1983    }
 1984
 1985    fn inline_completions_disabled_in_scope(
 1986        &self,
 1987        buffer: &Entity<Buffer>,
 1988        buffer_position: language::Anchor,
 1989        cx: &App,
 1990    ) -> bool {
 1991        let snapshot = buffer.read(cx).snapshot();
 1992        let settings = snapshot.settings_at(buffer_position, cx);
 1993
 1994        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1995            return false;
 1996        };
 1997
 1998        scope.override_name().map_or(false, |scope_name| {
 1999            settings
 2000                .edit_predictions_disabled_in
 2001                .iter()
 2002                .any(|s| s == scope_name)
 2003        })
 2004    }
 2005
 2006    pub fn set_use_modal_editing(&mut self, to: bool) {
 2007        self.use_modal_editing = to;
 2008    }
 2009
 2010    pub fn use_modal_editing(&self) -> bool {
 2011        self.use_modal_editing
 2012    }
 2013
 2014    fn selections_did_change(
 2015        &mut self,
 2016        local: bool,
 2017        old_cursor_position: &Anchor,
 2018        show_completions: bool,
 2019        window: &mut Window,
 2020        cx: &mut Context<Self>,
 2021    ) {
 2022        window.invalidate_character_coordinates();
 2023
 2024        // Copy selections to primary selection buffer
 2025        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2026        if local {
 2027            let selections = self.selections.all::<usize>(cx);
 2028            let buffer_handle = self.buffer.read(cx).read(cx);
 2029
 2030            let mut text = String::new();
 2031            for (index, selection) in selections.iter().enumerate() {
 2032                let text_for_selection = buffer_handle
 2033                    .text_for_range(selection.start..selection.end)
 2034                    .collect::<String>();
 2035
 2036                text.push_str(&text_for_selection);
 2037                if index != selections.len() - 1 {
 2038                    text.push('\n');
 2039                }
 2040            }
 2041
 2042            if !text.is_empty() {
 2043                cx.write_to_primary(ClipboardItem::new_string(text));
 2044            }
 2045        }
 2046
 2047        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2048            self.buffer.update(cx, |buffer, cx| {
 2049                buffer.set_active_selections(
 2050                    &self.selections.disjoint_anchors(),
 2051                    self.selections.line_mode,
 2052                    self.cursor_shape,
 2053                    cx,
 2054                )
 2055            });
 2056        }
 2057        let display_map = self
 2058            .display_map
 2059            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2060        let buffer = &display_map.buffer_snapshot;
 2061        self.add_selections_state = None;
 2062        self.select_next_state = None;
 2063        self.select_prev_state = None;
 2064        self.select_larger_syntax_node_stack.clear();
 2065        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2066        self.snippet_stack
 2067            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2068        self.take_rename(false, window, cx);
 2069
 2070        let new_cursor_position = self.selections.newest_anchor().head();
 2071
 2072        self.push_to_nav_history(
 2073            *old_cursor_position,
 2074            Some(new_cursor_position.to_point(buffer)),
 2075            cx,
 2076        );
 2077
 2078        if local {
 2079            let new_cursor_position = self.selections.newest_anchor().head();
 2080            let mut context_menu = self.context_menu.borrow_mut();
 2081            let completion_menu = match context_menu.as_ref() {
 2082                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2083                _ => {
 2084                    *context_menu = None;
 2085                    None
 2086                }
 2087            };
 2088            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2089                if !self.registered_buffers.contains_key(&buffer_id) {
 2090                    if let Some(lsp_store) = self.lsp_store(cx) {
 2091                        lsp_store.update(cx, |lsp_store, cx| {
 2092                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2093                                return;
 2094                            };
 2095                            self.registered_buffers.insert(
 2096                                buffer_id,
 2097                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2098                            );
 2099                        })
 2100                    }
 2101                }
 2102            }
 2103
 2104            if let Some(completion_menu) = completion_menu {
 2105                let cursor_position = new_cursor_position.to_offset(buffer);
 2106                let (word_range, kind) =
 2107                    buffer.surrounding_word(completion_menu.initial_position, true);
 2108                if kind == Some(CharKind::Word)
 2109                    && word_range.to_inclusive().contains(&cursor_position)
 2110                {
 2111                    let mut completion_menu = completion_menu.clone();
 2112                    drop(context_menu);
 2113
 2114                    let query = Self::completion_query(buffer, cursor_position);
 2115                    cx.spawn(move |this, mut cx| async move {
 2116                        completion_menu
 2117                            .filter(query.as_deref(), cx.background_executor().clone())
 2118                            .await;
 2119
 2120                        this.update(&mut cx, |this, cx| {
 2121                            let mut context_menu = this.context_menu.borrow_mut();
 2122                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2123                            else {
 2124                                return;
 2125                            };
 2126
 2127                            if menu.id > completion_menu.id {
 2128                                return;
 2129                            }
 2130
 2131                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2132                            drop(context_menu);
 2133                            cx.notify();
 2134                        })
 2135                    })
 2136                    .detach();
 2137
 2138                    if show_completions {
 2139                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2140                    }
 2141                } else {
 2142                    drop(context_menu);
 2143                    self.hide_context_menu(window, cx);
 2144                }
 2145            } else {
 2146                drop(context_menu);
 2147            }
 2148
 2149            hide_hover(self, cx);
 2150
 2151            if old_cursor_position.to_display_point(&display_map).row()
 2152                != new_cursor_position.to_display_point(&display_map).row()
 2153            {
 2154                self.available_code_actions.take();
 2155            }
 2156            self.refresh_code_actions(window, cx);
 2157            self.refresh_document_highlights(cx);
 2158            refresh_matching_bracket_highlights(self, window, cx);
 2159            self.update_visible_inline_completion(window, cx);
 2160            self.edit_prediction_requires_modifier_in_leading_space = true;
 2161            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2162            if self.git_blame_inline_enabled {
 2163                self.start_inline_blame_timer(window, cx);
 2164            }
 2165        }
 2166
 2167        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2168        cx.emit(EditorEvent::SelectionsChanged { local });
 2169
 2170        if self.selections.disjoint_anchors().len() == 1 {
 2171            cx.emit(SearchEvent::ActiveMatchChanged)
 2172        }
 2173        cx.notify();
 2174    }
 2175
 2176    pub fn change_selections<R>(
 2177        &mut self,
 2178        autoscroll: Option<Autoscroll>,
 2179        window: &mut Window,
 2180        cx: &mut Context<Self>,
 2181        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2182    ) -> R {
 2183        self.change_selections_inner(autoscroll, true, window, cx, change)
 2184    }
 2185
 2186    pub fn change_selections_inner<R>(
 2187        &mut self,
 2188        autoscroll: Option<Autoscroll>,
 2189        request_completions: bool,
 2190        window: &mut Window,
 2191        cx: &mut Context<Self>,
 2192        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2193    ) -> R {
 2194        let old_cursor_position = self.selections.newest_anchor().head();
 2195        self.push_to_selection_history();
 2196
 2197        let (changed, result) = self.selections.change_with(cx, change);
 2198
 2199        if changed {
 2200            if let Some(autoscroll) = autoscroll {
 2201                self.request_autoscroll(autoscroll, cx);
 2202            }
 2203            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2204
 2205            if self.should_open_signature_help_automatically(
 2206                &old_cursor_position,
 2207                self.signature_help_state.backspace_pressed(),
 2208                cx,
 2209            ) {
 2210                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2211            }
 2212            self.signature_help_state.set_backspace_pressed(false);
 2213        }
 2214
 2215        result
 2216    }
 2217
 2218    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2219    where
 2220        I: IntoIterator<Item = (Range<S>, T)>,
 2221        S: ToOffset,
 2222        T: Into<Arc<str>>,
 2223    {
 2224        if self.read_only(cx) {
 2225            return;
 2226        }
 2227
 2228        self.buffer
 2229            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2230    }
 2231
 2232    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2233    where
 2234        I: IntoIterator<Item = (Range<S>, T)>,
 2235        S: ToOffset,
 2236        T: Into<Arc<str>>,
 2237    {
 2238        if self.read_only(cx) {
 2239            return;
 2240        }
 2241
 2242        self.buffer.update(cx, |buffer, cx| {
 2243            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2244        });
 2245    }
 2246
 2247    pub fn edit_with_block_indent<I, S, T>(
 2248        &mut self,
 2249        edits: I,
 2250        original_indent_columns: Vec<u32>,
 2251        cx: &mut Context<Self>,
 2252    ) where
 2253        I: IntoIterator<Item = (Range<S>, T)>,
 2254        S: ToOffset,
 2255        T: Into<Arc<str>>,
 2256    {
 2257        if self.read_only(cx) {
 2258            return;
 2259        }
 2260
 2261        self.buffer.update(cx, |buffer, cx| {
 2262            buffer.edit(
 2263                edits,
 2264                Some(AutoindentMode::Block {
 2265                    original_indent_columns,
 2266                }),
 2267                cx,
 2268            )
 2269        });
 2270    }
 2271
 2272    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2273        self.hide_context_menu(window, cx);
 2274
 2275        match phase {
 2276            SelectPhase::Begin {
 2277                position,
 2278                add,
 2279                click_count,
 2280            } => self.begin_selection(position, add, click_count, window, cx),
 2281            SelectPhase::BeginColumnar {
 2282                position,
 2283                goal_column,
 2284                reset,
 2285            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2286            SelectPhase::Extend {
 2287                position,
 2288                click_count,
 2289            } => self.extend_selection(position, click_count, window, cx),
 2290            SelectPhase::Update {
 2291                position,
 2292                goal_column,
 2293                scroll_delta,
 2294            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2295            SelectPhase::End => self.end_selection(window, cx),
 2296        }
 2297    }
 2298
 2299    fn extend_selection(
 2300        &mut self,
 2301        position: DisplayPoint,
 2302        click_count: usize,
 2303        window: &mut Window,
 2304        cx: &mut Context<Self>,
 2305    ) {
 2306        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2307        let tail = self.selections.newest::<usize>(cx).tail();
 2308        self.begin_selection(position, false, click_count, window, cx);
 2309
 2310        let position = position.to_offset(&display_map, Bias::Left);
 2311        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2312
 2313        let mut pending_selection = self
 2314            .selections
 2315            .pending_anchor()
 2316            .expect("extend_selection not called with pending selection");
 2317        if position >= tail {
 2318            pending_selection.start = tail_anchor;
 2319        } else {
 2320            pending_selection.end = tail_anchor;
 2321            pending_selection.reversed = true;
 2322        }
 2323
 2324        let mut pending_mode = self.selections.pending_mode().unwrap();
 2325        match &mut pending_mode {
 2326            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2327            _ => {}
 2328        }
 2329
 2330        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2331            s.set_pending(pending_selection, pending_mode)
 2332        });
 2333    }
 2334
 2335    fn begin_selection(
 2336        &mut self,
 2337        position: DisplayPoint,
 2338        add: bool,
 2339        click_count: usize,
 2340        window: &mut Window,
 2341        cx: &mut Context<Self>,
 2342    ) {
 2343        if !self.focus_handle.is_focused(window) {
 2344            self.last_focused_descendant = None;
 2345            window.focus(&self.focus_handle);
 2346        }
 2347
 2348        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2349        let buffer = &display_map.buffer_snapshot;
 2350        let newest_selection = self.selections.newest_anchor().clone();
 2351        let position = display_map.clip_point(position, Bias::Left);
 2352
 2353        let start;
 2354        let end;
 2355        let mode;
 2356        let mut auto_scroll;
 2357        match click_count {
 2358            1 => {
 2359                start = buffer.anchor_before(position.to_point(&display_map));
 2360                end = start;
 2361                mode = SelectMode::Character;
 2362                auto_scroll = true;
 2363            }
 2364            2 => {
 2365                let range = movement::surrounding_word(&display_map, position);
 2366                start = buffer.anchor_before(range.start.to_point(&display_map));
 2367                end = buffer.anchor_before(range.end.to_point(&display_map));
 2368                mode = SelectMode::Word(start..end);
 2369                auto_scroll = true;
 2370            }
 2371            3 => {
 2372                let position = display_map
 2373                    .clip_point(position, Bias::Left)
 2374                    .to_point(&display_map);
 2375                let line_start = display_map.prev_line_boundary(position).0;
 2376                let next_line_start = buffer.clip_point(
 2377                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2378                    Bias::Left,
 2379                );
 2380                start = buffer.anchor_before(line_start);
 2381                end = buffer.anchor_before(next_line_start);
 2382                mode = SelectMode::Line(start..end);
 2383                auto_scroll = true;
 2384            }
 2385            _ => {
 2386                start = buffer.anchor_before(0);
 2387                end = buffer.anchor_before(buffer.len());
 2388                mode = SelectMode::All;
 2389                auto_scroll = false;
 2390            }
 2391        }
 2392        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2393
 2394        let point_to_delete: Option<usize> = {
 2395            let selected_points: Vec<Selection<Point>> =
 2396                self.selections.disjoint_in_range(start..end, cx);
 2397
 2398            if !add || click_count > 1 {
 2399                None
 2400            } else if !selected_points.is_empty() {
 2401                Some(selected_points[0].id)
 2402            } else {
 2403                let clicked_point_already_selected =
 2404                    self.selections.disjoint.iter().find(|selection| {
 2405                        selection.start.to_point(buffer) == start.to_point(buffer)
 2406                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2407                    });
 2408
 2409                clicked_point_already_selected.map(|selection| selection.id)
 2410            }
 2411        };
 2412
 2413        let selections_count = self.selections.count();
 2414
 2415        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2416            if let Some(point_to_delete) = point_to_delete {
 2417                s.delete(point_to_delete);
 2418
 2419                if selections_count == 1 {
 2420                    s.set_pending_anchor_range(start..end, mode);
 2421                }
 2422            } else {
 2423                if !add {
 2424                    s.clear_disjoint();
 2425                } else if click_count > 1 {
 2426                    s.delete(newest_selection.id)
 2427                }
 2428
 2429                s.set_pending_anchor_range(start..end, mode);
 2430            }
 2431        });
 2432    }
 2433
 2434    fn begin_columnar_selection(
 2435        &mut self,
 2436        position: DisplayPoint,
 2437        goal_column: u32,
 2438        reset: bool,
 2439        window: &mut Window,
 2440        cx: &mut Context<Self>,
 2441    ) {
 2442        if !self.focus_handle.is_focused(window) {
 2443            self.last_focused_descendant = None;
 2444            window.focus(&self.focus_handle);
 2445        }
 2446
 2447        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2448
 2449        if reset {
 2450            let pointer_position = display_map
 2451                .buffer_snapshot
 2452                .anchor_before(position.to_point(&display_map));
 2453
 2454            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2455                s.clear_disjoint();
 2456                s.set_pending_anchor_range(
 2457                    pointer_position..pointer_position,
 2458                    SelectMode::Character,
 2459                );
 2460            });
 2461        }
 2462
 2463        let tail = self.selections.newest::<Point>(cx).tail();
 2464        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2465
 2466        if !reset {
 2467            self.select_columns(
 2468                tail.to_display_point(&display_map),
 2469                position,
 2470                goal_column,
 2471                &display_map,
 2472                window,
 2473                cx,
 2474            );
 2475        }
 2476    }
 2477
 2478    fn update_selection(
 2479        &mut self,
 2480        position: DisplayPoint,
 2481        goal_column: u32,
 2482        scroll_delta: gpui::Point<f32>,
 2483        window: &mut Window,
 2484        cx: &mut Context<Self>,
 2485    ) {
 2486        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2487
 2488        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2489            let tail = tail.to_display_point(&display_map);
 2490            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2491        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2492            let buffer = self.buffer.read(cx).snapshot(cx);
 2493            let head;
 2494            let tail;
 2495            let mode = self.selections.pending_mode().unwrap();
 2496            match &mode {
 2497                SelectMode::Character => {
 2498                    head = position.to_point(&display_map);
 2499                    tail = pending.tail().to_point(&buffer);
 2500                }
 2501                SelectMode::Word(original_range) => {
 2502                    let original_display_range = original_range.start.to_display_point(&display_map)
 2503                        ..original_range.end.to_display_point(&display_map);
 2504                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2505                        ..original_display_range.end.to_point(&display_map);
 2506                    if movement::is_inside_word(&display_map, position)
 2507                        || original_display_range.contains(&position)
 2508                    {
 2509                        let word_range = movement::surrounding_word(&display_map, position);
 2510                        if word_range.start < original_display_range.start {
 2511                            head = word_range.start.to_point(&display_map);
 2512                        } else {
 2513                            head = word_range.end.to_point(&display_map);
 2514                        }
 2515                    } else {
 2516                        head = position.to_point(&display_map);
 2517                    }
 2518
 2519                    if head <= original_buffer_range.start {
 2520                        tail = original_buffer_range.end;
 2521                    } else {
 2522                        tail = original_buffer_range.start;
 2523                    }
 2524                }
 2525                SelectMode::Line(original_range) => {
 2526                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2527
 2528                    let position = display_map
 2529                        .clip_point(position, Bias::Left)
 2530                        .to_point(&display_map);
 2531                    let line_start = display_map.prev_line_boundary(position).0;
 2532                    let next_line_start = buffer.clip_point(
 2533                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2534                        Bias::Left,
 2535                    );
 2536
 2537                    if line_start < original_range.start {
 2538                        head = line_start
 2539                    } else {
 2540                        head = next_line_start
 2541                    }
 2542
 2543                    if head <= original_range.start {
 2544                        tail = original_range.end;
 2545                    } else {
 2546                        tail = original_range.start;
 2547                    }
 2548                }
 2549                SelectMode::All => {
 2550                    return;
 2551                }
 2552            };
 2553
 2554            if head < tail {
 2555                pending.start = buffer.anchor_before(head);
 2556                pending.end = buffer.anchor_before(tail);
 2557                pending.reversed = true;
 2558            } else {
 2559                pending.start = buffer.anchor_before(tail);
 2560                pending.end = buffer.anchor_before(head);
 2561                pending.reversed = false;
 2562            }
 2563
 2564            self.change_selections(None, window, cx, |s| {
 2565                s.set_pending(pending, mode);
 2566            });
 2567        } else {
 2568            log::error!("update_selection dispatched with no pending selection");
 2569            return;
 2570        }
 2571
 2572        self.apply_scroll_delta(scroll_delta, window, cx);
 2573        cx.notify();
 2574    }
 2575
 2576    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2577        self.columnar_selection_tail.take();
 2578        if self.selections.pending_anchor().is_some() {
 2579            let selections = self.selections.all::<usize>(cx);
 2580            self.change_selections(None, window, cx, |s| {
 2581                s.select(selections);
 2582                s.clear_pending();
 2583            });
 2584        }
 2585    }
 2586
 2587    fn select_columns(
 2588        &mut self,
 2589        tail: DisplayPoint,
 2590        head: DisplayPoint,
 2591        goal_column: u32,
 2592        display_map: &DisplaySnapshot,
 2593        window: &mut Window,
 2594        cx: &mut Context<Self>,
 2595    ) {
 2596        let start_row = cmp::min(tail.row(), head.row());
 2597        let end_row = cmp::max(tail.row(), head.row());
 2598        let start_column = cmp::min(tail.column(), goal_column);
 2599        let end_column = cmp::max(tail.column(), goal_column);
 2600        let reversed = start_column < tail.column();
 2601
 2602        let selection_ranges = (start_row.0..=end_row.0)
 2603            .map(DisplayRow)
 2604            .filter_map(|row| {
 2605                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2606                    let start = display_map
 2607                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2608                        .to_point(display_map);
 2609                    let end = display_map
 2610                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2611                        .to_point(display_map);
 2612                    if reversed {
 2613                        Some(end..start)
 2614                    } else {
 2615                        Some(start..end)
 2616                    }
 2617                } else {
 2618                    None
 2619                }
 2620            })
 2621            .collect::<Vec<_>>();
 2622
 2623        self.change_selections(None, window, cx, |s| {
 2624            s.select_ranges(selection_ranges);
 2625        });
 2626        cx.notify();
 2627    }
 2628
 2629    pub fn has_pending_nonempty_selection(&self) -> bool {
 2630        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2631            Some(Selection { start, end, .. }) => start != end,
 2632            None => false,
 2633        };
 2634
 2635        pending_nonempty_selection
 2636            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2637    }
 2638
 2639    pub fn has_pending_selection(&self) -> bool {
 2640        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2641    }
 2642
 2643    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2644        self.selection_mark_mode = false;
 2645
 2646        if self.clear_expanded_diff_hunks(cx) {
 2647            cx.notify();
 2648            return;
 2649        }
 2650        if self.dismiss_menus_and_popups(true, window, cx) {
 2651            return;
 2652        }
 2653
 2654        if self.mode == EditorMode::Full
 2655            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2656        {
 2657            return;
 2658        }
 2659
 2660        cx.propagate();
 2661    }
 2662
 2663    pub fn dismiss_menus_and_popups(
 2664        &mut self,
 2665        is_user_requested: bool,
 2666        window: &mut Window,
 2667        cx: &mut Context<Self>,
 2668    ) -> bool {
 2669        if self.take_rename(false, window, cx).is_some() {
 2670            return true;
 2671        }
 2672
 2673        if hide_hover(self, cx) {
 2674            return true;
 2675        }
 2676
 2677        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2678            return true;
 2679        }
 2680
 2681        if self.hide_context_menu(window, cx).is_some() {
 2682            return true;
 2683        }
 2684
 2685        if self.mouse_context_menu.take().is_some() {
 2686            return true;
 2687        }
 2688
 2689        if is_user_requested && self.discard_inline_completion(true, cx) {
 2690            return true;
 2691        }
 2692
 2693        if self.snippet_stack.pop().is_some() {
 2694            return true;
 2695        }
 2696
 2697        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2698            self.dismiss_diagnostics(cx);
 2699            return true;
 2700        }
 2701
 2702        false
 2703    }
 2704
 2705    fn linked_editing_ranges_for(
 2706        &self,
 2707        selection: Range<text::Anchor>,
 2708        cx: &App,
 2709    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2710        if self.linked_edit_ranges.is_empty() {
 2711            return None;
 2712        }
 2713        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2714            selection.end.buffer_id.and_then(|end_buffer_id| {
 2715                if selection.start.buffer_id != Some(end_buffer_id) {
 2716                    return None;
 2717                }
 2718                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2719                let snapshot = buffer.read(cx).snapshot();
 2720                self.linked_edit_ranges
 2721                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2722                    .map(|ranges| (ranges, snapshot, buffer))
 2723            })?;
 2724        use text::ToOffset as TO;
 2725        // find offset from the start of current range to current cursor position
 2726        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2727
 2728        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2729        let start_difference = start_offset - start_byte_offset;
 2730        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2731        let end_difference = end_offset - start_byte_offset;
 2732        // Current range has associated linked ranges.
 2733        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2734        for range in linked_ranges.iter() {
 2735            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2736            let end_offset = start_offset + end_difference;
 2737            let start_offset = start_offset + start_difference;
 2738            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2739                continue;
 2740            }
 2741            if self.selections.disjoint_anchor_ranges().any(|s| {
 2742                if s.start.buffer_id != selection.start.buffer_id
 2743                    || s.end.buffer_id != selection.end.buffer_id
 2744                {
 2745                    return false;
 2746                }
 2747                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2748                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2749            }) {
 2750                continue;
 2751            }
 2752            let start = buffer_snapshot.anchor_after(start_offset);
 2753            let end = buffer_snapshot.anchor_after(end_offset);
 2754            linked_edits
 2755                .entry(buffer.clone())
 2756                .or_default()
 2757                .push(start..end);
 2758        }
 2759        Some(linked_edits)
 2760    }
 2761
 2762    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2763        let text: Arc<str> = text.into();
 2764
 2765        if self.read_only(cx) {
 2766            return;
 2767        }
 2768
 2769        let selections = self.selections.all_adjusted(cx);
 2770        let mut bracket_inserted = false;
 2771        let mut edits = Vec::new();
 2772        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2773        let mut new_selections = Vec::with_capacity(selections.len());
 2774        let mut new_autoclose_regions = Vec::new();
 2775        let snapshot = self.buffer.read(cx).read(cx);
 2776
 2777        for (selection, autoclose_region) in
 2778            self.selections_with_autoclose_regions(selections, &snapshot)
 2779        {
 2780            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2781                // Determine if the inserted text matches the opening or closing
 2782                // bracket of any of this language's bracket pairs.
 2783                let mut bracket_pair = None;
 2784                let mut is_bracket_pair_start = false;
 2785                let mut is_bracket_pair_end = false;
 2786                if !text.is_empty() {
 2787                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2788                    //  and they are removing the character that triggered IME popup.
 2789                    for (pair, enabled) in scope.brackets() {
 2790                        if !pair.close && !pair.surround {
 2791                            continue;
 2792                        }
 2793
 2794                        if enabled && pair.start.ends_with(text.as_ref()) {
 2795                            let prefix_len = pair.start.len() - text.len();
 2796                            let preceding_text_matches_prefix = prefix_len == 0
 2797                                || (selection.start.column >= (prefix_len as u32)
 2798                                    && snapshot.contains_str_at(
 2799                                        Point::new(
 2800                                            selection.start.row,
 2801                                            selection.start.column - (prefix_len as u32),
 2802                                        ),
 2803                                        &pair.start[..prefix_len],
 2804                                    ));
 2805                            if preceding_text_matches_prefix {
 2806                                bracket_pair = Some(pair.clone());
 2807                                is_bracket_pair_start = true;
 2808                                break;
 2809                            }
 2810                        }
 2811                        if pair.end.as_str() == text.as_ref() {
 2812                            bracket_pair = Some(pair.clone());
 2813                            is_bracket_pair_end = true;
 2814                            break;
 2815                        }
 2816                    }
 2817                }
 2818
 2819                if let Some(bracket_pair) = bracket_pair {
 2820                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2821                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2822                    let auto_surround =
 2823                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2824                    if selection.is_empty() {
 2825                        if is_bracket_pair_start {
 2826                            // If the inserted text is a suffix of an opening bracket and the
 2827                            // selection is preceded by the rest of the opening bracket, then
 2828                            // insert the closing bracket.
 2829                            let following_text_allows_autoclose = snapshot
 2830                                .chars_at(selection.start)
 2831                                .next()
 2832                                .map_or(true, |c| scope.should_autoclose_before(c));
 2833
 2834                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2835                                && bracket_pair.start.len() == 1
 2836                            {
 2837                                let target = bracket_pair.start.chars().next().unwrap();
 2838                                let current_line_count = snapshot
 2839                                    .reversed_chars_at(selection.start)
 2840                                    .take_while(|&c| c != '\n')
 2841                                    .filter(|&c| c == target)
 2842                                    .count();
 2843                                current_line_count % 2 == 1
 2844                            } else {
 2845                                false
 2846                            };
 2847
 2848                            if autoclose
 2849                                && bracket_pair.close
 2850                                && following_text_allows_autoclose
 2851                                && !is_closing_quote
 2852                            {
 2853                                let anchor = snapshot.anchor_before(selection.end);
 2854                                new_selections.push((selection.map(|_| anchor), text.len()));
 2855                                new_autoclose_regions.push((
 2856                                    anchor,
 2857                                    text.len(),
 2858                                    selection.id,
 2859                                    bracket_pair.clone(),
 2860                                ));
 2861                                edits.push((
 2862                                    selection.range(),
 2863                                    format!("{}{}", text, bracket_pair.end).into(),
 2864                                ));
 2865                                bracket_inserted = true;
 2866                                continue;
 2867                            }
 2868                        }
 2869
 2870                        if let Some(region) = autoclose_region {
 2871                            // If the selection is followed by an auto-inserted closing bracket,
 2872                            // then don't insert that closing bracket again; just move the selection
 2873                            // past the closing bracket.
 2874                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2875                                && text.as_ref() == region.pair.end.as_str();
 2876                            if should_skip {
 2877                                let anchor = snapshot.anchor_after(selection.end);
 2878                                new_selections
 2879                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2880                                continue;
 2881                            }
 2882                        }
 2883
 2884                        let always_treat_brackets_as_autoclosed = snapshot
 2885                            .settings_at(selection.start, cx)
 2886                            .always_treat_brackets_as_autoclosed;
 2887                        if always_treat_brackets_as_autoclosed
 2888                            && is_bracket_pair_end
 2889                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2890                        {
 2891                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2892                            // and the inserted text is a closing bracket and the selection is followed
 2893                            // by the closing bracket then move the selection past the closing bracket.
 2894                            let anchor = snapshot.anchor_after(selection.end);
 2895                            new_selections.push((selection.map(|_| anchor), text.len()));
 2896                            continue;
 2897                        }
 2898                    }
 2899                    // If an opening bracket is 1 character long and is typed while
 2900                    // text is selected, then surround that text with the bracket pair.
 2901                    else if auto_surround
 2902                        && bracket_pair.surround
 2903                        && is_bracket_pair_start
 2904                        && bracket_pair.start.chars().count() == 1
 2905                    {
 2906                        edits.push((selection.start..selection.start, text.clone()));
 2907                        edits.push((
 2908                            selection.end..selection.end,
 2909                            bracket_pair.end.as_str().into(),
 2910                        ));
 2911                        bracket_inserted = true;
 2912                        new_selections.push((
 2913                            Selection {
 2914                                id: selection.id,
 2915                                start: snapshot.anchor_after(selection.start),
 2916                                end: snapshot.anchor_before(selection.end),
 2917                                reversed: selection.reversed,
 2918                                goal: selection.goal,
 2919                            },
 2920                            0,
 2921                        ));
 2922                        continue;
 2923                    }
 2924                }
 2925            }
 2926
 2927            if self.auto_replace_emoji_shortcode
 2928                && selection.is_empty()
 2929                && text.as_ref().ends_with(':')
 2930            {
 2931                if let Some(possible_emoji_short_code) =
 2932                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2933                {
 2934                    if !possible_emoji_short_code.is_empty() {
 2935                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2936                            let emoji_shortcode_start = Point::new(
 2937                                selection.start.row,
 2938                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2939                            );
 2940
 2941                            // Remove shortcode from buffer
 2942                            edits.push((
 2943                                emoji_shortcode_start..selection.start,
 2944                                "".to_string().into(),
 2945                            ));
 2946                            new_selections.push((
 2947                                Selection {
 2948                                    id: selection.id,
 2949                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2950                                    end: snapshot.anchor_before(selection.start),
 2951                                    reversed: selection.reversed,
 2952                                    goal: selection.goal,
 2953                                },
 2954                                0,
 2955                            ));
 2956
 2957                            // Insert emoji
 2958                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2959                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2960                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2961
 2962                            continue;
 2963                        }
 2964                    }
 2965                }
 2966            }
 2967
 2968            // If not handling any auto-close operation, then just replace the selected
 2969            // text with the given input and move the selection to the end of the
 2970            // newly inserted text.
 2971            let anchor = snapshot.anchor_after(selection.end);
 2972            if !self.linked_edit_ranges.is_empty() {
 2973                let start_anchor = snapshot.anchor_before(selection.start);
 2974
 2975                let is_word_char = text.chars().next().map_or(true, |char| {
 2976                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2977                    classifier.is_word(char)
 2978                });
 2979
 2980                if is_word_char {
 2981                    if let Some(ranges) = self
 2982                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2983                    {
 2984                        for (buffer, edits) in ranges {
 2985                            linked_edits
 2986                                .entry(buffer.clone())
 2987                                .or_default()
 2988                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2989                        }
 2990                    }
 2991                }
 2992            }
 2993
 2994            new_selections.push((selection.map(|_| anchor), 0));
 2995            edits.push((selection.start..selection.end, text.clone()));
 2996        }
 2997
 2998        drop(snapshot);
 2999
 3000        self.transact(window, cx, |this, window, cx| {
 3001            this.buffer.update(cx, |buffer, cx| {
 3002                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3003            });
 3004            for (buffer, edits) in linked_edits {
 3005                buffer.update(cx, |buffer, cx| {
 3006                    let snapshot = buffer.snapshot();
 3007                    let edits = edits
 3008                        .into_iter()
 3009                        .map(|(range, text)| {
 3010                            use text::ToPoint as TP;
 3011                            let end_point = TP::to_point(&range.end, &snapshot);
 3012                            let start_point = TP::to_point(&range.start, &snapshot);
 3013                            (start_point..end_point, text)
 3014                        })
 3015                        .sorted_by_key(|(range, _)| range.start)
 3016                        .collect::<Vec<_>>();
 3017                    buffer.edit(edits, None, cx);
 3018                })
 3019            }
 3020            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3021            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3022            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3023            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3024                .zip(new_selection_deltas)
 3025                .map(|(selection, delta)| Selection {
 3026                    id: selection.id,
 3027                    start: selection.start + delta,
 3028                    end: selection.end + delta,
 3029                    reversed: selection.reversed,
 3030                    goal: SelectionGoal::None,
 3031                })
 3032                .collect::<Vec<_>>();
 3033
 3034            let mut i = 0;
 3035            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3036                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3037                let start = map.buffer_snapshot.anchor_before(position);
 3038                let end = map.buffer_snapshot.anchor_after(position);
 3039                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3040                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3041                        Ordering::Less => i += 1,
 3042                        Ordering::Greater => break,
 3043                        Ordering::Equal => {
 3044                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3045                                Ordering::Less => i += 1,
 3046                                Ordering::Equal => break,
 3047                                Ordering::Greater => break,
 3048                            }
 3049                        }
 3050                    }
 3051                }
 3052                this.autoclose_regions.insert(
 3053                    i,
 3054                    AutocloseRegion {
 3055                        selection_id,
 3056                        range: start..end,
 3057                        pair,
 3058                    },
 3059                );
 3060            }
 3061
 3062            let had_active_inline_completion = this.has_active_inline_completion();
 3063            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3064                s.select(new_selections)
 3065            });
 3066
 3067            if !bracket_inserted {
 3068                if let Some(on_type_format_task) =
 3069                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3070                {
 3071                    on_type_format_task.detach_and_log_err(cx);
 3072                }
 3073            }
 3074
 3075            let editor_settings = EditorSettings::get_global(cx);
 3076            if bracket_inserted
 3077                && (editor_settings.auto_signature_help
 3078                    || editor_settings.show_signature_help_after_edits)
 3079            {
 3080                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3081            }
 3082
 3083            let trigger_in_words =
 3084                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3085            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3086            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3087            this.refresh_inline_completion(true, false, window, cx);
 3088        });
 3089    }
 3090
 3091    fn find_possible_emoji_shortcode_at_position(
 3092        snapshot: &MultiBufferSnapshot,
 3093        position: Point,
 3094    ) -> Option<String> {
 3095        let mut chars = Vec::new();
 3096        let mut found_colon = false;
 3097        for char in snapshot.reversed_chars_at(position).take(100) {
 3098            // Found a possible emoji shortcode in the middle of the buffer
 3099            if found_colon {
 3100                if char.is_whitespace() {
 3101                    chars.reverse();
 3102                    return Some(chars.iter().collect());
 3103                }
 3104                // If the previous character is not a whitespace, we are in the middle of a word
 3105                // and we only want to complete the shortcode if the word is made up of other emojis
 3106                let mut containing_word = String::new();
 3107                for ch in snapshot
 3108                    .reversed_chars_at(position)
 3109                    .skip(chars.len() + 1)
 3110                    .take(100)
 3111                {
 3112                    if ch.is_whitespace() {
 3113                        break;
 3114                    }
 3115                    containing_word.push(ch);
 3116                }
 3117                let containing_word = containing_word.chars().rev().collect::<String>();
 3118                if util::word_consists_of_emojis(containing_word.as_str()) {
 3119                    chars.reverse();
 3120                    return Some(chars.iter().collect());
 3121                }
 3122            }
 3123
 3124            if char.is_whitespace() || !char.is_ascii() {
 3125                return None;
 3126            }
 3127            if char == ':' {
 3128                found_colon = true;
 3129            } else {
 3130                chars.push(char);
 3131            }
 3132        }
 3133        // Found a possible emoji shortcode at the beginning of the buffer
 3134        chars.reverse();
 3135        Some(chars.iter().collect())
 3136    }
 3137
 3138    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3139        self.transact(window, cx, |this, window, cx| {
 3140            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3141                let selections = this.selections.all::<usize>(cx);
 3142                let multi_buffer = this.buffer.read(cx);
 3143                let buffer = multi_buffer.snapshot(cx);
 3144                selections
 3145                    .iter()
 3146                    .map(|selection| {
 3147                        let start_point = selection.start.to_point(&buffer);
 3148                        let mut indent =
 3149                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3150                        indent.len = cmp::min(indent.len, start_point.column);
 3151                        let start = selection.start;
 3152                        let end = selection.end;
 3153                        let selection_is_empty = start == end;
 3154                        let language_scope = buffer.language_scope_at(start);
 3155                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3156                            &language_scope
 3157                        {
 3158                            let leading_whitespace_len = buffer
 3159                                .reversed_chars_at(start)
 3160                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3161                                .map(|c| c.len_utf8())
 3162                                .sum::<usize>();
 3163
 3164                            let trailing_whitespace_len = buffer
 3165                                .chars_at(end)
 3166                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3167                                .map(|c| c.len_utf8())
 3168                                .sum::<usize>();
 3169
 3170                            let insert_extra_newline =
 3171                                language.brackets().any(|(pair, enabled)| {
 3172                                    let pair_start = pair.start.trim_end();
 3173                                    let pair_end = pair.end.trim_start();
 3174
 3175                                    enabled
 3176                                        && pair.newline
 3177                                        && buffer.contains_str_at(
 3178                                            end + trailing_whitespace_len,
 3179                                            pair_end,
 3180                                        )
 3181                                        && buffer.contains_str_at(
 3182                                            (start - leading_whitespace_len)
 3183                                                .saturating_sub(pair_start.len()),
 3184                                            pair_start,
 3185                                        )
 3186                                });
 3187
 3188                            // Comment extension on newline is allowed only for cursor selections
 3189                            let comment_delimiter = maybe!({
 3190                                if !selection_is_empty {
 3191                                    return None;
 3192                                }
 3193
 3194                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3195                                    return None;
 3196                                }
 3197
 3198                                let delimiters = language.line_comment_prefixes();
 3199                                let max_len_of_delimiter =
 3200                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3201                                let (snapshot, range) =
 3202                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3203
 3204                                let mut index_of_first_non_whitespace = 0;
 3205                                let comment_candidate = snapshot
 3206                                    .chars_for_range(range)
 3207                                    .skip_while(|c| {
 3208                                        let should_skip = c.is_whitespace();
 3209                                        if should_skip {
 3210                                            index_of_first_non_whitespace += 1;
 3211                                        }
 3212                                        should_skip
 3213                                    })
 3214                                    .take(max_len_of_delimiter)
 3215                                    .collect::<String>();
 3216                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3217                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3218                                })?;
 3219                                let cursor_is_placed_after_comment_marker =
 3220                                    index_of_first_non_whitespace + comment_prefix.len()
 3221                                        <= start_point.column as usize;
 3222                                if cursor_is_placed_after_comment_marker {
 3223                                    Some(comment_prefix.clone())
 3224                                } else {
 3225                                    None
 3226                                }
 3227                            });
 3228                            (comment_delimiter, insert_extra_newline)
 3229                        } else {
 3230                            (None, false)
 3231                        };
 3232
 3233                        let capacity_for_delimiter = comment_delimiter
 3234                            .as_deref()
 3235                            .map(str::len)
 3236                            .unwrap_or_default();
 3237                        let mut new_text =
 3238                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3239                        new_text.push('\n');
 3240                        new_text.extend(indent.chars());
 3241                        if let Some(delimiter) = &comment_delimiter {
 3242                            new_text.push_str(delimiter);
 3243                        }
 3244                        if insert_extra_newline {
 3245                            new_text = new_text.repeat(2);
 3246                        }
 3247
 3248                        let anchor = buffer.anchor_after(end);
 3249                        let new_selection = selection.map(|_| anchor);
 3250                        (
 3251                            (start..end, new_text),
 3252                            (insert_extra_newline, new_selection),
 3253                        )
 3254                    })
 3255                    .unzip()
 3256            };
 3257
 3258            this.edit_with_autoindent(edits, cx);
 3259            let buffer = this.buffer.read(cx).snapshot(cx);
 3260            let new_selections = selection_fixup_info
 3261                .into_iter()
 3262                .map(|(extra_newline_inserted, new_selection)| {
 3263                    let mut cursor = new_selection.end.to_point(&buffer);
 3264                    if extra_newline_inserted {
 3265                        cursor.row -= 1;
 3266                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3267                    }
 3268                    new_selection.map(|_| cursor)
 3269                })
 3270                .collect();
 3271
 3272            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3273                s.select(new_selections)
 3274            });
 3275            this.refresh_inline_completion(true, false, window, cx);
 3276        });
 3277    }
 3278
 3279    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3280        let buffer = self.buffer.read(cx);
 3281        let snapshot = buffer.snapshot(cx);
 3282
 3283        let mut edits = Vec::new();
 3284        let mut rows = Vec::new();
 3285
 3286        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3287            let cursor = selection.head();
 3288            let row = cursor.row;
 3289
 3290            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3291
 3292            let newline = "\n".to_string();
 3293            edits.push((start_of_line..start_of_line, newline));
 3294
 3295            rows.push(row + rows_inserted as u32);
 3296        }
 3297
 3298        self.transact(window, cx, |editor, window, cx| {
 3299            editor.edit(edits, cx);
 3300
 3301            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3302                let mut index = 0;
 3303                s.move_cursors_with(|map, _, _| {
 3304                    let row = rows[index];
 3305                    index += 1;
 3306
 3307                    let point = Point::new(row, 0);
 3308                    let boundary = map.next_line_boundary(point).1;
 3309                    let clipped = map.clip_point(boundary, Bias::Left);
 3310
 3311                    (clipped, SelectionGoal::None)
 3312                });
 3313            });
 3314
 3315            let mut indent_edits = Vec::new();
 3316            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3317            for row in rows {
 3318                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3319                for (row, indent) in indents {
 3320                    if indent.len == 0 {
 3321                        continue;
 3322                    }
 3323
 3324                    let text = match indent.kind {
 3325                        IndentKind::Space => " ".repeat(indent.len as usize),
 3326                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3327                    };
 3328                    let point = Point::new(row.0, 0);
 3329                    indent_edits.push((point..point, text));
 3330                }
 3331            }
 3332            editor.edit(indent_edits, cx);
 3333        });
 3334    }
 3335
 3336    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3337        let buffer = self.buffer.read(cx);
 3338        let snapshot = buffer.snapshot(cx);
 3339
 3340        let mut edits = Vec::new();
 3341        let mut rows = Vec::new();
 3342        let mut rows_inserted = 0;
 3343
 3344        for selection in self.selections.all_adjusted(cx) {
 3345            let cursor = selection.head();
 3346            let row = cursor.row;
 3347
 3348            let point = Point::new(row + 1, 0);
 3349            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3350
 3351            let newline = "\n".to_string();
 3352            edits.push((start_of_line..start_of_line, newline));
 3353
 3354            rows_inserted += 1;
 3355            rows.push(row + rows_inserted);
 3356        }
 3357
 3358        self.transact(window, cx, |editor, window, cx| {
 3359            editor.edit(edits, cx);
 3360
 3361            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3362                let mut index = 0;
 3363                s.move_cursors_with(|map, _, _| {
 3364                    let row = rows[index];
 3365                    index += 1;
 3366
 3367                    let point = Point::new(row, 0);
 3368                    let boundary = map.next_line_boundary(point).1;
 3369                    let clipped = map.clip_point(boundary, Bias::Left);
 3370
 3371                    (clipped, SelectionGoal::None)
 3372                });
 3373            });
 3374
 3375            let mut indent_edits = Vec::new();
 3376            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3377            for row in rows {
 3378                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3379                for (row, indent) in indents {
 3380                    if indent.len == 0 {
 3381                        continue;
 3382                    }
 3383
 3384                    let text = match indent.kind {
 3385                        IndentKind::Space => " ".repeat(indent.len as usize),
 3386                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3387                    };
 3388                    let point = Point::new(row.0, 0);
 3389                    indent_edits.push((point..point, text));
 3390                }
 3391            }
 3392            editor.edit(indent_edits, cx);
 3393        });
 3394    }
 3395
 3396    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3397        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3398            original_indent_columns: Vec::new(),
 3399        });
 3400        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3401    }
 3402
 3403    fn insert_with_autoindent_mode(
 3404        &mut self,
 3405        text: &str,
 3406        autoindent_mode: Option<AutoindentMode>,
 3407        window: &mut Window,
 3408        cx: &mut Context<Self>,
 3409    ) {
 3410        if self.read_only(cx) {
 3411            return;
 3412        }
 3413
 3414        let text: Arc<str> = text.into();
 3415        self.transact(window, cx, |this, window, cx| {
 3416            let old_selections = this.selections.all_adjusted(cx);
 3417            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3418                let anchors = {
 3419                    let snapshot = buffer.read(cx);
 3420                    old_selections
 3421                        .iter()
 3422                        .map(|s| {
 3423                            let anchor = snapshot.anchor_after(s.head());
 3424                            s.map(|_| anchor)
 3425                        })
 3426                        .collect::<Vec<_>>()
 3427                };
 3428                buffer.edit(
 3429                    old_selections
 3430                        .iter()
 3431                        .map(|s| (s.start..s.end, text.clone())),
 3432                    autoindent_mode,
 3433                    cx,
 3434                );
 3435                anchors
 3436            });
 3437
 3438            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3439                s.select_anchors(selection_anchors);
 3440            });
 3441
 3442            cx.notify();
 3443        });
 3444    }
 3445
 3446    fn trigger_completion_on_input(
 3447        &mut self,
 3448        text: &str,
 3449        trigger_in_words: bool,
 3450        window: &mut Window,
 3451        cx: &mut Context<Self>,
 3452    ) {
 3453        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3454            self.show_completions(
 3455                &ShowCompletions {
 3456                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3457                },
 3458                window,
 3459                cx,
 3460            );
 3461        } else {
 3462            self.hide_context_menu(window, cx);
 3463        }
 3464    }
 3465
 3466    fn is_completion_trigger(
 3467        &self,
 3468        text: &str,
 3469        trigger_in_words: bool,
 3470        cx: &mut Context<Self>,
 3471    ) -> bool {
 3472        let position = self.selections.newest_anchor().head();
 3473        let multibuffer = self.buffer.read(cx);
 3474        let Some(buffer) = position
 3475            .buffer_id
 3476            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3477        else {
 3478            return false;
 3479        };
 3480
 3481        if let Some(completion_provider) = &self.completion_provider {
 3482            completion_provider.is_completion_trigger(
 3483                &buffer,
 3484                position.text_anchor,
 3485                text,
 3486                trigger_in_words,
 3487                cx,
 3488            )
 3489        } else {
 3490            false
 3491        }
 3492    }
 3493
 3494    /// If any empty selections is touching the start of its innermost containing autoclose
 3495    /// region, expand it to select the brackets.
 3496    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3497        let selections = self.selections.all::<usize>(cx);
 3498        let buffer = self.buffer.read(cx).read(cx);
 3499        let new_selections = self
 3500            .selections_with_autoclose_regions(selections, &buffer)
 3501            .map(|(mut selection, region)| {
 3502                if !selection.is_empty() {
 3503                    return selection;
 3504                }
 3505
 3506                if let Some(region) = region {
 3507                    let mut range = region.range.to_offset(&buffer);
 3508                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3509                        range.start -= region.pair.start.len();
 3510                        if buffer.contains_str_at(range.start, &region.pair.start)
 3511                            && buffer.contains_str_at(range.end, &region.pair.end)
 3512                        {
 3513                            range.end += region.pair.end.len();
 3514                            selection.start = range.start;
 3515                            selection.end = range.end;
 3516
 3517                            return selection;
 3518                        }
 3519                    }
 3520                }
 3521
 3522                let always_treat_brackets_as_autoclosed = buffer
 3523                    .settings_at(selection.start, cx)
 3524                    .always_treat_brackets_as_autoclosed;
 3525
 3526                if !always_treat_brackets_as_autoclosed {
 3527                    return selection;
 3528                }
 3529
 3530                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3531                    for (pair, enabled) in scope.brackets() {
 3532                        if !enabled || !pair.close {
 3533                            continue;
 3534                        }
 3535
 3536                        if buffer.contains_str_at(selection.start, &pair.end) {
 3537                            let pair_start_len = pair.start.len();
 3538                            if buffer.contains_str_at(
 3539                                selection.start.saturating_sub(pair_start_len),
 3540                                &pair.start,
 3541                            ) {
 3542                                selection.start -= pair_start_len;
 3543                                selection.end += pair.end.len();
 3544
 3545                                return selection;
 3546                            }
 3547                        }
 3548                    }
 3549                }
 3550
 3551                selection
 3552            })
 3553            .collect();
 3554
 3555        drop(buffer);
 3556        self.change_selections(None, window, cx, |selections| {
 3557            selections.select(new_selections)
 3558        });
 3559    }
 3560
 3561    /// Iterate the given selections, and for each one, find the smallest surrounding
 3562    /// autoclose region. This uses the ordering of the selections and the autoclose
 3563    /// regions to avoid repeated comparisons.
 3564    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3565        &'a self,
 3566        selections: impl IntoIterator<Item = Selection<D>>,
 3567        buffer: &'a MultiBufferSnapshot,
 3568    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3569        let mut i = 0;
 3570        let mut regions = self.autoclose_regions.as_slice();
 3571        selections.into_iter().map(move |selection| {
 3572            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3573
 3574            let mut enclosing = None;
 3575            while let Some(pair_state) = regions.get(i) {
 3576                if pair_state.range.end.to_offset(buffer) < range.start {
 3577                    regions = &regions[i + 1..];
 3578                    i = 0;
 3579                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3580                    break;
 3581                } else {
 3582                    if pair_state.selection_id == selection.id {
 3583                        enclosing = Some(pair_state);
 3584                    }
 3585                    i += 1;
 3586                }
 3587            }
 3588
 3589            (selection, enclosing)
 3590        })
 3591    }
 3592
 3593    /// Remove any autoclose regions that no longer contain their selection.
 3594    fn invalidate_autoclose_regions(
 3595        &mut self,
 3596        mut selections: &[Selection<Anchor>],
 3597        buffer: &MultiBufferSnapshot,
 3598    ) {
 3599        self.autoclose_regions.retain(|state| {
 3600            let mut i = 0;
 3601            while let Some(selection) = selections.get(i) {
 3602                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3603                    selections = &selections[1..];
 3604                    continue;
 3605                }
 3606                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3607                    break;
 3608                }
 3609                if selection.id == state.selection_id {
 3610                    return true;
 3611                } else {
 3612                    i += 1;
 3613                }
 3614            }
 3615            false
 3616        });
 3617    }
 3618
 3619    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3620        let offset = position.to_offset(buffer);
 3621        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3622        if offset > word_range.start && kind == Some(CharKind::Word) {
 3623            Some(
 3624                buffer
 3625                    .text_for_range(word_range.start..offset)
 3626                    .collect::<String>(),
 3627            )
 3628        } else {
 3629            None
 3630        }
 3631    }
 3632
 3633    pub fn toggle_inlay_hints(
 3634        &mut self,
 3635        _: &ToggleInlayHints,
 3636        _: &mut Window,
 3637        cx: &mut Context<Self>,
 3638    ) {
 3639        self.refresh_inlay_hints(
 3640            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3641            cx,
 3642        );
 3643    }
 3644
 3645    pub fn inlay_hints_enabled(&self) -> bool {
 3646        self.inlay_hint_cache.enabled
 3647    }
 3648
 3649    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3650        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3651            return;
 3652        }
 3653
 3654        let reason_description = reason.description();
 3655        let ignore_debounce = matches!(
 3656            reason,
 3657            InlayHintRefreshReason::SettingsChange(_)
 3658                | InlayHintRefreshReason::Toggle(_)
 3659                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3660        );
 3661        let (invalidate_cache, required_languages) = match reason {
 3662            InlayHintRefreshReason::Toggle(enabled) => {
 3663                self.inlay_hint_cache.enabled = enabled;
 3664                if enabled {
 3665                    (InvalidationStrategy::RefreshRequested, None)
 3666                } else {
 3667                    self.inlay_hint_cache.clear();
 3668                    self.splice_inlays(
 3669                        &self
 3670                            .visible_inlay_hints(cx)
 3671                            .iter()
 3672                            .map(|inlay| inlay.id)
 3673                            .collect::<Vec<InlayId>>(),
 3674                        Vec::new(),
 3675                        cx,
 3676                    );
 3677                    return;
 3678                }
 3679            }
 3680            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3681                match self.inlay_hint_cache.update_settings(
 3682                    &self.buffer,
 3683                    new_settings,
 3684                    self.visible_inlay_hints(cx),
 3685                    cx,
 3686                ) {
 3687                    ControlFlow::Break(Some(InlaySplice {
 3688                        to_remove,
 3689                        to_insert,
 3690                    })) => {
 3691                        self.splice_inlays(&to_remove, to_insert, cx);
 3692                        return;
 3693                    }
 3694                    ControlFlow::Break(None) => return,
 3695                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3696                }
 3697            }
 3698            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3699                if let Some(InlaySplice {
 3700                    to_remove,
 3701                    to_insert,
 3702                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3703                {
 3704                    self.splice_inlays(&to_remove, to_insert, cx);
 3705                }
 3706                return;
 3707            }
 3708            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3709            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3710                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3711            }
 3712            InlayHintRefreshReason::RefreshRequested => {
 3713                (InvalidationStrategy::RefreshRequested, None)
 3714            }
 3715        };
 3716
 3717        if let Some(InlaySplice {
 3718            to_remove,
 3719            to_insert,
 3720        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3721            reason_description,
 3722            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3723            invalidate_cache,
 3724            ignore_debounce,
 3725            cx,
 3726        ) {
 3727            self.splice_inlays(&to_remove, to_insert, cx);
 3728        }
 3729    }
 3730
 3731    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3732        self.display_map
 3733            .read(cx)
 3734            .current_inlays()
 3735            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3736            .cloned()
 3737            .collect()
 3738    }
 3739
 3740    pub fn excerpts_for_inlay_hints_query(
 3741        &self,
 3742        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3743        cx: &mut Context<Editor>,
 3744    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3745        let Some(project) = self.project.as_ref() else {
 3746            return HashMap::default();
 3747        };
 3748        let project = project.read(cx);
 3749        let multi_buffer = self.buffer().read(cx);
 3750        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3751        let multi_buffer_visible_start = self
 3752            .scroll_manager
 3753            .anchor()
 3754            .anchor
 3755            .to_point(&multi_buffer_snapshot);
 3756        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3757            multi_buffer_visible_start
 3758                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3759            Bias::Left,
 3760        );
 3761        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3762        multi_buffer_snapshot
 3763            .range_to_buffer_ranges(multi_buffer_visible_range)
 3764            .into_iter()
 3765            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3766            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3767                let buffer_file = project::File::from_dyn(buffer.file())?;
 3768                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3769                let worktree_entry = buffer_worktree
 3770                    .read(cx)
 3771                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3772                if worktree_entry.is_ignored {
 3773                    return None;
 3774                }
 3775
 3776                let language = buffer.language()?;
 3777                if let Some(restrict_to_languages) = restrict_to_languages {
 3778                    if !restrict_to_languages.contains(language) {
 3779                        return None;
 3780                    }
 3781                }
 3782                Some((
 3783                    excerpt_id,
 3784                    (
 3785                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3786                        buffer.version().clone(),
 3787                        excerpt_visible_range,
 3788                    ),
 3789                ))
 3790            })
 3791            .collect()
 3792    }
 3793
 3794    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3795        TextLayoutDetails {
 3796            text_system: window.text_system().clone(),
 3797            editor_style: self.style.clone().unwrap(),
 3798            rem_size: window.rem_size(),
 3799            scroll_anchor: self.scroll_manager.anchor(),
 3800            visible_rows: self.visible_line_count(),
 3801            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3802        }
 3803    }
 3804
 3805    pub fn splice_inlays(
 3806        &self,
 3807        to_remove: &[InlayId],
 3808        to_insert: Vec<Inlay>,
 3809        cx: &mut Context<Self>,
 3810    ) {
 3811        self.display_map.update(cx, |display_map, cx| {
 3812            display_map.splice_inlays(to_remove, to_insert, cx)
 3813        });
 3814        cx.notify();
 3815    }
 3816
 3817    fn trigger_on_type_formatting(
 3818        &self,
 3819        input: String,
 3820        window: &mut Window,
 3821        cx: &mut Context<Self>,
 3822    ) -> Option<Task<Result<()>>> {
 3823        if input.len() != 1 {
 3824            return None;
 3825        }
 3826
 3827        let project = self.project.as_ref()?;
 3828        let position = self.selections.newest_anchor().head();
 3829        let (buffer, buffer_position) = self
 3830            .buffer
 3831            .read(cx)
 3832            .text_anchor_for_position(position, cx)?;
 3833
 3834        let settings = language_settings::language_settings(
 3835            buffer
 3836                .read(cx)
 3837                .language_at(buffer_position)
 3838                .map(|l| l.name()),
 3839            buffer.read(cx).file(),
 3840            cx,
 3841        );
 3842        if !settings.use_on_type_format {
 3843            return None;
 3844        }
 3845
 3846        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3847        // hence we do LSP request & edit on host side only — add formats to host's history.
 3848        let push_to_lsp_host_history = true;
 3849        // If this is not the host, append its history with new edits.
 3850        let push_to_client_history = project.read(cx).is_via_collab();
 3851
 3852        let on_type_formatting = project.update(cx, |project, cx| {
 3853            project.on_type_format(
 3854                buffer.clone(),
 3855                buffer_position,
 3856                input,
 3857                push_to_lsp_host_history,
 3858                cx,
 3859            )
 3860        });
 3861        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3862            if let Some(transaction) = on_type_formatting.await? {
 3863                if push_to_client_history {
 3864                    buffer
 3865                        .update(&mut cx, |buffer, _| {
 3866                            buffer.push_transaction(transaction, Instant::now());
 3867                        })
 3868                        .ok();
 3869                }
 3870                editor.update(&mut cx, |editor, cx| {
 3871                    editor.refresh_document_highlights(cx);
 3872                })?;
 3873            }
 3874            Ok(())
 3875        }))
 3876    }
 3877
 3878    pub fn show_completions(
 3879        &mut self,
 3880        options: &ShowCompletions,
 3881        window: &mut Window,
 3882        cx: &mut Context<Self>,
 3883    ) {
 3884        if self.pending_rename.is_some() {
 3885            return;
 3886        }
 3887
 3888        let Some(provider) = self.completion_provider.as_ref() else {
 3889            return;
 3890        };
 3891
 3892        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3893            return;
 3894        }
 3895
 3896        let position = self.selections.newest_anchor().head();
 3897        if position.diff_base_anchor.is_some() {
 3898            return;
 3899        }
 3900        let (buffer, buffer_position) =
 3901            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3902                output
 3903            } else {
 3904                return;
 3905            };
 3906        let show_completion_documentation = buffer
 3907            .read(cx)
 3908            .snapshot()
 3909            .settings_at(buffer_position, cx)
 3910            .show_completion_documentation;
 3911
 3912        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3913
 3914        let trigger_kind = match &options.trigger {
 3915            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3916                CompletionTriggerKind::TRIGGER_CHARACTER
 3917            }
 3918            _ => CompletionTriggerKind::INVOKED,
 3919        };
 3920        let completion_context = CompletionContext {
 3921            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3922                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3923                    Some(String::from(trigger))
 3924                } else {
 3925                    None
 3926                }
 3927            }),
 3928            trigger_kind,
 3929        };
 3930        let completions =
 3931            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3932        let sort_completions = provider.sort_completions();
 3933
 3934        let id = post_inc(&mut self.next_completion_id);
 3935        let task = cx.spawn_in(window, |editor, mut cx| {
 3936            async move {
 3937                editor.update(&mut cx, |this, _| {
 3938                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3939                })?;
 3940                let completions = completions.await.log_err();
 3941                let menu = if let Some(completions) = completions {
 3942                    let mut menu = CompletionsMenu::new(
 3943                        id,
 3944                        sort_completions,
 3945                        show_completion_documentation,
 3946                        position,
 3947                        buffer.clone(),
 3948                        completions.into(),
 3949                    );
 3950
 3951                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3952                        .await;
 3953
 3954                    menu.visible().then_some(menu)
 3955                } else {
 3956                    None
 3957                };
 3958
 3959                editor.update_in(&mut cx, |editor, window, cx| {
 3960                    match editor.context_menu.borrow().as_ref() {
 3961                        None => {}
 3962                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3963                            if prev_menu.id > id {
 3964                                return;
 3965                            }
 3966                        }
 3967                        _ => return,
 3968                    }
 3969
 3970                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3971                        let mut menu = menu.unwrap();
 3972                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3973
 3974                        *editor.context_menu.borrow_mut() =
 3975                            Some(CodeContextMenu::Completions(menu));
 3976
 3977                        if editor.show_edit_predictions_in_menu() {
 3978                            editor.update_visible_inline_completion(window, cx);
 3979                        } else {
 3980                            editor.discard_inline_completion(false, cx);
 3981                        }
 3982
 3983                        cx.notify();
 3984                    } else if editor.completion_tasks.len() <= 1 {
 3985                        // If there are no more completion tasks and the last menu was
 3986                        // empty, we should hide it.
 3987                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3988                        // If it was already hidden and we don't show inline
 3989                        // completions in the menu, we should also show the
 3990                        // inline-completion when available.
 3991                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3992                            editor.update_visible_inline_completion(window, cx);
 3993                        }
 3994                    }
 3995                })?;
 3996
 3997                Ok::<_, anyhow::Error>(())
 3998            }
 3999            .log_err()
 4000        });
 4001
 4002        self.completion_tasks.push((id, task));
 4003    }
 4004
 4005    pub fn confirm_completion(
 4006        &mut self,
 4007        action: &ConfirmCompletion,
 4008        window: &mut Window,
 4009        cx: &mut Context<Self>,
 4010    ) -> Option<Task<Result<()>>> {
 4011        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4012    }
 4013
 4014    pub fn compose_completion(
 4015        &mut self,
 4016        action: &ComposeCompletion,
 4017        window: &mut Window,
 4018        cx: &mut Context<Self>,
 4019    ) -> Option<Task<Result<()>>> {
 4020        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4021    }
 4022
 4023    fn do_completion(
 4024        &mut self,
 4025        item_ix: Option<usize>,
 4026        intent: CompletionIntent,
 4027        window: &mut Window,
 4028        cx: &mut Context<Editor>,
 4029    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4030        use language::ToOffset as _;
 4031
 4032        let completions_menu =
 4033            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4034                menu
 4035            } else {
 4036                return None;
 4037            };
 4038
 4039        let entries = completions_menu.entries.borrow();
 4040        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4041        if self.show_edit_predictions_in_menu() {
 4042            self.discard_inline_completion(true, cx);
 4043        }
 4044        let candidate_id = mat.candidate_id;
 4045        drop(entries);
 4046
 4047        let buffer_handle = completions_menu.buffer;
 4048        let completion = completions_menu
 4049            .completions
 4050            .borrow()
 4051            .get(candidate_id)?
 4052            .clone();
 4053        cx.stop_propagation();
 4054
 4055        let snippet;
 4056        let text;
 4057
 4058        if completion.is_snippet() {
 4059            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4060            text = snippet.as_ref().unwrap().text.clone();
 4061        } else {
 4062            snippet = None;
 4063            text = completion.new_text.clone();
 4064        };
 4065        let selections = self.selections.all::<usize>(cx);
 4066        let buffer = buffer_handle.read(cx);
 4067        let old_range = completion.old_range.to_offset(buffer);
 4068        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4069
 4070        let newest_selection = self.selections.newest_anchor();
 4071        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4072            return None;
 4073        }
 4074
 4075        let lookbehind = newest_selection
 4076            .start
 4077            .text_anchor
 4078            .to_offset(buffer)
 4079            .saturating_sub(old_range.start);
 4080        let lookahead = old_range
 4081            .end
 4082            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4083        let mut common_prefix_len = old_text
 4084            .bytes()
 4085            .zip(text.bytes())
 4086            .take_while(|(a, b)| a == b)
 4087            .count();
 4088
 4089        let snapshot = self.buffer.read(cx).snapshot(cx);
 4090        let mut range_to_replace: Option<Range<isize>> = None;
 4091        let mut ranges = Vec::new();
 4092        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4093        for selection in &selections {
 4094            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4095                let start = selection.start.saturating_sub(lookbehind);
 4096                let end = selection.end + lookahead;
 4097                if selection.id == newest_selection.id {
 4098                    range_to_replace = Some(
 4099                        ((start + common_prefix_len) as isize - selection.start as isize)
 4100                            ..(end as isize - selection.start as isize),
 4101                    );
 4102                }
 4103                ranges.push(start + common_prefix_len..end);
 4104            } else {
 4105                common_prefix_len = 0;
 4106                ranges.clear();
 4107                ranges.extend(selections.iter().map(|s| {
 4108                    if s.id == newest_selection.id {
 4109                        range_to_replace = Some(
 4110                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4111                                - selection.start as isize
 4112                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4113                                    - selection.start as isize,
 4114                        );
 4115                        old_range.clone()
 4116                    } else {
 4117                        s.start..s.end
 4118                    }
 4119                }));
 4120                break;
 4121            }
 4122            if !self.linked_edit_ranges.is_empty() {
 4123                let start_anchor = snapshot.anchor_before(selection.head());
 4124                let end_anchor = snapshot.anchor_after(selection.tail());
 4125                if let Some(ranges) = self
 4126                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4127                {
 4128                    for (buffer, edits) in ranges {
 4129                        linked_edits.entry(buffer.clone()).or_default().extend(
 4130                            edits
 4131                                .into_iter()
 4132                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4133                        );
 4134                    }
 4135                }
 4136            }
 4137        }
 4138        let text = &text[common_prefix_len..];
 4139
 4140        cx.emit(EditorEvent::InputHandled {
 4141            utf16_range_to_replace: range_to_replace,
 4142            text: text.into(),
 4143        });
 4144
 4145        self.transact(window, cx, |this, window, cx| {
 4146            if let Some(mut snippet) = snippet {
 4147                snippet.text = text.to_string();
 4148                for tabstop in snippet
 4149                    .tabstops
 4150                    .iter_mut()
 4151                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4152                {
 4153                    tabstop.start -= common_prefix_len as isize;
 4154                    tabstop.end -= common_prefix_len as isize;
 4155                }
 4156
 4157                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4158            } else {
 4159                this.buffer.update(cx, |buffer, cx| {
 4160                    buffer.edit(
 4161                        ranges.iter().map(|range| (range.clone(), text)),
 4162                        this.autoindent_mode.clone(),
 4163                        cx,
 4164                    );
 4165                });
 4166            }
 4167            for (buffer, edits) in linked_edits {
 4168                buffer.update(cx, |buffer, cx| {
 4169                    let snapshot = buffer.snapshot();
 4170                    let edits = edits
 4171                        .into_iter()
 4172                        .map(|(range, text)| {
 4173                            use text::ToPoint as TP;
 4174                            let end_point = TP::to_point(&range.end, &snapshot);
 4175                            let start_point = TP::to_point(&range.start, &snapshot);
 4176                            (start_point..end_point, text)
 4177                        })
 4178                        .sorted_by_key(|(range, _)| range.start)
 4179                        .collect::<Vec<_>>();
 4180                    buffer.edit(edits, None, cx);
 4181                })
 4182            }
 4183
 4184            this.refresh_inline_completion(true, false, window, cx);
 4185        });
 4186
 4187        let show_new_completions_on_confirm = completion
 4188            .confirm
 4189            .as_ref()
 4190            .map_or(false, |confirm| confirm(intent, window, cx));
 4191        if show_new_completions_on_confirm {
 4192            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4193        }
 4194
 4195        let provider = self.completion_provider.as_ref()?;
 4196        drop(completion);
 4197        let apply_edits = provider.apply_additional_edits_for_completion(
 4198            buffer_handle,
 4199            completions_menu.completions.clone(),
 4200            candidate_id,
 4201            true,
 4202            cx,
 4203        );
 4204
 4205        let editor_settings = EditorSettings::get_global(cx);
 4206        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4207            // After the code completion is finished, users often want to know what signatures are needed.
 4208            // so we should automatically call signature_help
 4209            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4210        }
 4211
 4212        Some(cx.foreground_executor().spawn(async move {
 4213            apply_edits.await?;
 4214            Ok(())
 4215        }))
 4216    }
 4217
 4218    pub fn toggle_code_actions(
 4219        &mut self,
 4220        action: &ToggleCodeActions,
 4221        window: &mut Window,
 4222        cx: &mut Context<Self>,
 4223    ) {
 4224        let mut context_menu = self.context_menu.borrow_mut();
 4225        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4226            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4227                // Toggle if we're selecting the same one
 4228                *context_menu = None;
 4229                cx.notify();
 4230                return;
 4231            } else {
 4232                // Otherwise, clear it and start a new one
 4233                *context_menu = None;
 4234                cx.notify();
 4235            }
 4236        }
 4237        drop(context_menu);
 4238        let snapshot = self.snapshot(window, cx);
 4239        let deployed_from_indicator = action.deployed_from_indicator;
 4240        let mut task = self.code_actions_task.take();
 4241        let action = action.clone();
 4242        cx.spawn_in(window, |editor, mut cx| async move {
 4243            while let Some(prev_task) = task {
 4244                prev_task.await.log_err();
 4245                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4246            }
 4247
 4248            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4249                if editor.focus_handle.is_focused(window) {
 4250                    let multibuffer_point = action
 4251                        .deployed_from_indicator
 4252                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4253                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4254                    let (buffer, buffer_row) = snapshot
 4255                        .buffer_snapshot
 4256                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4257                        .and_then(|(buffer_snapshot, range)| {
 4258                            editor
 4259                                .buffer
 4260                                .read(cx)
 4261                                .buffer(buffer_snapshot.remote_id())
 4262                                .map(|buffer| (buffer, range.start.row))
 4263                        })?;
 4264                    let (_, code_actions) = editor
 4265                        .available_code_actions
 4266                        .clone()
 4267                        .and_then(|(location, code_actions)| {
 4268                            let snapshot = location.buffer.read(cx).snapshot();
 4269                            let point_range = location.range.to_point(&snapshot);
 4270                            let point_range = point_range.start.row..=point_range.end.row;
 4271                            if point_range.contains(&buffer_row) {
 4272                                Some((location, code_actions))
 4273                            } else {
 4274                                None
 4275                            }
 4276                        })
 4277                        .unzip();
 4278                    let buffer_id = buffer.read(cx).remote_id();
 4279                    let tasks = editor
 4280                        .tasks
 4281                        .get(&(buffer_id, buffer_row))
 4282                        .map(|t| Arc::new(t.to_owned()));
 4283                    if tasks.is_none() && code_actions.is_none() {
 4284                        return None;
 4285                    }
 4286
 4287                    editor.completion_tasks.clear();
 4288                    editor.discard_inline_completion(false, cx);
 4289                    let task_context =
 4290                        tasks
 4291                            .as_ref()
 4292                            .zip(editor.project.clone())
 4293                            .map(|(tasks, project)| {
 4294                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4295                            });
 4296
 4297                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4298                        let task_context = match task_context {
 4299                            Some(task_context) => task_context.await,
 4300                            None => None,
 4301                        };
 4302                        let resolved_tasks =
 4303                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4304                                Rc::new(ResolvedTasks {
 4305                                    templates: tasks.resolve(&task_context).collect(),
 4306                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4307                                        multibuffer_point.row,
 4308                                        tasks.column,
 4309                                    )),
 4310                                })
 4311                            });
 4312                        let spawn_straight_away = resolved_tasks
 4313                            .as_ref()
 4314                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4315                            && code_actions
 4316                                .as_ref()
 4317                                .map_or(true, |actions| actions.is_empty());
 4318                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4319                            *editor.context_menu.borrow_mut() =
 4320                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4321                                    buffer,
 4322                                    actions: CodeActionContents {
 4323                                        tasks: resolved_tasks,
 4324                                        actions: code_actions,
 4325                                    },
 4326                                    selected_item: Default::default(),
 4327                                    scroll_handle: UniformListScrollHandle::default(),
 4328                                    deployed_from_indicator,
 4329                                }));
 4330                            if spawn_straight_away {
 4331                                if let Some(task) = editor.confirm_code_action(
 4332                                    &ConfirmCodeAction { item_ix: Some(0) },
 4333                                    window,
 4334                                    cx,
 4335                                ) {
 4336                                    cx.notify();
 4337                                    return task;
 4338                                }
 4339                            }
 4340                            cx.notify();
 4341                            Task::ready(Ok(()))
 4342                        }) {
 4343                            task.await
 4344                        } else {
 4345                            Ok(())
 4346                        }
 4347                    }))
 4348                } else {
 4349                    Some(Task::ready(Ok(())))
 4350                }
 4351            })?;
 4352            if let Some(task) = spawned_test_task {
 4353                task.await?;
 4354            }
 4355
 4356            Ok::<_, anyhow::Error>(())
 4357        })
 4358        .detach_and_log_err(cx);
 4359    }
 4360
 4361    pub fn confirm_code_action(
 4362        &mut self,
 4363        action: &ConfirmCodeAction,
 4364        window: &mut Window,
 4365        cx: &mut Context<Self>,
 4366    ) -> Option<Task<Result<()>>> {
 4367        let actions_menu =
 4368            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4369                menu
 4370            } else {
 4371                return None;
 4372            };
 4373        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4374        let action = actions_menu.actions.get(action_ix)?;
 4375        let title = action.label();
 4376        let buffer = actions_menu.buffer;
 4377        let workspace = self.workspace()?;
 4378
 4379        match action {
 4380            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4381                workspace.update(cx, |workspace, cx| {
 4382                    workspace::tasks::schedule_resolved_task(
 4383                        workspace,
 4384                        task_source_kind,
 4385                        resolved_task,
 4386                        false,
 4387                        cx,
 4388                    );
 4389
 4390                    Some(Task::ready(Ok(())))
 4391                })
 4392            }
 4393            CodeActionsItem::CodeAction {
 4394                excerpt_id,
 4395                action,
 4396                provider,
 4397            } => {
 4398                let apply_code_action =
 4399                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4400                let workspace = workspace.downgrade();
 4401                Some(cx.spawn_in(window, |editor, cx| async move {
 4402                    let project_transaction = apply_code_action.await?;
 4403                    Self::open_project_transaction(
 4404                        &editor,
 4405                        workspace,
 4406                        project_transaction,
 4407                        title,
 4408                        cx,
 4409                    )
 4410                    .await
 4411                }))
 4412            }
 4413        }
 4414    }
 4415
 4416    pub async fn open_project_transaction(
 4417        this: &WeakEntity<Editor>,
 4418        workspace: WeakEntity<Workspace>,
 4419        transaction: ProjectTransaction,
 4420        title: String,
 4421        mut cx: AsyncWindowContext,
 4422    ) -> Result<()> {
 4423        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4424        cx.update(|_, cx| {
 4425            entries.sort_unstable_by_key(|(buffer, _)| {
 4426                buffer.read(cx).file().map(|f| f.path().clone())
 4427            });
 4428        })?;
 4429
 4430        // If the project transaction's edits are all contained within this editor, then
 4431        // avoid opening a new editor to display them.
 4432
 4433        if let Some((buffer, transaction)) = entries.first() {
 4434            if entries.len() == 1 {
 4435                let excerpt = this.update(&mut cx, |editor, cx| {
 4436                    editor
 4437                        .buffer()
 4438                        .read(cx)
 4439                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4440                })?;
 4441                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4442                    if excerpted_buffer == *buffer {
 4443                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4444                            let excerpt_range = excerpt_range.to_offset(buffer);
 4445                            buffer
 4446                                .edited_ranges_for_transaction::<usize>(transaction)
 4447                                .all(|range| {
 4448                                    excerpt_range.start <= range.start
 4449                                        && excerpt_range.end >= range.end
 4450                                })
 4451                        })?;
 4452
 4453                        if all_edits_within_excerpt {
 4454                            return Ok(());
 4455                        }
 4456                    }
 4457                }
 4458            }
 4459        } else {
 4460            return Ok(());
 4461        }
 4462
 4463        let mut ranges_to_highlight = Vec::new();
 4464        let excerpt_buffer = cx.new(|cx| {
 4465            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4466            for (buffer_handle, transaction) in &entries {
 4467                let buffer = buffer_handle.read(cx);
 4468                ranges_to_highlight.extend(
 4469                    multibuffer.push_excerpts_with_context_lines(
 4470                        buffer_handle.clone(),
 4471                        buffer
 4472                            .edited_ranges_for_transaction::<usize>(transaction)
 4473                            .collect(),
 4474                        DEFAULT_MULTIBUFFER_CONTEXT,
 4475                        cx,
 4476                    ),
 4477                );
 4478            }
 4479            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4480            multibuffer
 4481        })?;
 4482
 4483        workspace.update_in(&mut cx, |workspace, window, cx| {
 4484            let project = workspace.project().clone();
 4485            let editor = cx
 4486                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4487            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4488            editor.update(cx, |editor, cx| {
 4489                editor.highlight_background::<Self>(
 4490                    &ranges_to_highlight,
 4491                    |theme| theme.editor_highlighted_line_background,
 4492                    cx,
 4493                );
 4494            });
 4495        })?;
 4496
 4497        Ok(())
 4498    }
 4499
 4500    pub fn clear_code_action_providers(&mut self) {
 4501        self.code_action_providers.clear();
 4502        self.available_code_actions.take();
 4503    }
 4504
 4505    pub fn add_code_action_provider(
 4506        &mut self,
 4507        provider: Rc<dyn CodeActionProvider>,
 4508        window: &mut Window,
 4509        cx: &mut Context<Self>,
 4510    ) {
 4511        if self
 4512            .code_action_providers
 4513            .iter()
 4514            .any(|existing_provider| existing_provider.id() == provider.id())
 4515        {
 4516            return;
 4517        }
 4518
 4519        self.code_action_providers.push(provider);
 4520        self.refresh_code_actions(window, cx);
 4521    }
 4522
 4523    pub fn remove_code_action_provider(
 4524        &mut self,
 4525        id: Arc<str>,
 4526        window: &mut Window,
 4527        cx: &mut Context<Self>,
 4528    ) {
 4529        self.code_action_providers
 4530            .retain(|provider| provider.id() != id);
 4531        self.refresh_code_actions(window, cx);
 4532    }
 4533
 4534    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4535        let buffer = self.buffer.read(cx);
 4536        let newest_selection = self.selections.newest_anchor().clone();
 4537        if newest_selection.head().diff_base_anchor.is_some() {
 4538            return None;
 4539        }
 4540        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4541        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4542        if start_buffer != end_buffer {
 4543            return None;
 4544        }
 4545
 4546        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4547            cx.background_executor()
 4548                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4549                .await;
 4550
 4551            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4552                let providers = this.code_action_providers.clone();
 4553                let tasks = this
 4554                    .code_action_providers
 4555                    .iter()
 4556                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4557                    .collect::<Vec<_>>();
 4558                (providers, tasks)
 4559            })?;
 4560
 4561            let mut actions = Vec::new();
 4562            for (provider, provider_actions) in
 4563                providers.into_iter().zip(future::join_all(tasks).await)
 4564            {
 4565                if let Some(provider_actions) = provider_actions.log_err() {
 4566                    actions.extend(provider_actions.into_iter().map(|action| {
 4567                        AvailableCodeAction {
 4568                            excerpt_id: newest_selection.start.excerpt_id,
 4569                            action,
 4570                            provider: provider.clone(),
 4571                        }
 4572                    }));
 4573                }
 4574            }
 4575
 4576            this.update(&mut cx, |this, cx| {
 4577                this.available_code_actions = if actions.is_empty() {
 4578                    None
 4579                } else {
 4580                    Some((
 4581                        Location {
 4582                            buffer: start_buffer,
 4583                            range: start..end,
 4584                        },
 4585                        actions.into(),
 4586                    ))
 4587                };
 4588                cx.notify();
 4589            })
 4590        }));
 4591        None
 4592    }
 4593
 4594    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4595        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4596            self.show_git_blame_inline = false;
 4597
 4598            self.show_git_blame_inline_delay_task =
 4599                Some(cx.spawn_in(window, |this, mut cx| async move {
 4600                    cx.background_executor().timer(delay).await;
 4601
 4602                    this.update(&mut cx, |this, cx| {
 4603                        this.show_git_blame_inline = true;
 4604                        cx.notify();
 4605                    })
 4606                    .log_err();
 4607                }));
 4608        }
 4609    }
 4610
 4611    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4612        if self.pending_rename.is_some() {
 4613            return None;
 4614        }
 4615
 4616        let provider = self.semantics_provider.clone()?;
 4617        let buffer = self.buffer.read(cx);
 4618        let newest_selection = self.selections.newest_anchor().clone();
 4619        let cursor_position = newest_selection.head();
 4620        let (cursor_buffer, cursor_buffer_position) =
 4621            buffer.text_anchor_for_position(cursor_position, cx)?;
 4622        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4623        if cursor_buffer != tail_buffer {
 4624            return None;
 4625        }
 4626        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4627        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4628            cx.background_executor()
 4629                .timer(Duration::from_millis(debounce))
 4630                .await;
 4631
 4632            let highlights = if let Some(highlights) = cx
 4633                .update(|cx| {
 4634                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4635                })
 4636                .ok()
 4637                .flatten()
 4638            {
 4639                highlights.await.log_err()
 4640            } else {
 4641                None
 4642            };
 4643
 4644            if let Some(highlights) = highlights {
 4645                this.update(&mut cx, |this, cx| {
 4646                    if this.pending_rename.is_some() {
 4647                        return;
 4648                    }
 4649
 4650                    let buffer_id = cursor_position.buffer_id;
 4651                    let buffer = this.buffer.read(cx);
 4652                    if !buffer
 4653                        .text_anchor_for_position(cursor_position, cx)
 4654                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4655                    {
 4656                        return;
 4657                    }
 4658
 4659                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4660                    let mut write_ranges = Vec::new();
 4661                    let mut read_ranges = Vec::new();
 4662                    for highlight in highlights {
 4663                        for (excerpt_id, excerpt_range) in
 4664                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4665                        {
 4666                            let start = highlight
 4667                                .range
 4668                                .start
 4669                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4670                            let end = highlight
 4671                                .range
 4672                                .end
 4673                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4674                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4675                                continue;
 4676                            }
 4677
 4678                            let range = Anchor {
 4679                                buffer_id,
 4680                                excerpt_id,
 4681                                text_anchor: start,
 4682                                diff_base_anchor: None,
 4683                            }..Anchor {
 4684                                buffer_id,
 4685                                excerpt_id,
 4686                                text_anchor: end,
 4687                                diff_base_anchor: None,
 4688                            };
 4689                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4690                                write_ranges.push(range);
 4691                            } else {
 4692                                read_ranges.push(range);
 4693                            }
 4694                        }
 4695                    }
 4696
 4697                    this.highlight_background::<DocumentHighlightRead>(
 4698                        &read_ranges,
 4699                        |theme| theme.editor_document_highlight_read_background,
 4700                        cx,
 4701                    );
 4702                    this.highlight_background::<DocumentHighlightWrite>(
 4703                        &write_ranges,
 4704                        |theme| theme.editor_document_highlight_write_background,
 4705                        cx,
 4706                    );
 4707                    cx.notify();
 4708                })
 4709                .log_err();
 4710            }
 4711        }));
 4712        None
 4713    }
 4714
 4715    pub fn refresh_inline_completion(
 4716        &mut self,
 4717        debounce: bool,
 4718        user_requested: bool,
 4719        window: &mut Window,
 4720        cx: &mut Context<Self>,
 4721    ) -> Option<()> {
 4722        let provider = self.edit_prediction_provider()?;
 4723        let cursor = self.selections.newest_anchor().head();
 4724        let (buffer, cursor_buffer_position) =
 4725            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4726
 4727        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4728            self.discard_inline_completion(false, cx);
 4729            return None;
 4730        }
 4731
 4732        if !user_requested
 4733            && (!self.should_show_edit_predictions()
 4734                || !self.is_focused(window)
 4735                || buffer.read(cx).is_empty())
 4736        {
 4737            self.discard_inline_completion(false, cx);
 4738            return None;
 4739        }
 4740
 4741        self.update_visible_inline_completion(window, cx);
 4742        provider.refresh(
 4743            self.project.clone(),
 4744            buffer,
 4745            cursor_buffer_position,
 4746            debounce,
 4747            cx,
 4748        );
 4749        Some(())
 4750    }
 4751
 4752    fn show_edit_predictions_in_menu(&self) -> bool {
 4753        match self.edit_prediction_settings {
 4754            EditPredictionSettings::Disabled => false,
 4755            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4756        }
 4757    }
 4758
 4759    pub fn edit_predictions_enabled(&self) -> bool {
 4760        match self.edit_prediction_settings {
 4761            EditPredictionSettings::Disabled => false,
 4762            EditPredictionSettings::Enabled { .. } => true,
 4763        }
 4764    }
 4765
 4766    fn edit_prediction_requires_modifier(&self) -> bool {
 4767        match self.edit_prediction_settings {
 4768            EditPredictionSettings::Disabled => false,
 4769            EditPredictionSettings::Enabled {
 4770                preview_requires_modifier,
 4771                ..
 4772            } => preview_requires_modifier,
 4773        }
 4774    }
 4775
 4776    fn edit_prediction_settings_at_position(
 4777        &self,
 4778        buffer: &Entity<Buffer>,
 4779        buffer_position: language::Anchor,
 4780        cx: &App,
 4781    ) -> EditPredictionSettings {
 4782        if self.mode != EditorMode::Full
 4783            || !self.show_inline_completions_override.unwrap_or(true)
 4784            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4785        {
 4786            return EditPredictionSettings::Disabled;
 4787        }
 4788
 4789        let buffer = buffer.read(cx);
 4790
 4791        let file = buffer.file();
 4792
 4793        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4794            return EditPredictionSettings::Disabled;
 4795        };
 4796
 4797        let by_provider = matches!(
 4798            self.menu_inline_completions_policy,
 4799            MenuInlineCompletionsPolicy::ByProvider
 4800        );
 4801
 4802        let show_in_menu = by_provider
 4803            && self
 4804                .edit_prediction_provider
 4805                .as_ref()
 4806                .map_or(false, |provider| {
 4807                    provider.provider.show_completions_in_menu()
 4808                });
 4809
 4810        let preview_requires_modifier =
 4811            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4812
 4813        EditPredictionSettings::Enabled {
 4814            show_in_menu,
 4815            preview_requires_modifier,
 4816        }
 4817    }
 4818
 4819    fn should_show_edit_predictions(&self) -> bool {
 4820        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4821    }
 4822
 4823    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4824        matches!(
 4825            self.edit_prediction_preview,
 4826            EditPredictionPreview::Active { .. }
 4827        )
 4828    }
 4829
 4830    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4831        let cursor = self.selections.newest_anchor().head();
 4832        if let Some((buffer, cursor_position)) =
 4833            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4834        {
 4835            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4836        } else {
 4837            false
 4838        }
 4839    }
 4840
 4841    fn inline_completions_enabled_in_buffer(
 4842        &self,
 4843        buffer: &Entity<Buffer>,
 4844        buffer_position: language::Anchor,
 4845        cx: &App,
 4846    ) -> bool {
 4847        maybe!({
 4848            let provider = self.edit_prediction_provider()?;
 4849            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4850                return Some(false);
 4851            }
 4852            let buffer = buffer.read(cx);
 4853            let Some(file) = buffer.file() else {
 4854                return Some(true);
 4855            };
 4856            let settings = all_language_settings(Some(file), cx);
 4857            Some(settings.inline_completions_enabled_for_path(file.path()))
 4858        })
 4859        .unwrap_or(false)
 4860    }
 4861
 4862    fn cycle_inline_completion(
 4863        &mut self,
 4864        direction: Direction,
 4865        window: &mut Window,
 4866        cx: &mut Context<Self>,
 4867    ) -> Option<()> {
 4868        let provider = self.edit_prediction_provider()?;
 4869        let cursor = self.selections.newest_anchor().head();
 4870        let (buffer, cursor_buffer_position) =
 4871            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4872        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4873            return None;
 4874        }
 4875
 4876        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4877        self.update_visible_inline_completion(window, cx);
 4878
 4879        Some(())
 4880    }
 4881
 4882    pub fn show_inline_completion(
 4883        &mut self,
 4884        _: &ShowEditPrediction,
 4885        window: &mut Window,
 4886        cx: &mut Context<Self>,
 4887    ) {
 4888        if !self.has_active_inline_completion() {
 4889            self.refresh_inline_completion(false, true, window, cx);
 4890            return;
 4891        }
 4892
 4893        self.update_visible_inline_completion(window, cx);
 4894    }
 4895
 4896    pub fn display_cursor_names(
 4897        &mut self,
 4898        _: &DisplayCursorNames,
 4899        window: &mut Window,
 4900        cx: &mut Context<Self>,
 4901    ) {
 4902        self.show_cursor_names(window, cx);
 4903    }
 4904
 4905    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4906        self.show_cursor_names = true;
 4907        cx.notify();
 4908        cx.spawn_in(window, |this, mut cx| async move {
 4909            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4910            this.update(&mut cx, |this, cx| {
 4911                this.show_cursor_names = false;
 4912                cx.notify()
 4913            })
 4914            .ok()
 4915        })
 4916        .detach();
 4917    }
 4918
 4919    pub fn next_edit_prediction(
 4920        &mut self,
 4921        _: &NextEditPrediction,
 4922        window: &mut Window,
 4923        cx: &mut Context<Self>,
 4924    ) {
 4925        if self.has_active_inline_completion() {
 4926            self.cycle_inline_completion(Direction::Next, 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 previous_edit_prediction(
 4938        &mut self,
 4939        _: &PreviousEditPrediction,
 4940        window: &mut Window,
 4941        cx: &mut Context<Self>,
 4942    ) {
 4943        if self.has_active_inline_completion() {
 4944            self.cycle_inline_completion(Direction::Prev, window, cx);
 4945        } else {
 4946            let is_copilot_disabled = self
 4947                .refresh_inline_completion(false, true, window, cx)
 4948                .is_none();
 4949            if is_copilot_disabled {
 4950                cx.propagate();
 4951            }
 4952        }
 4953    }
 4954
 4955    pub fn accept_edit_prediction(
 4956        &mut self,
 4957        _: &AcceptEditPrediction,
 4958        window: &mut Window,
 4959        cx: &mut Context<Self>,
 4960    ) {
 4961        if self.show_edit_predictions_in_menu() {
 4962            self.hide_context_menu(window, cx);
 4963        }
 4964
 4965        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4966            return;
 4967        };
 4968
 4969        self.report_inline_completion_event(
 4970            active_inline_completion.completion_id.clone(),
 4971            true,
 4972            cx,
 4973        );
 4974
 4975        match &active_inline_completion.completion {
 4976            InlineCompletion::Move { target, .. } => {
 4977                let target = *target;
 4978
 4979                if let Some(position_map) = &self.last_position_map {
 4980                    if position_map
 4981                        .visible_row_range
 4982                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4983                        || !self.edit_prediction_requires_modifier()
 4984                    {
 4985                        // Note that this is also done in vim's handler of the Tab action.
 4986                        self.change_selections(
 4987                            Some(Autoscroll::newest()),
 4988                            window,
 4989                            cx,
 4990                            |selections| {
 4991                                selections.select_anchor_ranges([target..target]);
 4992                            },
 4993                        );
 4994                        self.clear_row_highlights::<EditPredictionPreview>();
 4995
 4996                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4997                            previous_scroll_position: None,
 4998                        };
 4999                    } else {
 5000                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5001                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5002                        };
 5003                        self.highlight_rows::<EditPredictionPreview>(
 5004                            target..target,
 5005                            cx.theme().colors().editor_highlighted_line_background,
 5006                            true,
 5007                            cx,
 5008                        );
 5009                        self.request_autoscroll(Autoscroll::fit(), cx);
 5010                    }
 5011                }
 5012            }
 5013            InlineCompletion::Edit { edits, .. } => {
 5014                if let Some(provider) = self.edit_prediction_provider() {
 5015                    provider.accept(cx);
 5016                }
 5017
 5018                let snapshot = self.buffer.read(cx).snapshot(cx);
 5019                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5020
 5021                self.buffer.update(cx, |buffer, cx| {
 5022                    buffer.edit(edits.iter().cloned(), None, cx)
 5023                });
 5024
 5025                self.change_selections(None, window, cx, |s| {
 5026                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5027                });
 5028
 5029                self.update_visible_inline_completion(window, cx);
 5030                if self.active_inline_completion.is_none() {
 5031                    self.refresh_inline_completion(true, true, window, cx);
 5032                }
 5033
 5034                cx.notify();
 5035            }
 5036        }
 5037
 5038        self.edit_prediction_requires_modifier_in_leading_space = false;
 5039    }
 5040
 5041    pub fn accept_partial_inline_completion(
 5042        &mut self,
 5043        _: &AcceptPartialEditPrediction,
 5044        window: &mut Window,
 5045        cx: &mut Context<Self>,
 5046    ) {
 5047        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5048            return;
 5049        };
 5050        if self.selections.count() != 1 {
 5051            return;
 5052        }
 5053
 5054        self.report_inline_completion_event(
 5055            active_inline_completion.completion_id.clone(),
 5056            true,
 5057            cx,
 5058        );
 5059
 5060        match &active_inline_completion.completion {
 5061            InlineCompletion::Move { target, .. } => {
 5062                let target = *target;
 5063                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5064                    selections.select_anchor_ranges([target..target]);
 5065                });
 5066            }
 5067            InlineCompletion::Edit { edits, .. } => {
 5068                // Find an insertion that starts at the cursor position.
 5069                let snapshot = self.buffer.read(cx).snapshot(cx);
 5070                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5071                let insertion = edits.iter().find_map(|(range, text)| {
 5072                    let range = range.to_offset(&snapshot);
 5073                    if range.is_empty() && range.start == cursor_offset {
 5074                        Some(text)
 5075                    } else {
 5076                        None
 5077                    }
 5078                });
 5079
 5080                if let Some(text) = insertion {
 5081                    let mut partial_completion = text
 5082                        .chars()
 5083                        .by_ref()
 5084                        .take_while(|c| c.is_alphabetic())
 5085                        .collect::<String>();
 5086                    if partial_completion.is_empty() {
 5087                        partial_completion = text
 5088                            .chars()
 5089                            .by_ref()
 5090                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5091                            .collect::<String>();
 5092                    }
 5093
 5094                    cx.emit(EditorEvent::InputHandled {
 5095                        utf16_range_to_replace: None,
 5096                        text: partial_completion.clone().into(),
 5097                    });
 5098
 5099                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5100
 5101                    self.refresh_inline_completion(true, true, window, cx);
 5102                    cx.notify();
 5103                } else {
 5104                    self.accept_edit_prediction(&Default::default(), window, cx);
 5105                }
 5106            }
 5107        }
 5108    }
 5109
 5110    fn discard_inline_completion(
 5111        &mut self,
 5112        should_report_inline_completion_event: bool,
 5113        cx: &mut Context<Self>,
 5114    ) -> bool {
 5115        if should_report_inline_completion_event {
 5116            let completion_id = self
 5117                .active_inline_completion
 5118                .as_ref()
 5119                .and_then(|active_completion| active_completion.completion_id.clone());
 5120
 5121            self.report_inline_completion_event(completion_id, false, cx);
 5122        }
 5123
 5124        if let Some(provider) = self.edit_prediction_provider() {
 5125            provider.discard(cx);
 5126        }
 5127
 5128        self.take_active_inline_completion(cx)
 5129    }
 5130
 5131    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5132        let Some(provider) = self.edit_prediction_provider() else {
 5133            return;
 5134        };
 5135
 5136        let Some((_, buffer, _)) = self
 5137            .buffer
 5138            .read(cx)
 5139            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5140        else {
 5141            return;
 5142        };
 5143
 5144        let extension = buffer
 5145            .read(cx)
 5146            .file()
 5147            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5148
 5149        let event_type = match accepted {
 5150            true => "Edit Prediction Accepted",
 5151            false => "Edit Prediction Discarded",
 5152        };
 5153        telemetry::event!(
 5154            event_type,
 5155            provider = provider.name(),
 5156            prediction_id = id,
 5157            suggestion_accepted = accepted,
 5158            file_extension = extension,
 5159        );
 5160    }
 5161
 5162    pub fn has_active_inline_completion(&self) -> bool {
 5163        self.active_inline_completion.is_some()
 5164    }
 5165
 5166    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5167        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5168            return false;
 5169        };
 5170
 5171        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5172        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5173        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5174        true
 5175    }
 5176
 5177    /// Returns true when we're displaying the edit prediction popover below the cursor
 5178    /// like we are not previewing and the LSP autocomplete menu is visible
 5179    /// or we are in `when_holding_modifier` mode.
 5180    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5181        if self.edit_prediction_preview_is_active()
 5182            || !self.show_edit_predictions_in_menu()
 5183            || !self.edit_predictions_enabled()
 5184        {
 5185            return false;
 5186        }
 5187
 5188        if self.has_visible_completions_menu() {
 5189            return true;
 5190        }
 5191
 5192        has_completion && self.edit_prediction_requires_modifier()
 5193    }
 5194
 5195    fn handle_modifiers_changed(
 5196        &mut self,
 5197        modifiers: Modifiers,
 5198        position_map: &PositionMap,
 5199        window: &mut Window,
 5200        cx: &mut Context<Self>,
 5201    ) {
 5202        if self.show_edit_predictions_in_menu() {
 5203            self.update_edit_prediction_preview(&modifiers, window, cx);
 5204        }
 5205
 5206        let mouse_position = window.mouse_position();
 5207        if !position_map.text_hitbox.is_hovered(window) {
 5208            return;
 5209        }
 5210
 5211        self.update_hovered_link(
 5212            position_map.point_for_position(mouse_position),
 5213            &position_map.snapshot,
 5214            modifiers,
 5215            window,
 5216            cx,
 5217        )
 5218    }
 5219
 5220    fn update_edit_prediction_preview(
 5221        &mut self,
 5222        modifiers: &Modifiers,
 5223        window: &mut Window,
 5224        cx: &mut Context<Self>,
 5225    ) {
 5226        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5227        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5228            return;
 5229        };
 5230
 5231        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5232            if matches!(
 5233                self.edit_prediction_preview,
 5234                EditPredictionPreview::Inactive
 5235            ) {
 5236                self.edit_prediction_preview = EditPredictionPreview::Active {
 5237                    previous_scroll_position: None,
 5238                };
 5239
 5240                self.update_visible_inline_completion(window, cx);
 5241                cx.notify();
 5242            }
 5243        } else if let EditPredictionPreview::Active {
 5244            previous_scroll_position,
 5245        } = self.edit_prediction_preview
 5246        {
 5247            if let (Some(previous_scroll_position), Some(position_map)) =
 5248                (previous_scroll_position, self.last_position_map.as_ref())
 5249            {
 5250                self.set_scroll_position(
 5251                    previous_scroll_position
 5252                        .scroll_position(&position_map.snapshot.display_snapshot),
 5253                    window,
 5254                    cx,
 5255                );
 5256            }
 5257
 5258            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5259            self.clear_row_highlights::<EditPredictionPreview>();
 5260            self.update_visible_inline_completion(window, cx);
 5261            cx.notify();
 5262        }
 5263    }
 5264
 5265    fn update_visible_inline_completion(
 5266        &mut self,
 5267        _window: &mut Window,
 5268        cx: &mut Context<Self>,
 5269    ) -> Option<()> {
 5270        let selection = self.selections.newest_anchor();
 5271        let cursor = selection.head();
 5272        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5273        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5274        let excerpt_id = cursor.excerpt_id;
 5275
 5276        let show_in_menu = self.show_edit_predictions_in_menu();
 5277        let completions_menu_has_precedence = !show_in_menu
 5278            && (self.context_menu.borrow().is_some()
 5279                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5280
 5281        if completions_menu_has_precedence
 5282            || !offset_selection.is_empty()
 5283            || self
 5284                .active_inline_completion
 5285                .as_ref()
 5286                .map_or(false, |completion| {
 5287                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5288                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5289                    !invalidation_range.contains(&offset_selection.head())
 5290                })
 5291        {
 5292            self.discard_inline_completion(false, cx);
 5293            return None;
 5294        }
 5295
 5296        self.take_active_inline_completion(cx);
 5297        let Some(provider) = self.edit_prediction_provider() else {
 5298            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5299            return None;
 5300        };
 5301
 5302        let (buffer, cursor_buffer_position) =
 5303            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5304
 5305        self.edit_prediction_settings =
 5306            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5307
 5308        self.edit_prediction_cursor_on_leading_whitespace =
 5309            multibuffer.is_line_whitespace_upto(cursor);
 5310
 5311        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5312        let edits = inline_completion
 5313            .edits
 5314            .into_iter()
 5315            .flat_map(|(range, new_text)| {
 5316                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5317                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5318                Some((start..end, new_text))
 5319            })
 5320            .collect::<Vec<_>>();
 5321        if edits.is_empty() {
 5322            return None;
 5323        }
 5324
 5325        let first_edit_start = edits.first().unwrap().0.start;
 5326        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5327        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5328
 5329        let last_edit_end = edits.last().unwrap().0.end;
 5330        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5331        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5332
 5333        let cursor_row = cursor.to_point(&multibuffer).row;
 5334
 5335        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5336
 5337        let mut inlay_ids = Vec::new();
 5338        let invalidation_row_range;
 5339        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5340            Some(cursor_row..edit_end_row)
 5341        } else if cursor_row > edit_end_row {
 5342            Some(edit_start_row..cursor_row)
 5343        } else {
 5344            None
 5345        };
 5346        let is_move =
 5347            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5348        let completion = if is_move {
 5349            invalidation_row_range =
 5350                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5351            let target = first_edit_start;
 5352            InlineCompletion::Move { target, snapshot }
 5353        } else {
 5354            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5355                && !self.inline_completions_hidden_for_vim_mode;
 5356
 5357            if show_completions_in_buffer {
 5358                if edits
 5359                    .iter()
 5360                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5361                {
 5362                    let mut inlays = Vec::new();
 5363                    for (range, new_text) in &edits {
 5364                        let inlay = Inlay::inline_completion(
 5365                            post_inc(&mut self.next_inlay_id),
 5366                            range.start,
 5367                            new_text.as_str(),
 5368                        );
 5369                        inlay_ids.push(inlay.id);
 5370                        inlays.push(inlay);
 5371                    }
 5372
 5373                    self.splice_inlays(&[], inlays, cx);
 5374                } else {
 5375                    let background_color = cx.theme().status().deleted_background;
 5376                    self.highlight_text::<InlineCompletionHighlight>(
 5377                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5378                        HighlightStyle {
 5379                            background_color: Some(background_color),
 5380                            ..Default::default()
 5381                        },
 5382                        cx,
 5383                    );
 5384                }
 5385            }
 5386
 5387            invalidation_row_range = edit_start_row..edit_end_row;
 5388
 5389            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5390                if provider.show_tab_accept_marker() {
 5391                    EditDisplayMode::TabAccept
 5392                } else {
 5393                    EditDisplayMode::Inline
 5394                }
 5395            } else {
 5396                EditDisplayMode::DiffPopover
 5397            };
 5398
 5399            InlineCompletion::Edit {
 5400                edits,
 5401                edit_preview: inline_completion.edit_preview,
 5402                display_mode,
 5403                snapshot,
 5404            }
 5405        };
 5406
 5407        let invalidation_range = multibuffer
 5408            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5409            ..multibuffer.anchor_after(Point::new(
 5410                invalidation_row_range.end,
 5411                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5412            ));
 5413
 5414        self.stale_inline_completion_in_menu = None;
 5415        self.active_inline_completion = Some(InlineCompletionState {
 5416            inlay_ids,
 5417            completion,
 5418            completion_id: inline_completion.id,
 5419            invalidation_range,
 5420        });
 5421
 5422        cx.notify();
 5423
 5424        Some(())
 5425    }
 5426
 5427    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5428        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5429    }
 5430
 5431    fn render_code_actions_indicator(
 5432        &self,
 5433        _style: &EditorStyle,
 5434        row: DisplayRow,
 5435        is_active: bool,
 5436        cx: &mut Context<Self>,
 5437    ) -> Option<IconButton> {
 5438        if self.available_code_actions.is_some() {
 5439            Some(
 5440                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5441                    .shape(ui::IconButtonShape::Square)
 5442                    .icon_size(IconSize::XSmall)
 5443                    .icon_color(Color::Muted)
 5444                    .toggle_state(is_active)
 5445                    .tooltip({
 5446                        let focus_handle = self.focus_handle.clone();
 5447                        move |window, cx| {
 5448                            Tooltip::for_action_in(
 5449                                "Toggle Code Actions",
 5450                                &ToggleCodeActions {
 5451                                    deployed_from_indicator: None,
 5452                                },
 5453                                &focus_handle,
 5454                                window,
 5455                                cx,
 5456                            )
 5457                        }
 5458                    })
 5459                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5460                        window.focus(&editor.focus_handle(cx));
 5461                        editor.toggle_code_actions(
 5462                            &ToggleCodeActions {
 5463                                deployed_from_indicator: Some(row),
 5464                            },
 5465                            window,
 5466                            cx,
 5467                        );
 5468                    })),
 5469            )
 5470        } else {
 5471            None
 5472        }
 5473    }
 5474
 5475    fn clear_tasks(&mut self) {
 5476        self.tasks.clear()
 5477    }
 5478
 5479    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5480        if self.tasks.insert(key, value).is_some() {
 5481            // This case should hopefully be rare, but just in case...
 5482            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5483        }
 5484    }
 5485
 5486    fn build_tasks_context(
 5487        project: &Entity<Project>,
 5488        buffer: &Entity<Buffer>,
 5489        buffer_row: u32,
 5490        tasks: &Arc<RunnableTasks>,
 5491        cx: &mut Context<Self>,
 5492    ) -> Task<Option<task::TaskContext>> {
 5493        let position = Point::new(buffer_row, tasks.column);
 5494        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5495        let location = Location {
 5496            buffer: buffer.clone(),
 5497            range: range_start..range_start,
 5498        };
 5499        // Fill in the environmental variables from the tree-sitter captures
 5500        let mut captured_task_variables = TaskVariables::default();
 5501        for (capture_name, value) in tasks.extra_variables.clone() {
 5502            captured_task_variables.insert(
 5503                task::VariableName::Custom(capture_name.into()),
 5504                value.clone(),
 5505            );
 5506        }
 5507        project.update(cx, |project, cx| {
 5508            project.task_store().update(cx, |task_store, cx| {
 5509                task_store.task_context_for_location(captured_task_variables, location, cx)
 5510            })
 5511        })
 5512    }
 5513
 5514    pub fn spawn_nearest_task(
 5515        &mut self,
 5516        action: &SpawnNearestTask,
 5517        window: &mut Window,
 5518        cx: &mut Context<Self>,
 5519    ) {
 5520        let Some((workspace, _)) = self.workspace.clone() else {
 5521            return;
 5522        };
 5523        let Some(project) = self.project.clone() else {
 5524            return;
 5525        };
 5526
 5527        // Try to find a closest, enclosing node using tree-sitter that has a
 5528        // task
 5529        let Some((buffer, buffer_row, tasks)) = self
 5530            .find_enclosing_node_task(cx)
 5531            // Or find the task that's closest in row-distance.
 5532            .or_else(|| self.find_closest_task(cx))
 5533        else {
 5534            return;
 5535        };
 5536
 5537        let reveal_strategy = action.reveal;
 5538        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5539        cx.spawn_in(window, |_, mut cx| async move {
 5540            let context = task_context.await?;
 5541            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5542
 5543            let resolved = resolved_task.resolved.as_mut()?;
 5544            resolved.reveal = reveal_strategy;
 5545
 5546            workspace
 5547                .update(&mut cx, |workspace, cx| {
 5548                    workspace::tasks::schedule_resolved_task(
 5549                        workspace,
 5550                        task_source_kind,
 5551                        resolved_task,
 5552                        false,
 5553                        cx,
 5554                    );
 5555                })
 5556                .ok()
 5557        })
 5558        .detach();
 5559    }
 5560
 5561    fn find_closest_task(
 5562        &mut self,
 5563        cx: &mut Context<Self>,
 5564    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5565        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5566
 5567        let ((buffer_id, row), tasks) = self
 5568            .tasks
 5569            .iter()
 5570            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5571
 5572        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5573        let tasks = Arc::new(tasks.to_owned());
 5574        Some((buffer, *row, tasks))
 5575    }
 5576
 5577    fn find_enclosing_node_task(
 5578        &mut self,
 5579        cx: &mut Context<Self>,
 5580    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5581        let snapshot = self.buffer.read(cx).snapshot(cx);
 5582        let offset = self.selections.newest::<usize>(cx).head();
 5583        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5584        let buffer_id = excerpt.buffer().remote_id();
 5585
 5586        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5587        let mut cursor = layer.node().walk();
 5588
 5589        while cursor.goto_first_child_for_byte(offset).is_some() {
 5590            if cursor.node().end_byte() == offset {
 5591                cursor.goto_next_sibling();
 5592            }
 5593        }
 5594
 5595        // Ascend to the smallest ancestor that contains the range and has a task.
 5596        loop {
 5597            let node = cursor.node();
 5598            let node_range = node.byte_range();
 5599            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5600
 5601            // Check if this node contains our offset
 5602            if node_range.start <= offset && node_range.end >= offset {
 5603                // If it contains offset, check for task
 5604                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5605                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5606                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5607                }
 5608            }
 5609
 5610            if !cursor.goto_parent() {
 5611                break;
 5612            }
 5613        }
 5614        None
 5615    }
 5616
 5617    fn render_run_indicator(
 5618        &self,
 5619        _style: &EditorStyle,
 5620        is_active: bool,
 5621        row: DisplayRow,
 5622        cx: &mut Context<Self>,
 5623    ) -> IconButton {
 5624        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5625            .shape(ui::IconButtonShape::Square)
 5626            .icon_size(IconSize::XSmall)
 5627            .icon_color(Color::Muted)
 5628            .toggle_state(is_active)
 5629            .on_click(cx.listener(move |editor, _e, window, cx| {
 5630                window.focus(&editor.focus_handle(cx));
 5631                editor.toggle_code_actions(
 5632                    &ToggleCodeActions {
 5633                        deployed_from_indicator: Some(row),
 5634                    },
 5635                    window,
 5636                    cx,
 5637                );
 5638            }))
 5639    }
 5640
 5641    pub fn context_menu_visible(&self) -> bool {
 5642        !self.edit_prediction_preview_is_active()
 5643            && self
 5644                .context_menu
 5645                .borrow()
 5646                .as_ref()
 5647                .map_or(false, |menu| menu.visible())
 5648    }
 5649
 5650    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5651        self.context_menu
 5652            .borrow()
 5653            .as_ref()
 5654            .map(|menu| menu.origin())
 5655    }
 5656
 5657    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5658        px(30.)
 5659    }
 5660
 5661    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5662        if self.read_only(cx) {
 5663            cx.theme().players().read_only()
 5664        } else {
 5665            self.style.as_ref().unwrap().local_player
 5666        }
 5667    }
 5668
 5669    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5670        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5671        let accept_keystroke = accept_binding.keystroke()?;
 5672
 5673        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5674
 5675        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5676            Color::Accent
 5677        } else {
 5678            Color::Muted
 5679        };
 5680
 5681        h_flex()
 5682            .px_0p5()
 5683            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5684            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5685            .text_size(TextSize::XSmall.rems(cx))
 5686            .child(h_flex().children(ui::render_modifiers(
 5687                &accept_keystroke.modifiers,
 5688                PlatformStyle::platform(),
 5689                Some(modifiers_color),
 5690                Some(IconSize::XSmall.rems().into()),
 5691                true,
 5692            )))
 5693            .when(is_platform_style_mac, |parent| {
 5694                parent.child(accept_keystroke.key.clone())
 5695            })
 5696            .when(!is_platform_style_mac, |parent| {
 5697                parent.child(
 5698                    Key::new(
 5699                        util::capitalize(&accept_keystroke.key),
 5700                        Some(Color::Default),
 5701                    )
 5702                    .size(Some(IconSize::XSmall.rems().into())),
 5703                )
 5704            })
 5705            .into()
 5706    }
 5707
 5708    fn render_edit_prediction_line_popover(
 5709        &self,
 5710        label: impl Into<SharedString>,
 5711        icon: Option<IconName>,
 5712        window: &mut Window,
 5713        cx: &App,
 5714    ) -> Option<Div> {
 5715        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5716
 5717        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5718
 5719        let result = h_flex()
 5720            .gap_1()
 5721            .border_1()
 5722            .rounded_lg()
 5723            .shadow_sm()
 5724            .bg(bg_color)
 5725            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5726            .py_0p5()
 5727            .pl_1()
 5728            .pr(padding_right)
 5729            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5730            .child(Label::new(label).size(LabelSize::Small))
 5731            .when_some(icon, |element, icon| {
 5732                element.child(
 5733                    div()
 5734                        .mt(px(1.5))
 5735                        .child(Icon::new(icon).size(IconSize::Small)),
 5736                )
 5737            });
 5738
 5739        Some(result)
 5740    }
 5741
 5742    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5743        let accent_color = cx.theme().colors().text_accent;
 5744        let editor_bg_color = cx.theme().colors().editor_background;
 5745        editor_bg_color.blend(accent_color.opacity(0.1))
 5746    }
 5747
 5748    #[allow(clippy::too_many_arguments)]
 5749    fn render_edit_prediction_cursor_popover(
 5750        &self,
 5751        min_width: Pixels,
 5752        max_width: Pixels,
 5753        cursor_point: Point,
 5754        style: &EditorStyle,
 5755        accept_keystroke: &gpui::Keystroke,
 5756        _window: &Window,
 5757        cx: &mut Context<Editor>,
 5758    ) -> Option<AnyElement> {
 5759        let provider = self.edit_prediction_provider.as_ref()?;
 5760
 5761        if provider.provider.needs_terms_acceptance(cx) {
 5762            return Some(
 5763                h_flex()
 5764                    .min_w(min_width)
 5765                    .flex_1()
 5766                    .px_2()
 5767                    .py_1()
 5768                    .gap_3()
 5769                    .elevation_2(cx)
 5770                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5771                    .id("accept-terms")
 5772                    .cursor_pointer()
 5773                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5774                    .on_click(cx.listener(|this, _event, window, cx| {
 5775                        cx.stop_propagation();
 5776                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5777                        window.dispatch_action(
 5778                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5779                            cx,
 5780                        );
 5781                    }))
 5782                    .child(
 5783                        h_flex()
 5784                            .flex_1()
 5785                            .gap_2()
 5786                            .child(Icon::new(IconName::ZedPredict))
 5787                            .child(Label::new("Accept Terms of Service"))
 5788                            .child(div().w_full())
 5789                            .child(
 5790                                Icon::new(IconName::ArrowUpRight)
 5791                                    .color(Color::Muted)
 5792                                    .size(IconSize::Small),
 5793                            )
 5794                            .into_any_element(),
 5795                    )
 5796                    .into_any(),
 5797            );
 5798        }
 5799
 5800        let is_refreshing = provider.provider.is_refreshing(cx);
 5801
 5802        fn pending_completion_container() -> Div {
 5803            h_flex()
 5804                .h_full()
 5805                .flex_1()
 5806                .gap_2()
 5807                .child(Icon::new(IconName::ZedPredict))
 5808        }
 5809
 5810        let completion = match &self.active_inline_completion {
 5811            Some(completion) => match &completion.completion {
 5812                InlineCompletion::Move {
 5813                    target, snapshot, ..
 5814                } if !self.has_visible_completions_menu() => {
 5815                    use text::ToPoint as _;
 5816
 5817                    return Some(
 5818                        h_flex()
 5819                            .px_2()
 5820                            .py_1()
 5821                            .elevation_2(cx)
 5822                            .border_color(cx.theme().colors().border)
 5823                            .rounded_tl(px(0.))
 5824                            .gap_2()
 5825                            .child(
 5826                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5827                                    Icon::new(IconName::ZedPredictDown)
 5828                                } else {
 5829                                    Icon::new(IconName::ZedPredictUp)
 5830                                },
 5831                            )
 5832                            .child(Label::new("Hold").size(LabelSize::Small))
 5833                            .child(h_flex().children(ui::render_modifiers(
 5834                                &accept_keystroke.modifiers,
 5835                                PlatformStyle::platform(),
 5836                                Some(Color::Default),
 5837                                Some(IconSize::Small.rems().into()),
 5838                                false,
 5839                            )))
 5840                            .into_any(),
 5841                    );
 5842                }
 5843                _ => self.render_edit_prediction_cursor_popover_preview(
 5844                    completion,
 5845                    cursor_point,
 5846                    style,
 5847                    cx,
 5848                )?,
 5849            },
 5850
 5851            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5852                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5853                    stale_completion,
 5854                    cursor_point,
 5855                    style,
 5856                    cx,
 5857                )?,
 5858
 5859                None => {
 5860                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5861                }
 5862            },
 5863
 5864            None => pending_completion_container().child(Label::new("No Prediction")),
 5865        };
 5866
 5867        let completion = if is_refreshing {
 5868            completion
 5869                .with_animation(
 5870                    "loading-completion",
 5871                    Animation::new(Duration::from_secs(2))
 5872                        .repeat()
 5873                        .with_easing(pulsating_between(0.4, 0.8)),
 5874                    |label, delta| label.opacity(delta),
 5875                )
 5876                .into_any_element()
 5877        } else {
 5878            completion.into_any_element()
 5879        };
 5880
 5881        let has_completion = self.active_inline_completion.is_some();
 5882
 5883        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5884        Some(
 5885            h_flex()
 5886                .min_w(min_width)
 5887                .max_w(max_width)
 5888                .flex_1()
 5889                .elevation_2(cx)
 5890                .border_color(cx.theme().colors().border)
 5891                .child(
 5892                    div()
 5893                        .flex_1()
 5894                        .py_1()
 5895                        .px_2()
 5896                        .overflow_hidden()
 5897                        .child(completion),
 5898                )
 5899                .child(
 5900                    h_flex()
 5901                        .h_full()
 5902                        .border_l_1()
 5903                        .rounded_r_lg()
 5904                        .border_color(cx.theme().colors().border)
 5905                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5906                        .gap_1()
 5907                        .py_1()
 5908                        .px_2()
 5909                        .child(
 5910                            h_flex()
 5911                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5912                                .when(is_platform_style_mac, |parent| parent.gap_1())
 5913                                .child(h_flex().children(ui::render_modifiers(
 5914                                    &accept_keystroke.modifiers,
 5915                                    PlatformStyle::platform(),
 5916                                    Some(if !has_completion {
 5917                                        Color::Muted
 5918                                    } else {
 5919                                        Color::Default
 5920                                    }),
 5921                                    None,
 5922                                    false,
 5923                                ))),
 5924                        )
 5925                        .child(Label::new("Preview").into_any_element())
 5926                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5927                )
 5928                .into_any(),
 5929        )
 5930    }
 5931
 5932    fn render_edit_prediction_cursor_popover_preview(
 5933        &self,
 5934        completion: &InlineCompletionState,
 5935        cursor_point: Point,
 5936        style: &EditorStyle,
 5937        cx: &mut Context<Editor>,
 5938    ) -> Option<Div> {
 5939        use text::ToPoint as _;
 5940
 5941        fn render_relative_row_jump(
 5942            prefix: impl Into<String>,
 5943            current_row: u32,
 5944            target_row: u32,
 5945        ) -> Div {
 5946            let (row_diff, arrow) = if target_row < current_row {
 5947                (current_row - target_row, IconName::ArrowUp)
 5948            } else {
 5949                (target_row - current_row, IconName::ArrowDown)
 5950            };
 5951
 5952            h_flex()
 5953                .child(
 5954                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5955                        .color(Color::Muted)
 5956                        .size(LabelSize::Small),
 5957                )
 5958                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5959        }
 5960
 5961        match &completion.completion {
 5962            InlineCompletion::Move {
 5963                target, snapshot, ..
 5964            } => Some(
 5965                h_flex()
 5966                    .px_2()
 5967                    .gap_2()
 5968                    .flex_1()
 5969                    .child(
 5970                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5971                            Icon::new(IconName::ZedPredictDown)
 5972                        } else {
 5973                            Icon::new(IconName::ZedPredictUp)
 5974                        },
 5975                    )
 5976                    .child(Label::new("Jump to Edit")),
 5977            ),
 5978
 5979            InlineCompletion::Edit {
 5980                edits,
 5981                edit_preview,
 5982                snapshot,
 5983                display_mode: _,
 5984            } => {
 5985                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5986
 5987                let highlighted_edits = crate::inline_completion_edit_text(
 5988                    &snapshot,
 5989                    &edits,
 5990                    edit_preview.as_ref()?,
 5991                    true,
 5992                    cx,
 5993                );
 5994
 5995                let len_total = highlighted_edits.text.len();
 5996                let first_line = &highlighted_edits.text
 5997                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5998                let first_line_len = first_line.len();
 5999
 6000                let first_highlight_start = highlighted_edits
 6001                    .highlights
 6002                    .first()
 6003                    .map_or(0, |(range, _)| range.start);
 6004                let drop_prefix_len = first_line
 6005                    .char_indices()
 6006                    .find(|(_, c)| !c.is_whitespace())
 6007                    .map_or(first_highlight_start, |(ix, _)| {
 6008                        ix.min(first_highlight_start)
 6009                    });
 6010
 6011                let preview_text = &first_line[drop_prefix_len..];
 6012                let preview_len = preview_text.len();
 6013                let highlights = highlighted_edits
 6014                    .highlights
 6015                    .into_iter()
 6016                    .take_until(|(range, _)| range.start > first_line_len)
 6017                    .map(|(range, style)| {
 6018                        (
 6019                            range.start - drop_prefix_len
 6020                                ..(range.end - drop_prefix_len).min(preview_len),
 6021                            style,
 6022                        )
 6023                    });
 6024
 6025                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 6026                    .with_highlights(&style.text, highlights);
 6027
 6028                let preview = h_flex()
 6029                    .gap_1()
 6030                    .min_w_16()
 6031                    .child(styled_text)
 6032                    .when(len_total > first_line_len, |parent| parent.child(""));
 6033
 6034                let left = if first_edit_row != cursor_point.row {
 6035                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6036                        .into_any_element()
 6037                } else {
 6038                    Icon::new(IconName::ZedPredict).into_any_element()
 6039                };
 6040
 6041                Some(
 6042                    h_flex()
 6043                        .h_full()
 6044                        .flex_1()
 6045                        .gap_2()
 6046                        .pr_1()
 6047                        .overflow_x_hidden()
 6048                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6049                        .child(left)
 6050                        .child(preview),
 6051                )
 6052            }
 6053        }
 6054    }
 6055
 6056    fn render_context_menu(
 6057        &self,
 6058        style: &EditorStyle,
 6059        max_height_in_lines: u32,
 6060        y_flipped: bool,
 6061        window: &mut Window,
 6062        cx: &mut Context<Editor>,
 6063    ) -> Option<AnyElement> {
 6064        let menu = self.context_menu.borrow();
 6065        let menu = menu.as_ref()?;
 6066        if !menu.visible() {
 6067            return None;
 6068        };
 6069        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6070    }
 6071
 6072    fn render_context_menu_aside(
 6073        &self,
 6074        style: &EditorStyle,
 6075        max_size: Size<Pixels>,
 6076        cx: &mut Context<Editor>,
 6077    ) -> Option<AnyElement> {
 6078        self.context_menu.borrow().as_ref().and_then(|menu| {
 6079            if menu.visible() {
 6080                menu.render_aside(
 6081                    style,
 6082                    max_size,
 6083                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6084                    cx,
 6085                )
 6086            } else {
 6087                None
 6088            }
 6089        })
 6090    }
 6091
 6092    fn hide_context_menu(
 6093        &mut self,
 6094        window: &mut Window,
 6095        cx: &mut Context<Self>,
 6096    ) -> Option<CodeContextMenu> {
 6097        cx.notify();
 6098        self.completion_tasks.clear();
 6099        let context_menu = self.context_menu.borrow_mut().take();
 6100        self.stale_inline_completion_in_menu.take();
 6101        self.update_visible_inline_completion(window, cx);
 6102        context_menu
 6103    }
 6104
 6105    fn show_snippet_choices(
 6106        &mut self,
 6107        choices: &Vec<String>,
 6108        selection: Range<Anchor>,
 6109        cx: &mut Context<Self>,
 6110    ) {
 6111        if selection.start.buffer_id.is_none() {
 6112            return;
 6113        }
 6114        let buffer_id = selection.start.buffer_id.unwrap();
 6115        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6116        let id = post_inc(&mut self.next_completion_id);
 6117
 6118        if let Some(buffer) = buffer {
 6119            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6120                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6121            ));
 6122        }
 6123    }
 6124
 6125    pub fn insert_snippet(
 6126        &mut self,
 6127        insertion_ranges: &[Range<usize>],
 6128        snippet: Snippet,
 6129        window: &mut Window,
 6130        cx: &mut Context<Self>,
 6131    ) -> Result<()> {
 6132        struct Tabstop<T> {
 6133            is_end_tabstop: bool,
 6134            ranges: Vec<Range<T>>,
 6135            choices: Option<Vec<String>>,
 6136        }
 6137
 6138        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6139            let snippet_text: Arc<str> = snippet.text.clone().into();
 6140            buffer.edit(
 6141                insertion_ranges
 6142                    .iter()
 6143                    .cloned()
 6144                    .map(|range| (range, snippet_text.clone())),
 6145                Some(AutoindentMode::EachLine),
 6146                cx,
 6147            );
 6148
 6149            let snapshot = &*buffer.read(cx);
 6150            let snippet = &snippet;
 6151            snippet
 6152                .tabstops
 6153                .iter()
 6154                .map(|tabstop| {
 6155                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6156                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6157                    });
 6158                    let mut tabstop_ranges = tabstop
 6159                        .ranges
 6160                        .iter()
 6161                        .flat_map(|tabstop_range| {
 6162                            let mut delta = 0_isize;
 6163                            insertion_ranges.iter().map(move |insertion_range| {
 6164                                let insertion_start = insertion_range.start as isize + delta;
 6165                                delta +=
 6166                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6167
 6168                                let start = ((insertion_start + tabstop_range.start) as usize)
 6169                                    .min(snapshot.len());
 6170                                let end = ((insertion_start + tabstop_range.end) as usize)
 6171                                    .min(snapshot.len());
 6172                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6173                            })
 6174                        })
 6175                        .collect::<Vec<_>>();
 6176                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6177
 6178                    Tabstop {
 6179                        is_end_tabstop,
 6180                        ranges: tabstop_ranges,
 6181                        choices: tabstop.choices.clone(),
 6182                    }
 6183                })
 6184                .collect::<Vec<_>>()
 6185        });
 6186        if let Some(tabstop) = tabstops.first() {
 6187            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6188                s.select_ranges(tabstop.ranges.iter().cloned());
 6189            });
 6190
 6191            if let Some(choices) = &tabstop.choices {
 6192                if let Some(selection) = tabstop.ranges.first() {
 6193                    self.show_snippet_choices(choices, selection.clone(), cx)
 6194                }
 6195            }
 6196
 6197            // If we're already at the last tabstop and it's at the end of the snippet,
 6198            // we're done, we don't need to keep the state around.
 6199            if !tabstop.is_end_tabstop {
 6200                let choices = tabstops
 6201                    .iter()
 6202                    .map(|tabstop| tabstop.choices.clone())
 6203                    .collect();
 6204
 6205                let ranges = tabstops
 6206                    .into_iter()
 6207                    .map(|tabstop| tabstop.ranges)
 6208                    .collect::<Vec<_>>();
 6209
 6210                self.snippet_stack.push(SnippetState {
 6211                    active_index: 0,
 6212                    ranges,
 6213                    choices,
 6214                });
 6215            }
 6216
 6217            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6218            if self.autoclose_regions.is_empty() {
 6219                let snapshot = self.buffer.read(cx).snapshot(cx);
 6220                for selection in &mut self.selections.all::<Point>(cx) {
 6221                    let selection_head = selection.head();
 6222                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6223                        continue;
 6224                    };
 6225
 6226                    let mut bracket_pair = None;
 6227                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6228                    let prev_chars = snapshot
 6229                        .reversed_chars_at(selection_head)
 6230                        .collect::<String>();
 6231                    for (pair, enabled) in scope.brackets() {
 6232                        if enabled
 6233                            && pair.close
 6234                            && prev_chars.starts_with(pair.start.as_str())
 6235                            && next_chars.starts_with(pair.end.as_str())
 6236                        {
 6237                            bracket_pair = Some(pair.clone());
 6238                            break;
 6239                        }
 6240                    }
 6241                    if let Some(pair) = bracket_pair {
 6242                        let start = snapshot.anchor_after(selection_head);
 6243                        let end = snapshot.anchor_after(selection_head);
 6244                        self.autoclose_regions.push(AutocloseRegion {
 6245                            selection_id: selection.id,
 6246                            range: start..end,
 6247                            pair,
 6248                        });
 6249                    }
 6250                }
 6251            }
 6252        }
 6253        Ok(())
 6254    }
 6255
 6256    pub fn move_to_next_snippet_tabstop(
 6257        &mut self,
 6258        window: &mut Window,
 6259        cx: &mut Context<Self>,
 6260    ) -> bool {
 6261        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6262    }
 6263
 6264    pub fn move_to_prev_snippet_tabstop(
 6265        &mut self,
 6266        window: &mut Window,
 6267        cx: &mut Context<Self>,
 6268    ) -> bool {
 6269        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6270    }
 6271
 6272    pub fn move_to_snippet_tabstop(
 6273        &mut self,
 6274        bias: Bias,
 6275        window: &mut Window,
 6276        cx: &mut Context<Self>,
 6277    ) -> bool {
 6278        if let Some(mut snippet) = self.snippet_stack.pop() {
 6279            match bias {
 6280                Bias::Left => {
 6281                    if snippet.active_index > 0 {
 6282                        snippet.active_index -= 1;
 6283                    } else {
 6284                        self.snippet_stack.push(snippet);
 6285                        return false;
 6286                    }
 6287                }
 6288                Bias::Right => {
 6289                    if snippet.active_index + 1 < snippet.ranges.len() {
 6290                        snippet.active_index += 1;
 6291                    } else {
 6292                        self.snippet_stack.push(snippet);
 6293                        return false;
 6294                    }
 6295                }
 6296            }
 6297            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6298                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6299                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6300                });
 6301
 6302                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6303                    if let Some(selection) = current_ranges.first() {
 6304                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6305                    }
 6306                }
 6307
 6308                // If snippet state is not at the last tabstop, push it back on the stack
 6309                if snippet.active_index + 1 < snippet.ranges.len() {
 6310                    self.snippet_stack.push(snippet);
 6311                }
 6312                return true;
 6313            }
 6314        }
 6315
 6316        false
 6317    }
 6318
 6319    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6320        self.transact(window, cx, |this, window, cx| {
 6321            this.select_all(&SelectAll, window, cx);
 6322            this.insert("", window, cx);
 6323        });
 6324    }
 6325
 6326    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6327        self.transact(window, cx, |this, window, cx| {
 6328            this.select_autoclose_pair(window, cx);
 6329            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6330            if !this.linked_edit_ranges.is_empty() {
 6331                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6332                let snapshot = this.buffer.read(cx).snapshot(cx);
 6333
 6334                for selection in selections.iter() {
 6335                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6336                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6337                    if selection_start.buffer_id != selection_end.buffer_id {
 6338                        continue;
 6339                    }
 6340                    if let Some(ranges) =
 6341                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6342                    {
 6343                        for (buffer, entries) in ranges {
 6344                            linked_ranges.entry(buffer).or_default().extend(entries);
 6345                        }
 6346                    }
 6347                }
 6348            }
 6349
 6350            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6351            if !this.selections.line_mode {
 6352                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6353                for selection in &mut selections {
 6354                    if selection.is_empty() {
 6355                        let old_head = selection.head();
 6356                        let mut new_head =
 6357                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6358                                .to_point(&display_map);
 6359                        if let Some((buffer, line_buffer_range)) = display_map
 6360                            .buffer_snapshot
 6361                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6362                        {
 6363                            let indent_size =
 6364                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6365                            let indent_len = match indent_size.kind {
 6366                                IndentKind::Space => {
 6367                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6368                                }
 6369                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6370                            };
 6371                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6372                                let indent_len = indent_len.get();
 6373                                new_head = cmp::min(
 6374                                    new_head,
 6375                                    MultiBufferPoint::new(
 6376                                        old_head.row,
 6377                                        ((old_head.column - 1) / indent_len) * indent_len,
 6378                                    ),
 6379                                );
 6380                            }
 6381                        }
 6382
 6383                        selection.set_head(new_head, SelectionGoal::None);
 6384                    }
 6385                }
 6386            }
 6387
 6388            this.signature_help_state.set_backspace_pressed(true);
 6389            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6390                s.select(selections)
 6391            });
 6392            this.insert("", window, cx);
 6393            let empty_str: Arc<str> = Arc::from("");
 6394            for (buffer, edits) in linked_ranges {
 6395                let snapshot = buffer.read(cx).snapshot();
 6396                use text::ToPoint as TP;
 6397
 6398                let edits = edits
 6399                    .into_iter()
 6400                    .map(|range| {
 6401                        let end_point = TP::to_point(&range.end, &snapshot);
 6402                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6403
 6404                        if end_point == start_point {
 6405                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6406                                .saturating_sub(1);
 6407                            start_point =
 6408                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6409                        };
 6410
 6411                        (start_point..end_point, empty_str.clone())
 6412                    })
 6413                    .sorted_by_key(|(range, _)| range.start)
 6414                    .collect::<Vec<_>>();
 6415                buffer.update(cx, |this, cx| {
 6416                    this.edit(edits, None, cx);
 6417                })
 6418            }
 6419            this.refresh_inline_completion(true, false, window, cx);
 6420            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6421        });
 6422    }
 6423
 6424    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6425        self.transact(window, cx, |this, window, cx| {
 6426            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6427                let line_mode = s.line_mode;
 6428                s.move_with(|map, selection| {
 6429                    if selection.is_empty() && !line_mode {
 6430                        let cursor = movement::right(map, selection.head());
 6431                        selection.end = cursor;
 6432                        selection.reversed = true;
 6433                        selection.goal = SelectionGoal::None;
 6434                    }
 6435                })
 6436            });
 6437            this.insert("", window, cx);
 6438            this.refresh_inline_completion(true, false, window, cx);
 6439        });
 6440    }
 6441
 6442    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6443        if self.move_to_prev_snippet_tabstop(window, cx) {
 6444            return;
 6445        }
 6446
 6447        self.outdent(&Outdent, window, cx);
 6448    }
 6449
 6450    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6451        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6452            return;
 6453        }
 6454
 6455        let mut selections = self.selections.all_adjusted(cx);
 6456        let buffer = self.buffer.read(cx);
 6457        let snapshot = buffer.snapshot(cx);
 6458        let rows_iter = selections.iter().map(|s| s.head().row);
 6459        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6460
 6461        let mut edits = Vec::new();
 6462        let mut prev_edited_row = 0;
 6463        let mut row_delta = 0;
 6464        for selection in &mut selections {
 6465            if selection.start.row != prev_edited_row {
 6466                row_delta = 0;
 6467            }
 6468            prev_edited_row = selection.end.row;
 6469
 6470            // If the selection is non-empty, then increase the indentation of the selected lines.
 6471            if !selection.is_empty() {
 6472                row_delta =
 6473                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6474                continue;
 6475            }
 6476
 6477            // If the selection is empty and the cursor is in the leading whitespace before the
 6478            // suggested indentation, then auto-indent the line.
 6479            let cursor = selection.head();
 6480            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6481            if let Some(suggested_indent) =
 6482                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6483            {
 6484                if cursor.column < suggested_indent.len
 6485                    && cursor.column <= current_indent.len
 6486                    && current_indent.len <= suggested_indent.len
 6487                {
 6488                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6489                    selection.end = selection.start;
 6490                    if row_delta == 0 {
 6491                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6492                            cursor.row,
 6493                            current_indent,
 6494                            suggested_indent,
 6495                        ));
 6496                        row_delta = suggested_indent.len - current_indent.len;
 6497                    }
 6498                    continue;
 6499                }
 6500            }
 6501
 6502            // Otherwise, insert a hard or soft tab.
 6503            let settings = buffer.settings_at(cursor, cx);
 6504            let tab_size = if settings.hard_tabs {
 6505                IndentSize::tab()
 6506            } else {
 6507                let tab_size = settings.tab_size.get();
 6508                let char_column = snapshot
 6509                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6510                    .flat_map(str::chars)
 6511                    .count()
 6512                    + row_delta as usize;
 6513                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6514                IndentSize::spaces(chars_to_next_tab_stop)
 6515            };
 6516            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6517            selection.end = selection.start;
 6518            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6519            row_delta += tab_size.len;
 6520        }
 6521
 6522        self.transact(window, cx, |this, window, cx| {
 6523            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6524            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6525                s.select(selections)
 6526            });
 6527            this.refresh_inline_completion(true, false, window, cx);
 6528        });
 6529    }
 6530
 6531    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6532        if self.read_only(cx) {
 6533            return;
 6534        }
 6535        let mut selections = self.selections.all::<Point>(cx);
 6536        let mut prev_edited_row = 0;
 6537        let mut row_delta = 0;
 6538        let mut edits = Vec::new();
 6539        let buffer = self.buffer.read(cx);
 6540        let snapshot = buffer.snapshot(cx);
 6541        for selection in &mut selections {
 6542            if selection.start.row != prev_edited_row {
 6543                row_delta = 0;
 6544            }
 6545            prev_edited_row = selection.end.row;
 6546
 6547            row_delta =
 6548                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6549        }
 6550
 6551        self.transact(window, cx, |this, window, cx| {
 6552            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6553            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6554                s.select(selections)
 6555            });
 6556        });
 6557    }
 6558
 6559    fn indent_selection(
 6560        buffer: &MultiBuffer,
 6561        snapshot: &MultiBufferSnapshot,
 6562        selection: &mut Selection<Point>,
 6563        edits: &mut Vec<(Range<Point>, String)>,
 6564        delta_for_start_row: u32,
 6565        cx: &App,
 6566    ) -> u32 {
 6567        let settings = buffer.settings_at(selection.start, cx);
 6568        let tab_size = settings.tab_size.get();
 6569        let indent_kind = if settings.hard_tabs {
 6570            IndentKind::Tab
 6571        } else {
 6572            IndentKind::Space
 6573        };
 6574        let mut start_row = selection.start.row;
 6575        let mut end_row = selection.end.row + 1;
 6576
 6577        // If a selection ends at the beginning of a line, don't indent
 6578        // that last line.
 6579        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6580            end_row -= 1;
 6581        }
 6582
 6583        // Avoid re-indenting a row that has already been indented by a
 6584        // previous selection, but still update this selection's column
 6585        // to reflect that indentation.
 6586        if delta_for_start_row > 0 {
 6587            start_row += 1;
 6588            selection.start.column += delta_for_start_row;
 6589            if selection.end.row == selection.start.row {
 6590                selection.end.column += delta_for_start_row;
 6591            }
 6592        }
 6593
 6594        let mut delta_for_end_row = 0;
 6595        let has_multiple_rows = start_row + 1 != end_row;
 6596        for row in start_row..end_row {
 6597            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6598            let indent_delta = match (current_indent.kind, indent_kind) {
 6599                (IndentKind::Space, IndentKind::Space) => {
 6600                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6601                    IndentSize::spaces(columns_to_next_tab_stop)
 6602                }
 6603                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6604                (_, IndentKind::Tab) => IndentSize::tab(),
 6605            };
 6606
 6607            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6608                0
 6609            } else {
 6610                selection.start.column
 6611            };
 6612            let row_start = Point::new(row, start);
 6613            edits.push((
 6614                row_start..row_start,
 6615                indent_delta.chars().collect::<String>(),
 6616            ));
 6617
 6618            // Update this selection's endpoints to reflect the indentation.
 6619            if row == selection.start.row {
 6620                selection.start.column += indent_delta.len;
 6621            }
 6622            if row == selection.end.row {
 6623                selection.end.column += indent_delta.len;
 6624                delta_for_end_row = indent_delta.len;
 6625            }
 6626        }
 6627
 6628        if selection.start.row == selection.end.row {
 6629            delta_for_start_row + delta_for_end_row
 6630        } else {
 6631            delta_for_end_row
 6632        }
 6633    }
 6634
 6635    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6636        if self.read_only(cx) {
 6637            return;
 6638        }
 6639        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6640        let selections = self.selections.all::<Point>(cx);
 6641        let mut deletion_ranges = Vec::new();
 6642        let mut last_outdent = None;
 6643        {
 6644            let buffer = self.buffer.read(cx);
 6645            let snapshot = buffer.snapshot(cx);
 6646            for selection in &selections {
 6647                let settings = buffer.settings_at(selection.start, cx);
 6648                let tab_size = settings.tab_size.get();
 6649                let mut rows = selection.spanned_rows(false, &display_map);
 6650
 6651                // Avoid re-outdenting a row that has already been outdented by a
 6652                // previous selection.
 6653                if let Some(last_row) = last_outdent {
 6654                    if last_row == rows.start {
 6655                        rows.start = rows.start.next_row();
 6656                    }
 6657                }
 6658                let has_multiple_rows = rows.len() > 1;
 6659                for row in rows.iter_rows() {
 6660                    let indent_size = snapshot.indent_size_for_line(row);
 6661                    if indent_size.len > 0 {
 6662                        let deletion_len = match indent_size.kind {
 6663                            IndentKind::Space => {
 6664                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6665                                if columns_to_prev_tab_stop == 0 {
 6666                                    tab_size
 6667                                } else {
 6668                                    columns_to_prev_tab_stop
 6669                                }
 6670                            }
 6671                            IndentKind::Tab => 1,
 6672                        };
 6673                        let start = if has_multiple_rows
 6674                            || deletion_len > selection.start.column
 6675                            || indent_size.len < selection.start.column
 6676                        {
 6677                            0
 6678                        } else {
 6679                            selection.start.column - deletion_len
 6680                        };
 6681                        deletion_ranges.push(
 6682                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6683                        );
 6684                        last_outdent = Some(row);
 6685                    }
 6686                }
 6687            }
 6688        }
 6689
 6690        self.transact(window, cx, |this, window, cx| {
 6691            this.buffer.update(cx, |buffer, cx| {
 6692                let empty_str: Arc<str> = Arc::default();
 6693                buffer.edit(
 6694                    deletion_ranges
 6695                        .into_iter()
 6696                        .map(|range| (range, empty_str.clone())),
 6697                    None,
 6698                    cx,
 6699                );
 6700            });
 6701            let selections = this.selections.all::<usize>(cx);
 6702            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6703                s.select(selections)
 6704            });
 6705        });
 6706    }
 6707
 6708    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6709        if self.read_only(cx) {
 6710            return;
 6711        }
 6712        let selections = self
 6713            .selections
 6714            .all::<usize>(cx)
 6715            .into_iter()
 6716            .map(|s| s.range());
 6717
 6718        self.transact(window, cx, |this, window, cx| {
 6719            this.buffer.update(cx, |buffer, cx| {
 6720                buffer.autoindent_ranges(selections, cx);
 6721            });
 6722            let selections = this.selections.all::<usize>(cx);
 6723            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6724                s.select(selections)
 6725            });
 6726        });
 6727    }
 6728
 6729    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6730        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6731        let selections = self.selections.all::<Point>(cx);
 6732
 6733        let mut new_cursors = Vec::new();
 6734        let mut edit_ranges = Vec::new();
 6735        let mut selections = selections.iter().peekable();
 6736        while let Some(selection) = selections.next() {
 6737            let mut rows = selection.spanned_rows(false, &display_map);
 6738            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6739
 6740            // Accumulate contiguous regions of rows that we want to delete.
 6741            while let Some(next_selection) = selections.peek() {
 6742                let next_rows = next_selection.spanned_rows(false, &display_map);
 6743                if next_rows.start <= rows.end {
 6744                    rows.end = next_rows.end;
 6745                    selections.next().unwrap();
 6746                } else {
 6747                    break;
 6748                }
 6749            }
 6750
 6751            let buffer = &display_map.buffer_snapshot;
 6752            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6753            let edit_end;
 6754            let cursor_buffer_row;
 6755            if buffer.max_point().row >= rows.end.0 {
 6756                // If there's a line after the range, delete the \n from the end of the row range
 6757                // and position the cursor on the next line.
 6758                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6759                cursor_buffer_row = rows.end;
 6760            } else {
 6761                // If there isn't a line after the range, delete the \n from the line before the
 6762                // start of the row range and position the cursor there.
 6763                edit_start = edit_start.saturating_sub(1);
 6764                edit_end = buffer.len();
 6765                cursor_buffer_row = rows.start.previous_row();
 6766            }
 6767
 6768            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6769            *cursor.column_mut() =
 6770                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6771
 6772            new_cursors.push((
 6773                selection.id,
 6774                buffer.anchor_after(cursor.to_point(&display_map)),
 6775            ));
 6776            edit_ranges.push(edit_start..edit_end);
 6777        }
 6778
 6779        self.transact(window, cx, |this, window, cx| {
 6780            let buffer = this.buffer.update(cx, |buffer, cx| {
 6781                let empty_str: Arc<str> = Arc::default();
 6782                buffer.edit(
 6783                    edit_ranges
 6784                        .into_iter()
 6785                        .map(|range| (range, empty_str.clone())),
 6786                    None,
 6787                    cx,
 6788                );
 6789                buffer.snapshot(cx)
 6790            });
 6791            let new_selections = new_cursors
 6792                .into_iter()
 6793                .map(|(id, cursor)| {
 6794                    let cursor = cursor.to_point(&buffer);
 6795                    Selection {
 6796                        id,
 6797                        start: cursor,
 6798                        end: cursor,
 6799                        reversed: false,
 6800                        goal: SelectionGoal::None,
 6801                    }
 6802                })
 6803                .collect();
 6804
 6805            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6806                s.select(new_selections);
 6807            });
 6808        });
 6809    }
 6810
 6811    pub fn join_lines_impl(
 6812        &mut self,
 6813        insert_whitespace: bool,
 6814        window: &mut Window,
 6815        cx: &mut Context<Self>,
 6816    ) {
 6817        if self.read_only(cx) {
 6818            return;
 6819        }
 6820        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6821        for selection in self.selections.all::<Point>(cx) {
 6822            let start = MultiBufferRow(selection.start.row);
 6823            // Treat single line selections as if they include the next line. Otherwise this action
 6824            // would do nothing for single line selections individual cursors.
 6825            let end = if selection.start.row == selection.end.row {
 6826                MultiBufferRow(selection.start.row + 1)
 6827            } else {
 6828                MultiBufferRow(selection.end.row)
 6829            };
 6830
 6831            if let Some(last_row_range) = row_ranges.last_mut() {
 6832                if start <= last_row_range.end {
 6833                    last_row_range.end = end;
 6834                    continue;
 6835                }
 6836            }
 6837            row_ranges.push(start..end);
 6838        }
 6839
 6840        let snapshot = self.buffer.read(cx).snapshot(cx);
 6841        let mut cursor_positions = Vec::new();
 6842        for row_range in &row_ranges {
 6843            let anchor = snapshot.anchor_before(Point::new(
 6844                row_range.end.previous_row().0,
 6845                snapshot.line_len(row_range.end.previous_row()),
 6846            ));
 6847            cursor_positions.push(anchor..anchor);
 6848        }
 6849
 6850        self.transact(window, cx, |this, window, cx| {
 6851            for row_range in row_ranges.into_iter().rev() {
 6852                for row in row_range.iter_rows().rev() {
 6853                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6854                    let next_line_row = row.next_row();
 6855                    let indent = snapshot.indent_size_for_line(next_line_row);
 6856                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6857
 6858                    let replace =
 6859                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6860                            " "
 6861                        } else {
 6862                            ""
 6863                        };
 6864
 6865                    this.buffer.update(cx, |buffer, cx| {
 6866                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6867                    });
 6868                }
 6869            }
 6870
 6871            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6872                s.select_anchor_ranges(cursor_positions)
 6873            });
 6874        });
 6875    }
 6876
 6877    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6878        self.join_lines_impl(true, window, cx);
 6879    }
 6880
 6881    pub fn sort_lines_case_sensitive(
 6882        &mut self,
 6883        _: &SortLinesCaseSensitive,
 6884        window: &mut Window,
 6885        cx: &mut Context<Self>,
 6886    ) {
 6887        self.manipulate_lines(window, cx, |lines| lines.sort())
 6888    }
 6889
 6890    pub fn sort_lines_case_insensitive(
 6891        &mut self,
 6892        _: &SortLinesCaseInsensitive,
 6893        window: &mut Window,
 6894        cx: &mut Context<Self>,
 6895    ) {
 6896        self.manipulate_lines(window, cx, |lines| {
 6897            lines.sort_by_key(|line| line.to_lowercase())
 6898        })
 6899    }
 6900
 6901    pub fn unique_lines_case_insensitive(
 6902        &mut self,
 6903        _: &UniqueLinesCaseInsensitive,
 6904        window: &mut Window,
 6905        cx: &mut Context<Self>,
 6906    ) {
 6907        self.manipulate_lines(window, cx, |lines| {
 6908            let mut seen = HashSet::default();
 6909            lines.retain(|line| seen.insert(line.to_lowercase()));
 6910        })
 6911    }
 6912
 6913    pub fn unique_lines_case_sensitive(
 6914        &mut self,
 6915        _: &UniqueLinesCaseSensitive,
 6916        window: &mut Window,
 6917        cx: &mut Context<Self>,
 6918    ) {
 6919        self.manipulate_lines(window, cx, |lines| {
 6920            let mut seen = HashSet::default();
 6921            lines.retain(|line| seen.insert(*line));
 6922        })
 6923    }
 6924
 6925    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6926        let mut revert_changes = HashMap::default();
 6927        let snapshot = self.snapshot(window, cx);
 6928        for hunk in snapshot
 6929            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6930        {
 6931            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6932        }
 6933        if !revert_changes.is_empty() {
 6934            self.transact(window, cx, |editor, window, cx| {
 6935                editor.revert(revert_changes, window, cx);
 6936            });
 6937        }
 6938    }
 6939
 6940    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6941        let Some(project) = self.project.clone() else {
 6942            return;
 6943        };
 6944        self.reload(project, window, cx)
 6945            .detach_and_notify_err(window, cx);
 6946    }
 6947
 6948    pub fn revert_selected_hunks(
 6949        &mut self,
 6950        _: &RevertSelectedHunks,
 6951        window: &mut Window,
 6952        cx: &mut Context<Self>,
 6953    ) {
 6954        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6955        self.revert_hunks_in_ranges(selections, window, cx);
 6956    }
 6957
 6958    fn revert_hunks_in_ranges(
 6959        &mut self,
 6960        ranges: impl Iterator<Item = Range<Point>>,
 6961        window: &mut Window,
 6962        cx: &mut Context<Editor>,
 6963    ) {
 6964        let mut revert_changes = HashMap::default();
 6965        let snapshot = self.snapshot(window, cx);
 6966        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6967            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6968        }
 6969        if !revert_changes.is_empty() {
 6970            self.transact(window, cx, |editor, window, cx| {
 6971                editor.revert(revert_changes, window, cx);
 6972            });
 6973        }
 6974    }
 6975
 6976    pub fn open_active_item_in_terminal(
 6977        &mut self,
 6978        _: &OpenInTerminal,
 6979        window: &mut Window,
 6980        cx: &mut Context<Self>,
 6981    ) {
 6982        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6983            let project_path = buffer.read(cx).project_path(cx)?;
 6984            let project = self.project.as_ref()?.read(cx);
 6985            let entry = project.entry_for_path(&project_path, cx)?;
 6986            let parent = match &entry.canonical_path {
 6987                Some(canonical_path) => canonical_path.to_path_buf(),
 6988                None => project.absolute_path(&project_path, cx)?,
 6989            }
 6990            .parent()?
 6991            .to_path_buf();
 6992            Some(parent)
 6993        }) {
 6994            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6995        }
 6996    }
 6997
 6998    pub fn prepare_revert_change(
 6999        &self,
 7000        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7001        hunk: &MultiBufferDiffHunk,
 7002        cx: &mut App,
 7003    ) -> Option<()> {
 7004        let buffer = self.buffer.read(cx);
 7005        let diff = buffer.diff_for(hunk.buffer_id)?;
 7006        let buffer = buffer.buffer(hunk.buffer_id)?;
 7007        let buffer = buffer.read(cx);
 7008        let original_text = diff
 7009            .read(cx)
 7010            .base_text()
 7011            .as_ref()?
 7012            .as_rope()
 7013            .slice(hunk.diff_base_byte_range.clone());
 7014        let buffer_snapshot = buffer.snapshot();
 7015        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7016        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7017            probe
 7018                .0
 7019                .start
 7020                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7021                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7022        }) {
 7023            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7024            Some(())
 7025        } else {
 7026            None
 7027        }
 7028    }
 7029
 7030    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7031        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7032    }
 7033
 7034    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7035        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7036    }
 7037
 7038    fn manipulate_lines<Fn>(
 7039        &mut self,
 7040        window: &mut Window,
 7041        cx: &mut Context<Self>,
 7042        mut callback: Fn,
 7043    ) where
 7044        Fn: FnMut(&mut Vec<&str>),
 7045    {
 7046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7047        let buffer = self.buffer.read(cx).snapshot(cx);
 7048
 7049        let mut edits = Vec::new();
 7050
 7051        let selections = self.selections.all::<Point>(cx);
 7052        let mut selections = selections.iter().peekable();
 7053        let mut contiguous_row_selections = Vec::new();
 7054        let mut new_selections = Vec::new();
 7055        let mut added_lines = 0;
 7056        let mut removed_lines = 0;
 7057
 7058        while let Some(selection) = selections.next() {
 7059            let (start_row, end_row) = consume_contiguous_rows(
 7060                &mut contiguous_row_selections,
 7061                selection,
 7062                &display_map,
 7063                &mut selections,
 7064            );
 7065
 7066            let start_point = Point::new(start_row.0, 0);
 7067            let end_point = Point::new(
 7068                end_row.previous_row().0,
 7069                buffer.line_len(end_row.previous_row()),
 7070            );
 7071            let text = buffer
 7072                .text_for_range(start_point..end_point)
 7073                .collect::<String>();
 7074
 7075            let mut lines = text.split('\n').collect_vec();
 7076
 7077            let lines_before = lines.len();
 7078            callback(&mut lines);
 7079            let lines_after = lines.len();
 7080
 7081            edits.push((start_point..end_point, lines.join("\n")));
 7082
 7083            // Selections must change based on added and removed line count
 7084            let start_row =
 7085                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7086            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7087            new_selections.push(Selection {
 7088                id: selection.id,
 7089                start: start_row,
 7090                end: end_row,
 7091                goal: SelectionGoal::None,
 7092                reversed: selection.reversed,
 7093            });
 7094
 7095            if lines_after > lines_before {
 7096                added_lines += lines_after - lines_before;
 7097            } else if lines_before > lines_after {
 7098                removed_lines += lines_before - lines_after;
 7099            }
 7100        }
 7101
 7102        self.transact(window, cx, |this, window, cx| {
 7103            let buffer = this.buffer.update(cx, |buffer, cx| {
 7104                buffer.edit(edits, None, cx);
 7105                buffer.snapshot(cx)
 7106            });
 7107
 7108            // Recalculate offsets on newly edited buffer
 7109            let new_selections = new_selections
 7110                .iter()
 7111                .map(|s| {
 7112                    let start_point = Point::new(s.start.0, 0);
 7113                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7114                    Selection {
 7115                        id: s.id,
 7116                        start: buffer.point_to_offset(start_point),
 7117                        end: buffer.point_to_offset(end_point),
 7118                        goal: s.goal,
 7119                        reversed: s.reversed,
 7120                    }
 7121                })
 7122                .collect();
 7123
 7124            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7125                s.select(new_selections);
 7126            });
 7127
 7128            this.request_autoscroll(Autoscroll::fit(), cx);
 7129        });
 7130    }
 7131
 7132    pub fn convert_to_upper_case(
 7133        &mut self,
 7134        _: &ConvertToUpperCase,
 7135        window: &mut Window,
 7136        cx: &mut Context<Self>,
 7137    ) {
 7138        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7139    }
 7140
 7141    pub fn convert_to_lower_case(
 7142        &mut self,
 7143        _: &ConvertToLowerCase,
 7144        window: &mut Window,
 7145        cx: &mut Context<Self>,
 7146    ) {
 7147        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7148    }
 7149
 7150    pub fn convert_to_title_case(
 7151        &mut self,
 7152        _: &ConvertToTitleCase,
 7153        window: &mut Window,
 7154        cx: &mut Context<Self>,
 7155    ) {
 7156        self.manipulate_text(window, cx, |text| {
 7157            text.split('\n')
 7158                .map(|line| line.to_case(Case::Title))
 7159                .join("\n")
 7160        })
 7161    }
 7162
 7163    pub fn convert_to_snake_case(
 7164        &mut self,
 7165        _: &ConvertToSnakeCase,
 7166        window: &mut Window,
 7167        cx: &mut Context<Self>,
 7168    ) {
 7169        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7170    }
 7171
 7172    pub fn convert_to_kebab_case(
 7173        &mut self,
 7174        _: &ConvertToKebabCase,
 7175        window: &mut Window,
 7176        cx: &mut Context<Self>,
 7177    ) {
 7178        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7179    }
 7180
 7181    pub fn convert_to_upper_camel_case(
 7182        &mut self,
 7183        _: &ConvertToUpperCamelCase,
 7184        window: &mut Window,
 7185        cx: &mut Context<Self>,
 7186    ) {
 7187        self.manipulate_text(window, cx, |text| {
 7188            text.split('\n')
 7189                .map(|line| line.to_case(Case::UpperCamel))
 7190                .join("\n")
 7191        })
 7192    }
 7193
 7194    pub fn convert_to_lower_camel_case(
 7195        &mut self,
 7196        _: &ConvertToLowerCamelCase,
 7197        window: &mut Window,
 7198        cx: &mut Context<Self>,
 7199    ) {
 7200        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7201    }
 7202
 7203    pub fn convert_to_opposite_case(
 7204        &mut self,
 7205        _: &ConvertToOppositeCase,
 7206        window: &mut Window,
 7207        cx: &mut Context<Self>,
 7208    ) {
 7209        self.manipulate_text(window, cx, |text| {
 7210            text.chars()
 7211                .fold(String::with_capacity(text.len()), |mut t, c| {
 7212                    if c.is_uppercase() {
 7213                        t.extend(c.to_lowercase());
 7214                    } else {
 7215                        t.extend(c.to_uppercase());
 7216                    }
 7217                    t
 7218                })
 7219        })
 7220    }
 7221
 7222    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7223    where
 7224        Fn: FnMut(&str) -> String,
 7225    {
 7226        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7227        let buffer = self.buffer.read(cx).snapshot(cx);
 7228
 7229        let mut new_selections = Vec::new();
 7230        let mut edits = Vec::new();
 7231        let mut selection_adjustment = 0i32;
 7232
 7233        for selection in self.selections.all::<usize>(cx) {
 7234            let selection_is_empty = selection.is_empty();
 7235
 7236            let (start, end) = if selection_is_empty {
 7237                let word_range = movement::surrounding_word(
 7238                    &display_map,
 7239                    selection.start.to_display_point(&display_map),
 7240                );
 7241                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7242                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7243                (start, end)
 7244            } else {
 7245                (selection.start, selection.end)
 7246            };
 7247
 7248            let text = buffer.text_for_range(start..end).collect::<String>();
 7249            let old_length = text.len() as i32;
 7250            let text = callback(&text);
 7251
 7252            new_selections.push(Selection {
 7253                start: (start as i32 - selection_adjustment) as usize,
 7254                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7255                goal: SelectionGoal::None,
 7256                ..selection
 7257            });
 7258
 7259            selection_adjustment += old_length - text.len() as i32;
 7260
 7261            edits.push((start..end, text));
 7262        }
 7263
 7264        self.transact(window, cx, |this, window, cx| {
 7265            this.buffer.update(cx, |buffer, cx| {
 7266                buffer.edit(edits, None, cx);
 7267            });
 7268
 7269            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7270                s.select(new_selections);
 7271            });
 7272
 7273            this.request_autoscroll(Autoscroll::fit(), cx);
 7274        });
 7275    }
 7276
 7277    pub fn duplicate(
 7278        &mut self,
 7279        upwards: bool,
 7280        whole_lines: bool,
 7281        window: &mut Window,
 7282        cx: &mut Context<Self>,
 7283    ) {
 7284        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7285        let buffer = &display_map.buffer_snapshot;
 7286        let selections = self.selections.all::<Point>(cx);
 7287
 7288        let mut edits = Vec::new();
 7289        let mut selections_iter = selections.iter().peekable();
 7290        while let Some(selection) = selections_iter.next() {
 7291            let mut rows = selection.spanned_rows(false, &display_map);
 7292            // duplicate line-wise
 7293            if whole_lines || selection.start == selection.end {
 7294                // Avoid duplicating the same lines twice.
 7295                while let Some(next_selection) = selections_iter.peek() {
 7296                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7297                    if next_rows.start < rows.end {
 7298                        rows.end = next_rows.end;
 7299                        selections_iter.next().unwrap();
 7300                    } else {
 7301                        break;
 7302                    }
 7303                }
 7304
 7305                // Copy the text from the selected row region and splice it either at the start
 7306                // or end of the region.
 7307                let start = Point::new(rows.start.0, 0);
 7308                let end = Point::new(
 7309                    rows.end.previous_row().0,
 7310                    buffer.line_len(rows.end.previous_row()),
 7311                );
 7312                let text = buffer
 7313                    .text_for_range(start..end)
 7314                    .chain(Some("\n"))
 7315                    .collect::<String>();
 7316                let insert_location = if upwards {
 7317                    Point::new(rows.end.0, 0)
 7318                } else {
 7319                    start
 7320                };
 7321                edits.push((insert_location..insert_location, text));
 7322            } else {
 7323                // duplicate character-wise
 7324                let start = selection.start;
 7325                let end = selection.end;
 7326                let text = buffer.text_for_range(start..end).collect::<String>();
 7327                edits.push((selection.end..selection.end, text));
 7328            }
 7329        }
 7330
 7331        self.transact(window, cx, |this, _, cx| {
 7332            this.buffer.update(cx, |buffer, cx| {
 7333                buffer.edit(edits, None, cx);
 7334            });
 7335
 7336            this.request_autoscroll(Autoscroll::fit(), cx);
 7337        });
 7338    }
 7339
 7340    pub fn duplicate_line_up(
 7341        &mut self,
 7342        _: &DuplicateLineUp,
 7343        window: &mut Window,
 7344        cx: &mut Context<Self>,
 7345    ) {
 7346        self.duplicate(true, true, window, cx);
 7347    }
 7348
 7349    pub fn duplicate_line_down(
 7350        &mut self,
 7351        _: &DuplicateLineDown,
 7352        window: &mut Window,
 7353        cx: &mut Context<Self>,
 7354    ) {
 7355        self.duplicate(false, true, window, cx);
 7356    }
 7357
 7358    pub fn duplicate_selection(
 7359        &mut self,
 7360        _: &DuplicateSelection,
 7361        window: &mut Window,
 7362        cx: &mut Context<Self>,
 7363    ) {
 7364        self.duplicate(false, false, window, cx);
 7365    }
 7366
 7367    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7368        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7369        let buffer = self.buffer.read(cx).snapshot(cx);
 7370
 7371        let mut edits = Vec::new();
 7372        let mut unfold_ranges = Vec::new();
 7373        let mut refold_creases = Vec::new();
 7374
 7375        let selections = self.selections.all::<Point>(cx);
 7376        let mut selections = selections.iter().peekable();
 7377        let mut contiguous_row_selections = Vec::new();
 7378        let mut new_selections = Vec::new();
 7379
 7380        while let Some(selection) = selections.next() {
 7381            // Find all the selections that span a contiguous row range
 7382            let (start_row, end_row) = consume_contiguous_rows(
 7383                &mut contiguous_row_selections,
 7384                selection,
 7385                &display_map,
 7386                &mut selections,
 7387            );
 7388
 7389            // Move the text spanned by the row range to be before the line preceding the row range
 7390            if start_row.0 > 0 {
 7391                let range_to_move = Point::new(
 7392                    start_row.previous_row().0,
 7393                    buffer.line_len(start_row.previous_row()),
 7394                )
 7395                    ..Point::new(
 7396                        end_row.previous_row().0,
 7397                        buffer.line_len(end_row.previous_row()),
 7398                    );
 7399                let insertion_point = display_map
 7400                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7401                    .0;
 7402
 7403                // Don't move lines across excerpts
 7404                if buffer
 7405                    .excerpt_containing(insertion_point..range_to_move.end)
 7406                    .is_some()
 7407                {
 7408                    let text = buffer
 7409                        .text_for_range(range_to_move.clone())
 7410                        .flat_map(|s| s.chars())
 7411                        .skip(1)
 7412                        .chain(['\n'])
 7413                        .collect::<String>();
 7414
 7415                    edits.push((
 7416                        buffer.anchor_after(range_to_move.start)
 7417                            ..buffer.anchor_before(range_to_move.end),
 7418                        String::new(),
 7419                    ));
 7420                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7421                    edits.push((insertion_anchor..insertion_anchor, text));
 7422
 7423                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7424
 7425                    // Move selections up
 7426                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7427                        |mut selection| {
 7428                            selection.start.row -= row_delta;
 7429                            selection.end.row -= row_delta;
 7430                            selection
 7431                        },
 7432                    ));
 7433
 7434                    // Move folds up
 7435                    unfold_ranges.push(range_to_move.clone());
 7436                    for fold in display_map.folds_in_range(
 7437                        buffer.anchor_before(range_to_move.start)
 7438                            ..buffer.anchor_after(range_to_move.end),
 7439                    ) {
 7440                        let mut start = fold.range.start.to_point(&buffer);
 7441                        let mut end = fold.range.end.to_point(&buffer);
 7442                        start.row -= row_delta;
 7443                        end.row -= row_delta;
 7444                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7445                    }
 7446                }
 7447            }
 7448
 7449            // If we didn't move line(s), preserve the existing selections
 7450            new_selections.append(&mut contiguous_row_selections);
 7451        }
 7452
 7453        self.transact(window, cx, |this, window, cx| {
 7454            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7455            this.buffer.update(cx, |buffer, cx| {
 7456                for (range, text) in edits {
 7457                    buffer.edit([(range, text)], None, cx);
 7458                }
 7459            });
 7460            this.fold_creases(refold_creases, true, window, cx);
 7461            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7462                s.select(new_selections);
 7463            })
 7464        });
 7465    }
 7466
 7467    pub fn move_line_down(
 7468        &mut self,
 7469        _: &MoveLineDown,
 7470        window: &mut Window,
 7471        cx: &mut Context<Self>,
 7472    ) {
 7473        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7474        let buffer = self.buffer.read(cx).snapshot(cx);
 7475
 7476        let mut edits = Vec::new();
 7477        let mut unfold_ranges = Vec::new();
 7478        let mut refold_creases = Vec::new();
 7479
 7480        let selections = self.selections.all::<Point>(cx);
 7481        let mut selections = selections.iter().peekable();
 7482        let mut contiguous_row_selections = Vec::new();
 7483        let mut new_selections = Vec::new();
 7484
 7485        while let Some(selection) = selections.next() {
 7486            // Find all the selections that span a contiguous row range
 7487            let (start_row, end_row) = consume_contiguous_rows(
 7488                &mut contiguous_row_selections,
 7489                selection,
 7490                &display_map,
 7491                &mut selections,
 7492            );
 7493
 7494            // Move the text spanned by the row range to be after the last line of the row range
 7495            if end_row.0 <= buffer.max_point().row {
 7496                let range_to_move =
 7497                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7498                let insertion_point = display_map
 7499                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7500                    .0;
 7501
 7502                // Don't move lines across excerpt boundaries
 7503                if buffer
 7504                    .excerpt_containing(range_to_move.start..insertion_point)
 7505                    .is_some()
 7506                {
 7507                    let mut text = String::from("\n");
 7508                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7509                    text.pop(); // Drop trailing newline
 7510                    edits.push((
 7511                        buffer.anchor_after(range_to_move.start)
 7512                            ..buffer.anchor_before(range_to_move.end),
 7513                        String::new(),
 7514                    ));
 7515                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7516                    edits.push((insertion_anchor..insertion_anchor, text));
 7517
 7518                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7519
 7520                    // Move selections down
 7521                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7522                        |mut selection| {
 7523                            selection.start.row += row_delta;
 7524                            selection.end.row += row_delta;
 7525                            selection
 7526                        },
 7527                    ));
 7528
 7529                    // Move folds down
 7530                    unfold_ranges.push(range_to_move.clone());
 7531                    for fold in display_map.folds_in_range(
 7532                        buffer.anchor_before(range_to_move.start)
 7533                            ..buffer.anchor_after(range_to_move.end),
 7534                    ) {
 7535                        let mut start = fold.range.start.to_point(&buffer);
 7536                        let mut end = fold.range.end.to_point(&buffer);
 7537                        start.row += row_delta;
 7538                        end.row += row_delta;
 7539                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7540                    }
 7541                }
 7542            }
 7543
 7544            // If we didn't move line(s), preserve the existing selections
 7545            new_selections.append(&mut contiguous_row_selections);
 7546        }
 7547
 7548        self.transact(window, cx, |this, window, cx| {
 7549            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7550            this.buffer.update(cx, |buffer, cx| {
 7551                for (range, text) in edits {
 7552                    buffer.edit([(range, text)], None, cx);
 7553                }
 7554            });
 7555            this.fold_creases(refold_creases, true, window, cx);
 7556            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7557                s.select(new_selections)
 7558            });
 7559        });
 7560    }
 7561
 7562    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7563        let text_layout_details = &self.text_layout_details(window);
 7564        self.transact(window, cx, |this, window, cx| {
 7565            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7566                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7567                let line_mode = s.line_mode;
 7568                s.move_with(|display_map, selection| {
 7569                    if !selection.is_empty() || line_mode {
 7570                        return;
 7571                    }
 7572
 7573                    let mut head = selection.head();
 7574                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7575                    if head.column() == display_map.line_len(head.row()) {
 7576                        transpose_offset = display_map
 7577                            .buffer_snapshot
 7578                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7579                    }
 7580
 7581                    if transpose_offset == 0 {
 7582                        return;
 7583                    }
 7584
 7585                    *head.column_mut() += 1;
 7586                    head = display_map.clip_point(head, Bias::Right);
 7587                    let goal = SelectionGoal::HorizontalPosition(
 7588                        display_map
 7589                            .x_for_display_point(head, text_layout_details)
 7590                            .into(),
 7591                    );
 7592                    selection.collapse_to(head, goal);
 7593
 7594                    let transpose_start = display_map
 7595                        .buffer_snapshot
 7596                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7597                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7598                        let transpose_end = display_map
 7599                            .buffer_snapshot
 7600                            .clip_offset(transpose_offset + 1, Bias::Right);
 7601                        if let Some(ch) =
 7602                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7603                        {
 7604                            edits.push((transpose_start..transpose_offset, String::new()));
 7605                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7606                        }
 7607                    }
 7608                });
 7609                edits
 7610            });
 7611            this.buffer
 7612                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7613            let selections = this.selections.all::<usize>(cx);
 7614            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7615                s.select(selections);
 7616            });
 7617        });
 7618    }
 7619
 7620    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7621        self.rewrap_impl(IsVimMode::No, cx)
 7622    }
 7623
 7624    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7625        let buffer = self.buffer.read(cx).snapshot(cx);
 7626        let selections = self.selections.all::<Point>(cx);
 7627        let mut selections = selections.iter().peekable();
 7628
 7629        let mut edits = Vec::new();
 7630        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7631
 7632        while let Some(selection) = selections.next() {
 7633            let mut start_row = selection.start.row;
 7634            let mut end_row = selection.end.row;
 7635
 7636            // Skip selections that overlap with a range that has already been rewrapped.
 7637            let selection_range = start_row..end_row;
 7638            if rewrapped_row_ranges
 7639                .iter()
 7640                .any(|range| range.overlaps(&selection_range))
 7641            {
 7642                continue;
 7643            }
 7644
 7645            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7646
 7647            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7648                match language_scope.language_name().as_ref() {
 7649                    "Markdown" | "Plain Text" => {
 7650                        should_rewrap = true;
 7651                    }
 7652                    _ => {}
 7653                }
 7654            }
 7655
 7656            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7657
 7658            // Since not all lines in the selection may be at the same indent
 7659            // level, choose the indent size that is the most common between all
 7660            // of the lines.
 7661            //
 7662            // If there is a tie, we use the deepest indent.
 7663            let (indent_size, indent_end) = {
 7664                let mut indent_size_occurrences = HashMap::default();
 7665                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7666
 7667                for row in start_row..=end_row {
 7668                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7669                    rows_by_indent_size.entry(indent).or_default().push(row);
 7670                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7671                }
 7672
 7673                let indent_size = indent_size_occurrences
 7674                    .into_iter()
 7675                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7676                    .map(|(indent, _)| indent)
 7677                    .unwrap_or_default();
 7678                let row = rows_by_indent_size[&indent_size][0];
 7679                let indent_end = Point::new(row, indent_size.len);
 7680
 7681                (indent_size, indent_end)
 7682            };
 7683
 7684            let mut line_prefix = indent_size.chars().collect::<String>();
 7685
 7686            if let Some(comment_prefix) =
 7687                buffer
 7688                    .language_scope_at(selection.head())
 7689                    .and_then(|language| {
 7690                        language
 7691                            .line_comment_prefixes()
 7692                            .iter()
 7693                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7694                            .cloned()
 7695                    })
 7696            {
 7697                line_prefix.push_str(&comment_prefix);
 7698                should_rewrap = true;
 7699            }
 7700
 7701            if !should_rewrap {
 7702                continue;
 7703            }
 7704
 7705            if selection.is_empty() {
 7706                'expand_upwards: while start_row > 0 {
 7707                    let prev_row = start_row - 1;
 7708                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7709                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7710                    {
 7711                        start_row = prev_row;
 7712                    } else {
 7713                        break 'expand_upwards;
 7714                    }
 7715                }
 7716
 7717                'expand_downwards: while end_row < buffer.max_point().row {
 7718                    let next_row = end_row + 1;
 7719                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7720                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7721                    {
 7722                        end_row = next_row;
 7723                    } else {
 7724                        break 'expand_downwards;
 7725                    }
 7726                }
 7727            }
 7728
 7729            let start = Point::new(start_row, 0);
 7730            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7731            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7732            let Some(lines_without_prefixes) = selection_text
 7733                .lines()
 7734                .map(|line| {
 7735                    line.strip_prefix(&line_prefix)
 7736                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7737                        .ok_or_else(|| {
 7738                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7739                        })
 7740                })
 7741                .collect::<Result<Vec<_>, _>>()
 7742                .log_err()
 7743            else {
 7744                continue;
 7745            };
 7746
 7747            let wrap_column = buffer
 7748                .settings_at(Point::new(start_row, 0), cx)
 7749                .preferred_line_length as usize;
 7750            let wrapped_text = wrap_with_prefix(
 7751                line_prefix,
 7752                lines_without_prefixes.join(" "),
 7753                wrap_column,
 7754                tab_size,
 7755            );
 7756
 7757            // TODO: should always use char-based diff while still supporting cursor behavior that
 7758            // matches vim.
 7759            let diff = match is_vim_mode {
 7760                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7761                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7762            };
 7763            let mut offset = start.to_offset(&buffer);
 7764            let mut moved_since_edit = true;
 7765
 7766            for change in diff.iter_all_changes() {
 7767                let value = change.value();
 7768                match change.tag() {
 7769                    ChangeTag::Equal => {
 7770                        offset += value.len();
 7771                        moved_since_edit = true;
 7772                    }
 7773                    ChangeTag::Delete => {
 7774                        let start = buffer.anchor_after(offset);
 7775                        let end = buffer.anchor_before(offset + value.len());
 7776
 7777                        if moved_since_edit {
 7778                            edits.push((start..end, String::new()));
 7779                        } else {
 7780                            edits.last_mut().unwrap().0.end = end;
 7781                        }
 7782
 7783                        offset += value.len();
 7784                        moved_since_edit = false;
 7785                    }
 7786                    ChangeTag::Insert => {
 7787                        if moved_since_edit {
 7788                            let anchor = buffer.anchor_after(offset);
 7789                            edits.push((anchor..anchor, value.to_string()));
 7790                        } else {
 7791                            edits.last_mut().unwrap().1.push_str(value);
 7792                        }
 7793
 7794                        moved_since_edit = false;
 7795                    }
 7796                }
 7797            }
 7798
 7799            rewrapped_row_ranges.push(start_row..=end_row);
 7800        }
 7801
 7802        self.buffer
 7803            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7804    }
 7805
 7806    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7807        let mut text = String::new();
 7808        let buffer = self.buffer.read(cx).snapshot(cx);
 7809        let mut selections = self.selections.all::<Point>(cx);
 7810        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7811        {
 7812            let max_point = buffer.max_point();
 7813            let mut is_first = true;
 7814            for selection in &mut selections {
 7815                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7816                if is_entire_line {
 7817                    selection.start = Point::new(selection.start.row, 0);
 7818                    if !selection.is_empty() && selection.end.column == 0 {
 7819                        selection.end = cmp::min(max_point, selection.end);
 7820                    } else {
 7821                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7822                    }
 7823                    selection.goal = SelectionGoal::None;
 7824                }
 7825                if is_first {
 7826                    is_first = false;
 7827                } else {
 7828                    text += "\n";
 7829                }
 7830                let mut len = 0;
 7831                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7832                    text.push_str(chunk);
 7833                    len += chunk.len();
 7834                }
 7835                clipboard_selections.push(ClipboardSelection {
 7836                    len,
 7837                    is_entire_line,
 7838                    first_line_indent: buffer
 7839                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7840                        .len,
 7841                });
 7842            }
 7843        }
 7844
 7845        self.transact(window, cx, |this, window, cx| {
 7846            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7847                s.select(selections);
 7848            });
 7849            this.insert("", window, cx);
 7850        });
 7851        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7852    }
 7853
 7854    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7855        let item = self.cut_common(window, cx);
 7856        cx.write_to_clipboard(item);
 7857    }
 7858
 7859    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7860        self.change_selections(None, window, cx, |s| {
 7861            s.move_with(|snapshot, sel| {
 7862                if sel.is_empty() {
 7863                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7864                }
 7865            });
 7866        });
 7867        let item = self.cut_common(window, cx);
 7868        cx.set_global(KillRing(item))
 7869    }
 7870
 7871    pub fn kill_ring_yank(
 7872        &mut self,
 7873        _: &KillRingYank,
 7874        window: &mut Window,
 7875        cx: &mut Context<Self>,
 7876    ) {
 7877        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7878            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7879                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7880            } else {
 7881                return;
 7882            }
 7883        } else {
 7884            return;
 7885        };
 7886        self.do_paste(&text, metadata, false, window, cx);
 7887    }
 7888
 7889    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7890        let selections = self.selections.all::<Point>(cx);
 7891        let buffer = self.buffer.read(cx).read(cx);
 7892        let mut text = String::new();
 7893
 7894        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7895        {
 7896            let max_point = buffer.max_point();
 7897            let mut is_first = true;
 7898            for selection in selections.iter() {
 7899                let mut start = selection.start;
 7900                let mut end = selection.end;
 7901                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7902                if is_entire_line {
 7903                    start = Point::new(start.row, 0);
 7904                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7905                }
 7906                if is_first {
 7907                    is_first = false;
 7908                } else {
 7909                    text += "\n";
 7910                }
 7911                let mut len = 0;
 7912                for chunk in buffer.text_for_range(start..end) {
 7913                    text.push_str(chunk);
 7914                    len += chunk.len();
 7915                }
 7916                clipboard_selections.push(ClipboardSelection {
 7917                    len,
 7918                    is_entire_line,
 7919                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7920                });
 7921            }
 7922        }
 7923
 7924        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7925            text,
 7926            clipboard_selections,
 7927        ));
 7928    }
 7929
 7930    pub fn do_paste(
 7931        &mut self,
 7932        text: &String,
 7933        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7934        handle_entire_lines: bool,
 7935        window: &mut Window,
 7936        cx: &mut Context<Self>,
 7937    ) {
 7938        if self.read_only(cx) {
 7939            return;
 7940        }
 7941
 7942        let clipboard_text = Cow::Borrowed(text);
 7943
 7944        self.transact(window, cx, |this, window, cx| {
 7945            if let Some(mut clipboard_selections) = clipboard_selections {
 7946                let old_selections = this.selections.all::<usize>(cx);
 7947                let all_selections_were_entire_line =
 7948                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7949                let first_selection_indent_column =
 7950                    clipboard_selections.first().map(|s| s.first_line_indent);
 7951                if clipboard_selections.len() != old_selections.len() {
 7952                    clipboard_selections.drain(..);
 7953                }
 7954                let cursor_offset = this.selections.last::<usize>(cx).head();
 7955                let mut auto_indent_on_paste = true;
 7956
 7957                this.buffer.update(cx, |buffer, cx| {
 7958                    let snapshot = buffer.read(cx);
 7959                    auto_indent_on_paste =
 7960                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7961
 7962                    let mut start_offset = 0;
 7963                    let mut edits = Vec::new();
 7964                    let mut original_indent_columns = Vec::new();
 7965                    for (ix, selection) in old_selections.iter().enumerate() {
 7966                        let to_insert;
 7967                        let entire_line;
 7968                        let original_indent_column;
 7969                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7970                            let end_offset = start_offset + clipboard_selection.len;
 7971                            to_insert = &clipboard_text[start_offset..end_offset];
 7972                            entire_line = clipboard_selection.is_entire_line;
 7973                            start_offset = end_offset + 1;
 7974                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7975                        } else {
 7976                            to_insert = clipboard_text.as_str();
 7977                            entire_line = all_selections_were_entire_line;
 7978                            original_indent_column = first_selection_indent_column
 7979                        }
 7980
 7981                        // If the corresponding selection was empty when this slice of the
 7982                        // clipboard text was written, then the entire line containing the
 7983                        // selection was copied. If this selection is also currently empty,
 7984                        // then paste the line before the current line of the buffer.
 7985                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7986                            let column = selection.start.to_point(&snapshot).column as usize;
 7987                            let line_start = selection.start - column;
 7988                            line_start..line_start
 7989                        } else {
 7990                            selection.range()
 7991                        };
 7992
 7993                        edits.push((range, to_insert));
 7994                        original_indent_columns.extend(original_indent_column);
 7995                    }
 7996                    drop(snapshot);
 7997
 7998                    buffer.edit(
 7999                        edits,
 8000                        if auto_indent_on_paste {
 8001                            Some(AutoindentMode::Block {
 8002                                original_indent_columns,
 8003                            })
 8004                        } else {
 8005                            None
 8006                        },
 8007                        cx,
 8008                    );
 8009                });
 8010
 8011                let selections = this.selections.all::<usize>(cx);
 8012                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8013                    s.select(selections)
 8014                });
 8015            } else {
 8016                this.insert(&clipboard_text, window, cx);
 8017            }
 8018        });
 8019    }
 8020
 8021    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8022        if let Some(item) = cx.read_from_clipboard() {
 8023            let entries = item.entries();
 8024
 8025            match entries.first() {
 8026                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8027                // of all the pasted entries.
 8028                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8029                    .do_paste(
 8030                        clipboard_string.text(),
 8031                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8032                        true,
 8033                        window,
 8034                        cx,
 8035                    ),
 8036                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8037            }
 8038        }
 8039    }
 8040
 8041    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8042        if self.read_only(cx) {
 8043            return;
 8044        }
 8045
 8046        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8047            if let Some((selections, _)) =
 8048                self.selection_history.transaction(transaction_id).cloned()
 8049            {
 8050                self.change_selections(None, window, cx, |s| {
 8051                    s.select_anchors(selections.to_vec());
 8052                });
 8053            }
 8054            self.request_autoscroll(Autoscroll::fit(), cx);
 8055            self.unmark_text(window, cx);
 8056            self.refresh_inline_completion(true, false, window, cx);
 8057            cx.emit(EditorEvent::Edited { transaction_id });
 8058            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8059        }
 8060    }
 8061
 8062    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8063        if self.read_only(cx) {
 8064            return;
 8065        }
 8066
 8067        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8068            if let Some((_, Some(selections))) =
 8069                self.selection_history.transaction(transaction_id).cloned()
 8070            {
 8071                self.change_selections(None, window, cx, |s| {
 8072                    s.select_anchors(selections.to_vec());
 8073                });
 8074            }
 8075            self.request_autoscroll(Autoscroll::fit(), cx);
 8076            self.unmark_text(window, cx);
 8077            self.refresh_inline_completion(true, false, window, cx);
 8078            cx.emit(EditorEvent::Edited { transaction_id });
 8079        }
 8080    }
 8081
 8082    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8083        self.buffer
 8084            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8085    }
 8086
 8087    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8088        self.buffer
 8089            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8090    }
 8091
 8092    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8093        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8094            let line_mode = s.line_mode;
 8095            s.move_with(|map, selection| {
 8096                let cursor = if selection.is_empty() && !line_mode {
 8097                    movement::left(map, selection.start)
 8098                } else {
 8099                    selection.start
 8100                };
 8101                selection.collapse_to(cursor, SelectionGoal::None);
 8102            });
 8103        })
 8104    }
 8105
 8106    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8107        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8108            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8109        })
 8110    }
 8111
 8112    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8113        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8114            let line_mode = s.line_mode;
 8115            s.move_with(|map, selection| {
 8116                let cursor = if selection.is_empty() && !line_mode {
 8117                    movement::right(map, selection.end)
 8118                } else {
 8119                    selection.end
 8120                };
 8121                selection.collapse_to(cursor, SelectionGoal::None)
 8122            });
 8123        })
 8124    }
 8125
 8126    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8127        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8128            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8129        })
 8130    }
 8131
 8132    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8133        if self.take_rename(true, window, cx).is_some() {
 8134            return;
 8135        }
 8136
 8137        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8138            cx.propagate();
 8139            return;
 8140        }
 8141
 8142        let text_layout_details = &self.text_layout_details(window);
 8143        let selection_count = self.selections.count();
 8144        let first_selection = self.selections.first_anchor();
 8145
 8146        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8147            let line_mode = s.line_mode;
 8148            s.move_with(|map, selection| {
 8149                if !selection.is_empty() && !line_mode {
 8150                    selection.goal = SelectionGoal::None;
 8151                }
 8152                let (cursor, goal) = movement::up(
 8153                    map,
 8154                    selection.start,
 8155                    selection.goal,
 8156                    false,
 8157                    text_layout_details,
 8158                );
 8159                selection.collapse_to(cursor, goal);
 8160            });
 8161        });
 8162
 8163        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8164        {
 8165            cx.propagate();
 8166        }
 8167    }
 8168
 8169    pub fn move_up_by_lines(
 8170        &mut self,
 8171        action: &MoveUpByLines,
 8172        window: &mut Window,
 8173        cx: &mut Context<Self>,
 8174    ) {
 8175        if self.take_rename(true, window, cx).is_some() {
 8176            return;
 8177        }
 8178
 8179        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8180            cx.propagate();
 8181            return;
 8182        }
 8183
 8184        let text_layout_details = &self.text_layout_details(window);
 8185
 8186        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8187            let line_mode = s.line_mode;
 8188            s.move_with(|map, selection| {
 8189                if !selection.is_empty() && !line_mode {
 8190                    selection.goal = SelectionGoal::None;
 8191                }
 8192                let (cursor, goal) = movement::up_by_rows(
 8193                    map,
 8194                    selection.start,
 8195                    action.lines,
 8196                    selection.goal,
 8197                    false,
 8198                    text_layout_details,
 8199                );
 8200                selection.collapse_to(cursor, goal);
 8201            });
 8202        })
 8203    }
 8204
 8205    pub fn move_down_by_lines(
 8206        &mut self,
 8207        action: &MoveDownByLines,
 8208        window: &mut Window,
 8209        cx: &mut Context<Self>,
 8210    ) {
 8211        if self.take_rename(true, window, cx).is_some() {
 8212            return;
 8213        }
 8214
 8215        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8216            cx.propagate();
 8217            return;
 8218        }
 8219
 8220        let text_layout_details = &self.text_layout_details(window);
 8221
 8222        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8223            let line_mode = s.line_mode;
 8224            s.move_with(|map, selection| {
 8225                if !selection.is_empty() && !line_mode {
 8226                    selection.goal = SelectionGoal::None;
 8227                }
 8228                let (cursor, goal) = movement::down_by_rows(
 8229                    map,
 8230                    selection.start,
 8231                    action.lines,
 8232                    selection.goal,
 8233                    false,
 8234                    text_layout_details,
 8235                );
 8236                selection.collapse_to(cursor, goal);
 8237            });
 8238        })
 8239    }
 8240
 8241    pub fn select_down_by_lines(
 8242        &mut self,
 8243        action: &SelectDownByLines,
 8244        window: &mut Window,
 8245        cx: &mut Context<Self>,
 8246    ) {
 8247        let text_layout_details = &self.text_layout_details(window);
 8248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8249            s.move_heads_with(|map, head, goal| {
 8250                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8251            })
 8252        })
 8253    }
 8254
 8255    pub fn select_up_by_lines(
 8256        &mut self,
 8257        action: &SelectUpByLines,
 8258        window: &mut Window,
 8259        cx: &mut Context<Self>,
 8260    ) {
 8261        let text_layout_details = &self.text_layout_details(window);
 8262        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8263            s.move_heads_with(|map, head, goal| {
 8264                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8265            })
 8266        })
 8267    }
 8268
 8269    pub fn select_page_up(
 8270        &mut self,
 8271        _: &SelectPageUp,
 8272        window: &mut Window,
 8273        cx: &mut Context<Self>,
 8274    ) {
 8275        let Some(row_count) = self.visible_row_count() else {
 8276            return;
 8277        };
 8278
 8279        let text_layout_details = &self.text_layout_details(window);
 8280
 8281        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8282            s.move_heads_with(|map, head, goal| {
 8283                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8284            })
 8285        })
 8286    }
 8287
 8288    pub fn move_page_up(
 8289        &mut self,
 8290        action: &MovePageUp,
 8291        window: &mut Window,
 8292        cx: &mut Context<Self>,
 8293    ) {
 8294        if self.take_rename(true, window, cx).is_some() {
 8295            return;
 8296        }
 8297
 8298        if self
 8299            .context_menu
 8300            .borrow_mut()
 8301            .as_mut()
 8302            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8303            .unwrap_or(false)
 8304        {
 8305            return;
 8306        }
 8307
 8308        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8309            cx.propagate();
 8310            return;
 8311        }
 8312
 8313        let Some(row_count) = self.visible_row_count() else {
 8314            return;
 8315        };
 8316
 8317        let autoscroll = if action.center_cursor {
 8318            Autoscroll::center()
 8319        } else {
 8320            Autoscroll::fit()
 8321        };
 8322
 8323        let text_layout_details = &self.text_layout_details(window);
 8324
 8325        self.change_selections(Some(autoscroll), window, cx, |s| {
 8326            let line_mode = s.line_mode;
 8327            s.move_with(|map, selection| {
 8328                if !selection.is_empty() && !line_mode {
 8329                    selection.goal = SelectionGoal::None;
 8330                }
 8331                let (cursor, goal) = movement::up_by_rows(
 8332                    map,
 8333                    selection.end,
 8334                    row_count,
 8335                    selection.goal,
 8336                    false,
 8337                    text_layout_details,
 8338                );
 8339                selection.collapse_to(cursor, goal);
 8340            });
 8341        });
 8342    }
 8343
 8344    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8345        let text_layout_details = &self.text_layout_details(window);
 8346        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8347            s.move_heads_with(|map, head, goal| {
 8348                movement::up(map, head, goal, false, text_layout_details)
 8349            })
 8350        })
 8351    }
 8352
 8353    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8354        self.take_rename(true, window, cx);
 8355
 8356        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8357            cx.propagate();
 8358            return;
 8359        }
 8360
 8361        let text_layout_details = &self.text_layout_details(window);
 8362        let selection_count = self.selections.count();
 8363        let first_selection = self.selections.first_anchor();
 8364
 8365        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8366            let line_mode = s.line_mode;
 8367            s.move_with(|map, selection| {
 8368                if !selection.is_empty() && !line_mode {
 8369                    selection.goal = SelectionGoal::None;
 8370                }
 8371                let (cursor, goal) = movement::down(
 8372                    map,
 8373                    selection.end,
 8374                    selection.goal,
 8375                    false,
 8376                    text_layout_details,
 8377                );
 8378                selection.collapse_to(cursor, goal);
 8379            });
 8380        });
 8381
 8382        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8383        {
 8384            cx.propagate();
 8385        }
 8386    }
 8387
 8388    pub fn select_page_down(
 8389        &mut self,
 8390        _: &SelectPageDown,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        let Some(row_count) = self.visible_row_count() else {
 8395            return;
 8396        };
 8397
 8398        let text_layout_details = &self.text_layout_details(window);
 8399
 8400        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8401            s.move_heads_with(|map, head, goal| {
 8402                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8403            })
 8404        })
 8405    }
 8406
 8407    pub fn move_page_down(
 8408        &mut self,
 8409        action: &MovePageDown,
 8410        window: &mut Window,
 8411        cx: &mut Context<Self>,
 8412    ) {
 8413        if self.take_rename(true, window, cx).is_some() {
 8414            return;
 8415        }
 8416
 8417        if self
 8418            .context_menu
 8419            .borrow_mut()
 8420            .as_mut()
 8421            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8422            .unwrap_or(false)
 8423        {
 8424            return;
 8425        }
 8426
 8427        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8428            cx.propagate();
 8429            return;
 8430        }
 8431
 8432        let Some(row_count) = self.visible_row_count() else {
 8433            return;
 8434        };
 8435
 8436        let autoscroll = if action.center_cursor {
 8437            Autoscroll::center()
 8438        } else {
 8439            Autoscroll::fit()
 8440        };
 8441
 8442        let text_layout_details = &self.text_layout_details(window);
 8443        self.change_selections(Some(autoscroll), window, cx, |s| {
 8444            let line_mode = s.line_mode;
 8445            s.move_with(|map, selection| {
 8446                if !selection.is_empty() && !line_mode {
 8447                    selection.goal = SelectionGoal::None;
 8448                }
 8449                let (cursor, goal) = movement::down_by_rows(
 8450                    map,
 8451                    selection.end,
 8452                    row_count,
 8453                    selection.goal,
 8454                    false,
 8455                    text_layout_details,
 8456                );
 8457                selection.collapse_to(cursor, goal);
 8458            });
 8459        });
 8460    }
 8461
 8462    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8463        let text_layout_details = &self.text_layout_details(window);
 8464        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8465            s.move_heads_with(|map, head, goal| {
 8466                movement::down(map, head, goal, false, text_layout_details)
 8467            })
 8468        });
 8469    }
 8470
 8471    pub fn context_menu_first(
 8472        &mut self,
 8473        _: &ContextMenuFirst,
 8474        _window: &mut Window,
 8475        cx: &mut Context<Self>,
 8476    ) {
 8477        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8478            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8479        }
 8480    }
 8481
 8482    pub fn context_menu_prev(
 8483        &mut self,
 8484        _: &ContextMenuPrev,
 8485        _window: &mut Window,
 8486        cx: &mut Context<Self>,
 8487    ) {
 8488        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8489            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8490        }
 8491    }
 8492
 8493    pub fn context_menu_next(
 8494        &mut self,
 8495        _: &ContextMenuNext,
 8496        _window: &mut Window,
 8497        cx: &mut Context<Self>,
 8498    ) {
 8499        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8500            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8501        }
 8502    }
 8503
 8504    pub fn context_menu_last(
 8505        &mut self,
 8506        _: &ContextMenuLast,
 8507        _window: &mut Window,
 8508        cx: &mut Context<Self>,
 8509    ) {
 8510        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8511            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8512        }
 8513    }
 8514
 8515    pub fn move_to_previous_word_start(
 8516        &mut self,
 8517        _: &MoveToPreviousWordStart,
 8518        window: &mut Window,
 8519        cx: &mut Context<Self>,
 8520    ) {
 8521        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8522            s.move_cursors_with(|map, head, _| {
 8523                (
 8524                    movement::previous_word_start(map, head),
 8525                    SelectionGoal::None,
 8526                )
 8527            });
 8528        })
 8529    }
 8530
 8531    pub fn move_to_previous_subword_start(
 8532        &mut self,
 8533        _: &MoveToPreviousSubwordStart,
 8534        window: &mut Window,
 8535        cx: &mut Context<Self>,
 8536    ) {
 8537        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8538            s.move_cursors_with(|map, head, _| {
 8539                (
 8540                    movement::previous_subword_start(map, head),
 8541                    SelectionGoal::None,
 8542                )
 8543            });
 8544        })
 8545    }
 8546
 8547    pub fn select_to_previous_word_start(
 8548        &mut self,
 8549        _: &SelectToPreviousWordStart,
 8550        window: &mut Window,
 8551        cx: &mut Context<Self>,
 8552    ) {
 8553        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8554            s.move_heads_with(|map, head, _| {
 8555                (
 8556                    movement::previous_word_start(map, head),
 8557                    SelectionGoal::None,
 8558                )
 8559            });
 8560        })
 8561    }
 8562
 8563    pub fn select_to_previous_subword_start(
 8564        &mut self,
 8565        _: &SelectToPreviousSubwordStart,
 8566        window: &mut Window,
 8567        cx: &mut Context<Self>,
 8568    ) {
 8569        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8570            s.move_heads_with(|map, head, _| {
 8571                (
 8572                    movement::previous_subword_start(map, head),
 8573                    SelectionGoal::None,
 8574                )
 8575            });
 8576        })
 8577    }
 8578
 8579    pub fn delete_to_previous_word_start(
 8580        &mut self,
 8581        action: &DeleteToPreviousWordStart,
 8582        window: &mut Window,
 8583        cx: &mut Context<Self>,
 8584    ) {
 8585        self.transact(window, cx, |this, window, cx| {
 8586            this.select_autoclose_pair(window, cx);
 8587            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8588                let line_mode = s.line_mode;
 8589                s.move_with(|map, selection| {
 8590                    if selection.is_empty() && !line_mode {
 8591                        let cursor = if action.ignore_newlines {
 8592                            movement::previous_word_start(map, selection.head())
 8593                        } else {
 8594                            movement::previous_word_start_or_newline(map, selection.head())
 8595                        };
 8596                        selection.set_head(cursor, SelectionGoal::None);
 8597                    }
 8598                });
 8599            });
 8600            this.insert("", window, cx);
 8601        });
 8602    }
 8603
 8604    pub fn delete_to_previous_subword_start(
 8605        &mut self,
 8606        _: &DeleteToPreviousSubwordStart,
 8607        window: &mut Window,
 8608        cx: &mut Context<Self>,
 8609    ) {
 8610        self.transact(window, cx, |this, window, cx| {
 8611            this.select_autoclose_pair(window, cx);
 8612            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8613                let line_mode = s.line_mode;
 8614                s.move_with(|map, selection| {
 8615                    if selection.is_empty() && !line_mode {
 8616                        let cursor = movement::previous_subword_start(map, selection.head());
 8617                        selection.set_head(cursor, SelectionGoal::None);
 8618                    }
 8619                });
 8620            });
 8621            this.insert("", window, cx);
 8622        });
 8623    }
 8624
 8625    pub fn move_to_next_word_end(
 8626        &mut self,
 8627        _: &MoveToNextWordEnd,
 8628        window: &mut Window,
 8629        cx: &mut Context<Self>,
 8630    ) {
 8631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632            s.move_cursors_with(|map, head, _| {
 8633                (movement::next_word_end(map, head), SelectionGoal::None)
 8634            });
 8635        })
 8636    }
 8637
 8638    pub fn move_to_next_subword_end(
 8639        &mut self,
 8640        _: &MoveToNextSubwordEnd,
 8641        window: &mut Window,
 8642        cx: &mut Context<Self>,
 8643    ) {
 8644        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8645            s.move_cursors_with(|map, head, _| {
 8646                (movement::next_subword_end(map, head), SelectionGoal::None)
 8647            });
 8648        })
 8649    }
 8650
 8651    pub fn select_to_next_word_end(
 8652        &mut self,
 8653        _: &SelectToNextWordEnd,
 8654        window: &mut Window,
 8655        cx: &mut Context<Self>,
 8656    ) {
 8657        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8658            s.move_heads_with(|map, head, _| {
 8659                (movement::next_word_end(map, head), SelectionGoal::None)
 8660            });
 8661        })
 8662    }
 8663
 8664    pub fn select_to_next_subword_end(
 8665        &mut self,
 8666        _: &SelectToNextSubwordEnd,
 8667        window: &mut Window,
 8668        cx: &mut Context<Self>,
 8669    ) {
 8670        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8671            s.move_heads_with(|map, head, _| {
 8672                (movement::next_subword_end(map, head), SelectionGoal::None)
 8673            });
 8674        })
 8675    }
 8676
 8677    pub fn delete_to_next_word_end(
 8678        &mut self,
 8679        action: &DeleteToNextWordEnd,
 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                let line_mode = s.line_mode;
 8686                s.move_with(|map, selection| {
 8687                    if selection.is_empty() && !line_mode {
 8688                        let cursor = if action.ignore_newlines {
 8689                            movement::next_word_end(map, selection.head())
 8690                        } else {
 8691                            movement::next_word_end_or_newline(map, selection.head())
 8692                        };
 8693                        selection.set_head(cursor, SelectionGoal::None);
 8694                    }
 8695                });
 8696            });
 8697            this.insert("", window, cx);
 8698        });
 8699    }
 8700
 8701    pub fn delete_to_next_subword_end(
 8702        &mut self,
 8703        _: &DeleteToNextSubwordEnd,
 8704        window: &mut Window,
 8705        cx: &mut Context<Self>,
 8706    ) {
 8707        self.transact(window, cx, |this, window, cx| {
 8708            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8709                s.move_with(|map, selection| {
 8710                    if selection.is_empty() {
 8711                        let cursor = movement::next_subword_end(map, selection.head());
 8712                        selection.set_head(cursor, SelectionGoal::None);
 8713                    }
 8714                });
 8715            });
 8716            this.insert("", window, cx);
 8717        });
 8718    }
 8719
 8720    pub fn move_to_beginning_of_line(
 8721        &mut self,
 8722        action: &MoveToBeginningOfLine,
 8723        window: &mut Window,
 8724        cx: &mut Context<Self>,
 8725    ) {
 8726        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8727            s.move_cursors_with(|map, head, _| {
 8728                (
 8729                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8730                    SelectionGoal::None,
 8731                )
 8732            });
 8733        })
 8734    }
 8735
 8736    pub fn select_to_beginning_of_line(
 8737        &mut self,
 8738        action: &SelectToBeginningOfLine,
 8739        window: &mut Window,
 8740        cx: &mut Context<Self>,
 8741    ) {
 8742        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8743            s.move_heads_with(|map, head, _| {
 8744                (
 8745                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8746                    SelectionGoal::None,
 8747                )
 8748            });
 8749        });
 8750    }
 8751
 8752    pub fn delete_to_beginning_of_line(
 8753        &mut self,
 8754        _: &DeleteToBeginningOfLine,
 8755        window: &mut Window,
 8756        cx: &mut Context<Self>,
 8757    ) {
 8758        self.transact(window, cx, |this, window, cx| {
 8759            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8760                s.move_with(|_, selection| {
 8761                    selection.reversed = true;
 8762                });
 8763            });
 8764
 8765            this.select_to_beginning_of_line(
 8766                &SelectToBeginningOfLine {
 8767                    stop_at_soft_wraps: false,
 8768                },
 8769                window,
 8770                cx,
 8771            );
 8772            this.backspace(&Backspace, window, cx);
 8773        });
 8774    }
 8775
 8776    pub fn move_to_end_of_line(
 8777        &mut self,
 8778        action: &MoveToEndOfLine,
 8779        window: &mut Window,
 8780        cx: &mut Context<Self>,
 8781    ) {
 8782        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8783            s.move_cursors_with(|map, head, _| {
 8784                (
 8785                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8786                    SelectionGoal::None,
 8787                )
 8788            });
 8789        })
 8790    }
 8791
 8792    pub fn select_to_end_of_line(
 8793        &mut self,
 8794        action: &SelectToEndOfLine,
 8795        window: &mut Window,
 8796        cx: &mut Context<Self>,
 8797    ) {
 8798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8799            s.move_heads_with(|map, head, _| {
 8800                (
 8801                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8802                    SelectionGoal::None,
 8803                )
 8804            });
 8805        })
 8806    }
 8807
 8808    pub fn delete_to_end_of_line(
 8809        &mut self,
 8810        _: &DeleteToEndOfLine,
 8811        window: &mut Window,
 8812        cx: &mut Context<Self>,
 8813    ) {
 8814        self.transact(window, cx, |this, window, cx| {
 8815            this.select_to_end_of_line(
 8816                &SelectToEndOfLine {
 8817                    stop_at_soft_wraps: false,
 8818                },
 8819                window,
 8820                cx,
 8821            );
 8822            this.delete(&Delete, window, cx);
 8823        });
 8824    }
 8825
 8826    pub fn cut_to_end_of_line(
 8827        &mut self,
 8828        _: &CutToEndOfLine,
 8829        window: &mut Window,
 8830        cx: &mut Context<Self>,
 8831    ) {
 8832        self.transact(window, cx, |this, window, cx| {
 8833            this.select_to_end_of_line(
 8834                &SelectToEndOfLine {
 8835                    stop_at_soft_wraps: false,
 8836                },
 8837                window,
 8838                cx,
 8839            );
 8840            this.cut(&Cut, window, cx);
 8841        });
 8842    }
 8843
 8844    pub fn move_to_start_of_paragraph(
 8845        &mut self,
 8846        _: &MoveToStartOfParagraph,
 8847        window: &mut Window,
 8848        cx: &mut Context<Self>,
 8849    ) {
 8850        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8851            cx.propagate();
 8852            return;
 8853        }
 8854
 8855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8856            s.move_with(|map, selection| {
 8857                selection.collapse_to(
 8858                    movement::start_of_paragraph(map, selection.head(), 1),
 8859                    SelectionGoal::None,
 8860                )
 8861            });
 8862        })
 8863    }
 8864
 8865    pub fn move_to_end_of_paragraph(
 8866        &mut self,
 8867        _: &MoveToEndOfParagraph,
 8868        window: &mut Window,
 8869        cx: &mut Context<Self>,
 8870    ) {
 8871        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8872            cx.propagate();
 8873            return;
 8874        }
 8875
 8876        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8877            s.move_with(|map, selection| {
 8878                selection.collapse_to(
 8879                    movement::end_of_paragraph(map, selection.head(), 1),
 8880                    SelectionGoal::None,
 8881                )
 8882            });
 8883        })
 8884    }
 8885
 8886    pub fn select_to_start_of_paragraph(
 8887        &mut self,
 8888        _: &SelectToStartOfParagraph,
 8889        window: &mut Window,
 8890        cx: &mut Context<Self>,
 8891    ) {
 8892        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8893            cx.propagate();
 8894            return;
 8895        }
 8896
 8897        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8898            s.move_heads_with(|map, head, _| {
 8899                (
 8900                    movement::start_of_paragraph(map, head, 1),
 8901                    SelectionGoal::None,
 8902                )
 8903            });
 8904        })
 8905    }
 8906
 8907    pub fn select_to_end_of_paragraph(
 8908        &mut self,
 8909        _: &SelectToEndOfParagraph,
 8910        window: &mut Window,
 8911        cx: &mut Context<Self>,
 8912    ) {
 8913        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8914            cx.propagate();
 8915            return;
 8916        }
 8917
 8918        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8919            s.move_heads_with(|map, head, _| {
 8920                (
 8921                    movement::end_of_paragraph(map, head, 1),
 8922                    SelectionGoal::None,
 8923                )
 8924            });
 8925        })
 8926    }
 8927
 8928    pub fn move_to_beginning(
 8929        &mut self,
 8930        _: &MoveToBeginning,
 8931        window: &mut Window,
 8932        cx: &mut Context<Self>,
 8933    ) {
 8934        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8935            cx.propagate();
 8936            return;
 8937        }
 8938
 8939        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8940            s.select_ranges(vec![0..0]);
 8941        });
 8942    }
 8943
 8944    pub fn select_to_beginning(
 8945        &mut self,
 8946        _: &SelectToBeginning,
 8947        window: &mut Window,
 8948        cx: &mut Context<Self>,
 8949    ) {
 8950        let mut selection = self.selections.last::<Point>(cx);
 8951        selection.set_head(Point::zero(), SelectionGoal::None);
 8952
 8953        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8954            s.select(vec![selection]);
 8955        });
 8956    }
 8957
 8958    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8959        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8960            cx.propagate();
 8961            return;
 8962        }
 8963
 8964        let cursor = self.buffer.read(cx).read(cx).len();
 8965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8966            s.select_ranges(vec![cursor..cursor])
 8967        });
 8968    }
 8969
 8970    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8971        self.nav_history = nav_history;
 8972    }
 8973
 8974    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8975        self.nav_history.as_ref()
 8976    }
 8977
 8978    fn push_to_nav_history(
 8979        &mut self,
 8980        cursor_anchor: Anchor,
 8981        new_position: Option<Point>,
 8982        cx: &mut Context<Self>,
 8983    ) {
 8984        if let Some(nav_history) = self.nav_history.as_mut() {
 8985            let buffer = self.buffer.read(cx).read(cx);
 8986            let cursor_position = cursor_anchor.to_point(&buffer);
 8987            let scroll_state = self.scroll_manager.anchor();
 8988            let scroll_top_row = scroll_state.top_row(&buffer);
 8989            drop(buffer);
 8990
 8991            if let Some(new_position) = new_position {
 8992                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8993                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8994                    return;
 8995                }
 8996            }
 8997
 8998            nav_history.push(
 8999                Some(NavigationData {
 9000                    cursor_anchor,
 9001                    cursor_position,
 9002                    scroll_anchor: scroll_state,
 9003                    scroll_top_row,
 9004                }),
 9005                cx,
 9006            );
 9007        }
 9008    }
 9009
 9010    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9011        let buffer = self.buffer.read(cx).snapshot(cx);
 9012        let mut selection = self.selections.first::<usize>(cx);
 9013        selection.set_head(buffer.len(), SelectionGoal::None);
 9014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9015            s.select(vec![selection]);
 9016        });
 9017    }
 9018
 9019    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9020        let end = self.buffer.read(cx).read(cx).len();
 9021        self.change_selections(None, window, cx, |s| {
 9022            s.select_ranges(vec![0..end]);
 9023        });
 9024    }
 9025
 9026    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9027        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9028        let mut selections = self.selections.all::<Point>(cx);
 9029        let max_point = display_map.buffer_snapshot.max_point();
 9030        for selection in &mut selections {
 9031            let rows = selection.spanned_rows(true, &display_map);
 9032            selection.start = Point::new(rows.start.0, 0);
 9033            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9034            selection.reversed = false;
 9035        }
 9036        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9037            s.select(selections);
 9038        });
 9039    }
 9040
 9041    pub fn split_selection_into_lines(
 9042        &mut self,
 9043        _: &SplitSelectionIntoLines,
 9044        window: &mut Window,
 9045        cx: &mut Context<Self>,
 9046    ) {
 9047        let mut to_unfold = Vec::new();
 9048        let mut new_selection_ranges = Vec::new();
 9049        {
 9050            let selections = self.selections.all::<Point>(cx);
 9051            let buffer = self.buffer.read(cx).read(cx);
 9052            for selection in selections {
 9053                for row in selection.start.row..selection.end.row {
 9054                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9055                    new_selection_ranges.push(cursor..cursor);
 9056                }
 9057                new_selection_ranges.push(selection.end..selection.end);
 9058                to_unfold.push(selection.start..selection.end);
 9059            }
 9060        }
 9061        self.unfold_ranges(&to_unfold, true, true, cx);
 9062        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9063            s.select_ranges(new_selection_ranges);
 9064        });
 9065    }
 9066
 9067    pub fn add_selection_above(
 9068        &mut self,
 9069        _: &AddSelectionAbove,
 9070        window: &mut Window,
 9071        cx: &mut Context<Self>,
 9072    ) {
 9073        self.add_selection(true, window, cx);
 9074    }
 9075
 9076    pub fn add_selection_below(
 9077        &mut self,
 9078        _: &AddSelectionBelow,
 9079        window: &mut Window,
 9080        cx: &mut Context<Self>,
 9081    ) {
 9082        self.add_selection(false, window, cx);
 9083    }
 9084
 9085    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9086        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9087        let mut selections = self.selections.all::<Point>(cx);
 9088        let text_layout_details = self.text_layout_details(window);
 9089        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9090            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9091            let range = oldest_selection.display_range(&display_map).sorted();
 9092
 9093            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9094            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9095            let positions = start_x.min(end_x)..start_x.max(end_x);
 9096
 9097            selections.clear();
 9098            let mut stack = Vec::new();
 9099            for row in range.start.row().0..=range.end.row().0 {
 9100                if let Some(selection) = self.selections.build_columnar_selection(
 9101                    &display_map,
 9102                    DisplayRow(row),
 9103                    &positions,
 9104                    oldest_selection.reversed,
 9105                    &text_layout_details,
 9106                ) {
 9107                    stack.push(selection.id);
 9108                    selections.push(selection);
 9109                }
 9110            }
 9111
 9112            if above {
 9113                stack.reverse();
 9114            }
 9115
 9116            AddSelectionsState { above, stack }
 9117        });
 9118
 9119        let last_added_selection = *state.stack.last().unwrap();
 9120        let mut new_selections = Vec::new();
 9121        if above == state.above {
 9122            let end_row = if above {
 9123                DisplayRow(0)
 9124            } else {
 9125                display_map.max_point().row()
 9126            };
 9127
 9128            'outer: for selection in selections {
 9129                if selection.id == last_added_selection {
 9130                    let range = selection.display_range(&display_map).sorted();
 9131                    debug_assert_eq!(range.start.row(), range.end.row());
 9132                    let mut row = range.start.row();
 9133                    let positions =
 9134                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9135                            px(start)..px(end)
 9136                        } else {
 9137                            let start_x =
 9138                                display_map.x_for_display_point(range.start, &text_layout_details);
 9139                            let end_x =
 9140                                display_map.x_for_display_point(range.end, &text_layout_details);
 9141                            start_x.min(end_x)..start_x.max(end_x)
 9142                        };
 9143
 9144                    while row != end_row {
 9145                        if above {
 9146                            row.0 -= 1;
 9147                        } else {
 9148                            row.0 += 1;
 9149                        }
 9150
 9151                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9152                            &display_map,
 9153                            row,
 9154                            &positions,
 9155                            selection.reversed,
 9156                            &text_layout_details,
 9157                        ) {
 9158                            state.stack.push(new_selection.id);
 9159                            if above {
 9160                                new_selections.push(new_selection);
 9161                                new_selections.push(selection);
 9162                            } else {
 9163                                new_selections.push(selection);
 9164                                new_selections.push(new_selection);
 9165                            }
 9166
 9167                            continue 'outer;
 9168                        }
 9169                    }
 9170                }
 9171
 9172                new_selections.push(selection);
 9173            }
 9174        } else {
 9175            new_selections = selections;
 9176            new_selections.retain(|s| s.id != last_added_selection);
 9177            state.stack.pop();
 9178        }
 9179
 9180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9181            s.select(new_selections);
 9182        });
 9183        if state.stack.len() > 1 {
 9184            self.add_selections_state = Some(state);
 9185        }
 9186    }
 9187
 9188    pub fn select_next_match_internal(
 9189        &mut self,
 9190        display_map: &DisplaySnapshot,
 9191        replace_newest: bool,
 9192        autoscroll: Option<Autoscroll>,
 9193        window: &mut Window,
 9194        cx: &mut Context<Self>,
 9195    ) -> Result<()> {
 9196        fn select_next_match_ranges(
 9197            this: &mut Editor,
 9198            range: Range<usize>,
 9199            replace_newest: bool,
 9200            auto_scroll: Option<Autoscroll>,
 9201            window: &mut Window,
 9202            cx: &mut Context<Editor>,
 9203        ) {
 9204            this.unfold_ranges(&[range.clone()], false, true, cx);
 9205            this.change_selections(auto_scroll, window, cx, |s| {
 9206                if replace_newest {
 9207                    s.delete(s.newest_anchor().id);
 9208                }
 9209                s.insert_range(range.clone());
 9210            });
 9211        }
 9212
 9213        let buffer = &display_map.buffer_snapshot;
 9214        let mut selections = self.selections.all::<usize>(cx);
 9215        if let Some(mut select_next_state) = self.select_next_state.take() {
 9216            let query = &select_next_state.query;
 9217            if !select_next_state.done {
 9218                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9219                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9220                let mut next_selected_range = None;
 9221
 9222                let bytes_after_last_selection =
 9223                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9224                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9225                let query_matches = query
 9226                    .stream_find_iter(bytes_after_last_selection)
 9227                    .map(|result| (last_selection.end, result))
 9228                    .chain(
 9229                        query
 9230                            .stream_find_iter(bytes_before_first_selection)
 9231                            .map(|result| (0, result)),
 9232                    );
 9233
 9234                for (start_offset, query_match) in query_matches {
 9235                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9236                    let offset_range =
 9237                        start_offset + query_match.start()..start_offset + query_match.end();
 9238                    let display_range = offset_range.start.to_display_point(display_map)
 9239                        ..offset_range.end.to_display_point(display_map);
 9240
 9241                    if !select_next_state.wordwise
 9242                        || (!movement::is_inside_word(display_map, display_range.start)
 9243                            && !movement::is_inside_word(display_map, display_range.end))
 9244                    {
 9245                        // TODO: This is n^2, because we might check all the selections
 9246                        if !selections
 9247                            .iter()
 9248                            .any(|selection| selection.range().overlaps(&offset_range))
 9249                        {
 9250                            next_selected_range = Some(offset_range);
 9251                            break;
 9252                        }
 9253                    }
 9254                }
 9255
 9256                if let Some(next_selected_range) = next_selected_range {
 9257                    select_next_match_ranges(
 9258                        self,
 9259                        next_selected_range,
 9260                        replace_newest,
 9261                        autoscroll,
 9262                        window,
 9263                        cx,
 9264                    );
 9265                } else {
 9266                    select_next_state.done = true;
 9267                }
 9268            }
 9269
 9270            self.select_next_state = Some(select_next_state);
 9271        } else {
 9272            let mut only_carets = true;
 9273            let mut same_text_selected = true;
 9274            let mut selected_text = None;
 9275
 9276            let mut selections_iter = selections.iter().peekable();
 9277            while let Some(selection) = selections_iter.next() {
 9278                if selection.start != selection.end {
 9279                    only_carets = false;
 9280                }
 9281
 9282                if same_text_selected {
 9283                    if selected_text.is_none() {
 9284                        selected_text =
 9285                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9286                    }
 9287
 9288                    if let Some(next_selection) = selections_iter.peek() {
 9289                        if next_selection.range().len() == selection.range().len() {
 9290                            let next_selected_text = buffer
 9291                                .text_for_range(next_selection.range())
 9292                                .collect::<String>();
 9293                            if Some(next_selected_text) != selected_text {
 9294                                same_text_selected = false;
 9295                                selected_text = None;
 9296                            }
 9297                        } else {
 9298                            same_text_selected = false;
 9299                            selected_text = None;
 9300                        }
 9301                    }
 9302                }
 9303            }
 9304
 9305            if only_carets {
 9306                for selection in &mut selections {
 9307                    let word_range = movement::surrounding_word(
 9308                        display_map,
 9309                        selection.start.to_display_point(display_map),
 9310                    );
 9311                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9312                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9313                    selection.goal = SelectionGoal::None;
 9314                    selection.reversed = false;
 9315                    select_next_match_ranges(
 9316                        self,
 9317                        selection.start..selection.end,
 9318                        replace_newest,
 9319                        autoscroll,
 9320                        window,
 9321                        cx,
 9322                    );
 9323                }
 9324
 9325                if selections.len() == 1 {
 9326                    let selection = selections
 9327                        .last()
 9328                        .expect("ensured that there's only one selection");
 9329                    let query = buffer
 9330                        .text_for_range(selection.start..selection.end)
 9331                        .collect::<String>();
 9332                    let is_empty = query.is_empty();
 9333                    let select_state = SelectNextState {
 9334                        query: AhoCorasick::new(&[query])?,
 9335                        wordwise: true,
 9336                        done: is_empty,
 9337                    };
 9338                    self.select_next_state = Some(select_state);
 9339                } else {
 9340                    self.select_next_state = None;
 9341                }
 9342            } else if let Some(selected_text) = selected_text {
 9343                self.select_next_state = Some(SelectNextState {
 9344                    query: AhoCorasick::new(&[selected_text])?,
 9345                    wordwise: false,
 9346                    done: false,
 9347                });
 9348                self.select_next_match_internal(
 9349                    display_map,
 9350                    replace_newest,
 9351                    autoscroll,
 9352                    window,
 9353                    cx,
 9354                )?;
 9355            }
 9356        }
 9357        Ok(())
 9358    }
 9359
 9360    pub fn select_all_matches(
 9361        &mut self,
 9362        _action: &SelectAllMatches,
 9363        window: &mut Window,
 9364        cx: &mut Context<Self>,
 9365    ) -> Result<()> {
 9366        self.push_to_selection_history();
 9367        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9368
 9369        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9370        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9371            return Ok(());
 9372        };
 9373        if select_next_state.done {
 9374            return Ok(());
 9375        }
 9376
 9377        let mut new_selections = self.selections.all::<usize>(cx);
 9378
 9379        let buffer = &display_map.buffer_snapshot;
 9380        let query_matches = select_next_state
 9381            .query
 9382            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9383
 9384        for query_match in query_matches {
 9385            let query_match = query_match.unwrap(); // can only fail due to I/O
 9386            let offset_range = query_match.start()..query_match.end();
 9387            let display_range = offset_range.start.to_display_point(&display_map)
 9388                ..offset_range.end.to_display_point(&display_map);
 9389
 9390            if !select_next_state.wordwise
 9391                || (!movement::is_inside_word(&display_map, display_range.start)
 9392                    && !movement::is_inside_word(&display_map, display_range.end))
 9393            {
 9394                self.selections.change_with(cx, |selections| {
 9395                    new_selections.push(Selection {
 9396                        id: selections.new_selection_id(),
 9397                        start: offset_range.start,
 9398                        end: offset_range.end,
 9399                        reversed: false,
 9400                        goal: SelectionGoal::None,
 9401                    });
 9402                });
 9403            }
 9404        }
 9405
 9406        new_selections.sort_by_key(|selection| selection.start);
 9407        let mut ix = 0;
 9408        while ix + 1 < new_selections.len() {
 9409            let current_selection = &new_selections[ix];
 9410            let next_selection = &new_selections[ix + 1];
 9411            if current_selection.range().overlaps(&next_selection.range()) {
 9412                if current_selection.id < next_selection.id {
 9413                    new_selections.remove(ix + 1);
 9414                } else {
 9415                    new_selections.remove(ix);
 9416                }
 9417            } else {
 9418                ix += 1;
 9419            }
 9420        }
 9421
 9422        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9423
 9424        for selection in new_selections.iter_mut() {
 9425            selection.reversed = reversed;
 9426        }
 9427
 9428        select_next_state.done = true;
 9429        self.unfold_ranges(
 9430            &new_selections
 9431                .iter()
 9432                .map(|selection| selection.range())
 9433                .collect::<Vec<_>>(),
 9434            false,
 9435            false,
 9436            cx,
 9437        );
 9438        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9439            selections.select(new_selections)
 9440        });
 9441
 9442        Ok(())
 9443    }
 9444
 9445    pub fn select_next(
 9446        &mut self,
 9447        action: &SelectNext,
 9448        window: &mut Window,
 9449        cx: &mut Context<Self>,
 9450    ) -> Result<()> {
 9451        self.push_to_selection_history();
 9452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9453        self.select_next_match_internal(
 9454            &display_map,
 9455            action.replace_newest,
 9456            Some(Autoscroll::newest()),
 9457            window,
 9458            cx,
 9459        )?;
 9460        Ok(())
 9461    }
 9462
 9463    pub fn select_previous(
 9464        &mut self,
 9465        action: &SelectPrevious,
 9466        window: &mut Window,
 9467        cx: &mut Context<Self>,
 9468    ) -> Result<()> {
 9469        self.push_to_selection_history();
 9470        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9471        let buffer = &display_map.buffer_snapshot;
 9472        let mut selections = self.selections.all::<usize>(cx);
 9473        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9474            let query = &select_prev_state.query;
 9475            if !select_prev_state.done {
 9476                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9477                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9478                let mut next_selected_range = None;
 9479                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9480                let bytes_before_last_selection =
 9481                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9482                let bytes_after_first_selection =
 9483                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9484                let query_matches = query
 9485                    .stream_find_iter(bytes_before_last_selection)
 9486                    .map(|result| (last_selection.start, result))
 9487                    .chain(
 9488                        query
 9489                            .stream_find_iter(bytes_after_first_selection)
 9490                            .map(|result| (buffer.len(), result)),
 9491                    );
 9492                for (end_offset, query_match) in query_matches {
 9493                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9494                    let offset_range =
 9495                        end_offset - query_match.end()..end_offset - query_match.start();
 9496                    let display_range = offset_range.start.to_display_point(&display_map)
 9497                        ..offset_range.end.to_display_point(&display_map);
 9498
 9499                    if !select_prev_state.wordwise
 9500                        || (!movement::is_inside_word(&display_map, display_range.start)
 9501                            && !movement::is_inside_word(&display_map, display_range.end))
 9502                    {
 9503                        next_selected_range = Some(offset_range);
 9504                        break;
 9505                    }
 9506                }
 9507
 9508                if let Some(next_selected_range) = next_selected_range {
 9509                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9510                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9511                        if action.replace_newest {
 9512                            s.delete(s.newest_anchor().id);
 9513                        }
 9514                        s.insert_range(next_selected_range);
 9515                    });
 9516                } else {
 9517                    select_prev_state.done = true;
 9518                }
 9519            }
 9520
 9521            self.select_prev_state = Some(select_prev_state);
 9522        } else {
 9523            let mut only_carets = true;
 9524            let mut same_text_selected = true;
 9525            let mut selected_text = None;
 9526
 9527            let mut selections_iter = selections.iter().peekable();
 9528            while let Some(selection) = selections_iter.next() {
 9529                if selection.start != selection.end {
 9530                    only_carets = false;
 9531                }
 9532
 9533                if same_text_selected {
 9534                    if selected_text.is_none() {
 9535                        selected_text =
 9536                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9537                    }
 9538
 9539                    if let Some(next_selection) = selections_iter.peek() {
 9540                        if next_selection.range().len() == selection.range().len() {
 9541                            let next_selected_text = buffer
 9542                                .text_for_range(next_selection.range())
 9543                                .collect::<String>();
 9544                            if Some(next_selected_text) != selected_text {
 9545                                same_text_selected = false;
 9546                                selected_text = None;
 9547                            }
 9548                        } else {
 9549                            same_text_selected = false;
 9550                            selected_text = None;
 9551                        }
 9552                    }
 9553                }
 9554            }
 9555
 9556            if only_carets {
 9557                for selection in &mut selections {
 9558                    let word_range = movement::surrounding_word(
 9559                        &display_map,
 9560                        selection.start.to_display_point(&display_map),
 9561                    );
 9562                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9563                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9564                    selection.goal = SelectionGoal::None;
 9565                    selection.reversed = false;
 9566                }
 9567                if selections.len() == 1 {
 9568                    let selection = selections
 9569                        .last()
 9570                        .expect("ensured that there's only one selection");
 9571                    let query = buffer
 9572                        .text_for_range(selection.start..selection.end)
 9573                        .collect::<String>();
 9574                    let is_empty = query.is_empty();
 9575                    let select_state = SelectNextState {
 9576                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9577                        wordwise: true,
 9578                        done: is_empty,
 9579                    };
 9580                    self.select_prev_state = Some(select_state);
 9581                } else {
 9582                    self.select_prev_state = None;
 9583                }
 9584
 9585                self.unfold_ranges(
 9586                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9587                    false,
 9588                    true,
 9589                    cx,
 9590                );
 9591                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9592                    s.select(selections);
 9593                });
 9594            } else if let Some(selected_text) = selected_text {
 9595                self.select_prev_state = Some(SelectNextState {
 9596                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9597                    wordwise: false,
 9598                    done: false,
 9599                });
 9600                self.select_previous(action, window, cx)?;
 9601            }
 9602        }
 9603        Ok(())
 9604    }
 9605
 9606    pub fn toggle_comments(
 9607        &mut self,
 9608        action: &ToggleComments,
 9609        window: &mut Window,
 9610        cx: &mut Context<Self>,
 9611    ) {
 9612        if self.read_only(cx) {
 9613            return;
 9614        }
 9615        let text_layout_details = &self.text_layout_details(window);
 9616        self.transact(window, cx, |this, window, cx| {
 9617            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9618            let mut edits = Vec::new();
 9619            let mut selection_edit_ranges = Vec::new();
 9620            let mut last_toggled_row = None;
 9621            let snapshot = this.buffer.read(cx).read(cx);
 9622            let empty_str: Arc<str> = Arc::default();
 9623            let mut suffixes_inserted = Vec::new();
 9624            let ignore_indent = action.ignore_indent;
 9625
 9626            fn comment_prefix_range(
 9627                snapshot: &MultiBufferSnapshot,
 9628                row: MultiBufferRow,
 9629                comment_prefix: &str,
 9630                comment_prefix_whitespace: &str,
 9631                ignore_indent: bool,
 9632            ) -> Range<Point> {
 9633                let indent_size = if ignore_indent {
 9634                    0
 9635                } else {
 9636                    snapshot.indent_size_for_line(row).len
 9637                };
 9638
 9639                let start = Point::new(row.0, indent_size);
 9640
 9641                let mut line_bytes = snapshot
 9642                    .bytes_in_range(start..snapshot.max_point())
 9643                    .flatten()
 9644                    .copied();
 9645
 9646                // If this line currently begins with the line comment prefix, then record
 9647                // the range containing the prefix.
 9648                if line_bytes
 9649                    .by_ref()
 9650                    .take(comment_prefix.len())
 9651                    .eq(comment_prefix.bytes())
 9652                {
 9653                    // Include any whitespace that matches the comment prefix.
 9654                    let matching_whitespace_len = line_bytes
 9655                        .zip(comment_prefix_whitespace.bytes())
 9656                        .take_while(|(a, b)| a == b)
 9657                        .count() as u32;
 9658                    let end = Point::new(
 9659                        start.row,
 9660                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9661                    );
 9662                    start..end
 9663                } else {
 9664                    start..start
 9665                }
 9666            }
 9667
 9668            fn comment_suffix_range(
 9669                snapshot: &MultiBufferSnapshot,
 9670                row: MultiBufferRow,
 9671                comment_suffix: &str,
 9672                comment_suffix_has_leading_space: bool,
 9673            ) -> Range<Point> {
 9674                let end = Point::new(row.0, snapshot.line_len(row));
 9675                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9676
 9677                let mut line_end_bytes = snapshot
 9678                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9679                    .flatten()
 9680                    .copied();
 9681
 9682                let leading_space_len = if suffix_start_column > 0
 9683                    && line_end_bytes.next() == Some(b' ')
 9684                    && comment_suffix_has_leading_space
 9685                {
 9686                    1
 9687                } else {
 9688                    0
 9689                };
 9690
 9691                // If this line currently begins with the line comment prefix, then record
 9692                // the range containing the prefix.
 9693                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9694                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9695                    start..end
 9696                } else {
 9697                    end..end
 9698                }
 9699            }
 9700
 9701            // TODO: Handle selections that cross excerpts
 9702            for selection in &mut selections {
 9703                let start_column = snapshot
 9704                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9705                    .len;
 9706                let language = if let Some(language) =
 9707                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9708                {
 9709                    language
 9710                } else {
 9711                    continue;
 9712                };
 9713
 9714                selection_edit_ranges.clear();
 9715
 9716                // If multiple selections contain a given row, avoid processing that
 9717                // row more than once.
 9718                let mut start_row = MultiBufferRow(selection.start.row);
 9719                if last_toggled_row == Some(start_row) {
 9720                    start_row = start_row.next_row();
 9721                }
 9722                let end_row =
 9723                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9724                        MultiBufferRow(selection.end.row - 1)
 9725                    } else {
 9726                        MultiBufferRow(selection.end.row)
 9727                    };
 9728                last_toggled_row = Some(end_row);
 9729
 9730                if start_row > end_row {
 9731                    continue;
 9732                }
 9733
 9734                // If the language has line comments, toggle those.
 9735                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9736
 9737                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9738                if ignore_indent {
 9739                    full_comment_prefixes = full_comment_prefixes
 9740                        .into_iter()
 9741                        .map(|s| Arc::from(s.trim_end()))
 9742                        .collect();
 9743                }
 9744
 9745                if !full_comment_prefixes.is_empty() {
 9746                    let first_prefix = full_comment_prefixes
 9747                        .first()
 9748                        .expect("prefixes is non-empty");
 9749                    let prefix_trimmed_lengths = full_comment_prefixes
 9750                        .iter()
 9751                        .map(|p| p.trim_end_matches(' ').len())
 9752                        .collect::<SmallVec<[usize; 4]>>();
 9753
 9754                    let mut all_selection_lines_are_comments = true;
 9755
 9756                    for row in start_row.0..=end_row.0 {
 9757                        let row = MultiBufferRow(row);
 9758                        if start_row < end_row && snapshot.is_line_blank(row) {
 9759                            continue;
 9760                        }
 9761
 9762                        let prefix_range = full_comment_prefixes
 9763                            .iter()
 9764                            .zip(prefix_trimmed_lengths.iter().copied())
 9765                            .map(|(prefix, trimmed_prefix_len)| {
 9766                                comment_prefix_range(
 9767                                    snapshot.deref(),
 9768                                    row,
 9769                                    &prefix[..trimmed_prefix_len],
 9770                                    &prefix[trimmed_prefix_len..],
 9771                                    ignore_indent,
 9772                                )
 9773                            })
 9774                            .max_by_key(|range| range.end.column - range.start.column)
 9775                            .expect("prefixes is non-empty");
 9776
 9777                        if prefix_range.is_empty() {
 9778                            all_selection_lines_are_comments = false;
 9779                        }
 9780
 9781                        selection_edit_ranges.push(prefix_range);
 9782                    }
 9783
 9784                    if all_selection_lines_are_comments {
 9785                        edits.extend(
 9786                            selection_edit_ranges
 9787                                .iter()
 9788                                .cloned()
 9789                                .map(|range| (range, empty_str.clone())),
 9790                        );
 9791                    } else {
 9792                        let min_column = selection_edit_ranges
 9793                            .iter()
 9794                            .map(|range| range.start.column)
 9795                            .min()
 9796                            .unwrap_or(0);
 9797                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9798                            let position = Point::new(range.start.row, min_column);
 9799                            (position..position, first_prefix.clone())
 9800                        }));
 9801                    }
 9802                } else if let Some((full_comment_prefix, comment_suffix)) =
 9803                    language.block_comment_delimiters()
 9804                {
 9805                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9806                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9807                    let prefix_range = comment_prefix_range(
 9808                        snapshot.deref(),
 9809                        start_row,
 9810                        comment_prefix,
 9811                        comment_prefix_whitespace,
 9812                        ignore_indent,
 9813                    );
 9814                    let suffix_range = comment_suffix_range(
 9815                        snapshot.deref(),
 9816                        end_row,
 9817                        comment_suffix.trim_start_matches(' '),
 9818                        comment_suffix.starts_with(' '),
 9819                    );
 9820
 9821                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9822                        edits.push((
 9823                            prefix_range.start..prefix_range.start,
 9824                            full_comment_prefix.clone(),
 9825                        ));
 9826                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9827                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9828                    } else {
 9829                        edits.push((prefix_range, empty_str.clone()));
 9830                        edits.push((suffix_range, empty_str.clone()));
 9831                    }
 9832                } else {
 9833                    continue;
 9834                }
 9835            }
 9836
 9837            drop(snapshot);
 9838            this.buffer.update(cx, |buffer, cx| {
 9839                buffer.edit(edits, None, cx);
 9840            });
 9841
 9842            // Adjust selections so that they end before any comment suffixes that
 9843            // were inserted.
 9844            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9845            let mut selections = this.selections.all::<Point>(cx);
 9846            let snapshot = this.buffer.read(cx).read(cx);
 9847            for selection in &mut selections {
 9848                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9849                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9850                        Ordering::Less => {
 9851                            suffixes_inserted.next();
 9852                            continue;
 9853                        }
 9854                        Ordering::Greater => break,
 9855                        Ordering::Equal => {
 9856                            if selection.end.column == snapshot.line_len(row) {
 9857                                if selection.is_empty() {
 9858                                    selection.start.column -= suffix_len as u32;
 9859                                }
 9860                                selection.end.column -= suffix_len as u32;
 9861                            }
 9862                            break;
 9863                        }
 9864                    }
 9865                }
 9866            }
 9867
 9868            drop(snapshot);
 9869            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9870                s.select(selections)
 9871            });
 9872
 9873            let selections = this.selections.all::<Point>(cx);
 9874            let selections_on_single_row = selections.windows(2).all(|selections| {
 9875                selections[0].start.row == selections[1].start.row
 9876                    && selections[0].end.row == selections[1].end.row
 9877                    && selections[0].start.row == selections[0].end.row
 9878            });
 9879            let selections_selecting = selections
 9880                .iter()
 9881                .any(|selection| selection.start != selection.end);
 9882            let advance_downwards = action.advance_downwards
 9883                && selections_on_single_row
 9884                && !selections_selecting
 9885                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9886
 9887            if advance_downwards {
 9888                let snapshot = this.buffer.read(cx).snapshot(cx);
 9889
 9890                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9891                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9892                        let mut point = display_point.to_point(display_snapshot);
 9893                        point.row += 1;
 9894                        point = snapshot.clip_point(point, Bias::Left);
 9895                        let display_point = point.to_display_point(display_snapshot);
 9896                        let goal = SelectionGoal::HorizontalPosition(
 9897                            display_snapshot
 9898                                .x_for_display_point(display_point, text_layout_details)
 9899                                .into(),
 9900                        );
 9901                        (display_point, goal)
 9902                    })
 9903                });
 9904            }
 9905        });
 9906    }
 9907
 9908    pub fn select_enclosing_symbol(
 9909        &mut self,
 9910        _: &SelectEnclosingSymbol,
 9911        window: &mut Window,
 9912        cx: &mut Context<Self>,
 9913    ) {
 9914        let buffer = self.buffer.read(cx).snapshot(cx);
 9915        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9916
 9917        fn update_selection(
 9918            selection: &Selection<usize>,
 9919            buffer_snap: &MultiBufferSnapshot,
 9920        ) -> Option<Selection<usize>> {
 9921            let cursor = selection.head();
 9922            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9923            for symbol in symbols.iter().rev() {
 9924                let start = symbol.range.start.to_offset(buffer_snap);
 9925                let end = symbol.range.end.to_offset(buffer_snap);
 9926                let new_range = start..end;
 9927                if start < selection.start || end > selection.end {
 9928                    return Some(Selection {
 9929                        id: selection.id,
 9930                        start: new_range.start,
 9931                        end: new_range.end,
 9932                        goal: SelectionGoal::None,
 9933                        reversed: selection.reversed,
 9934                    });
 9935                }
 9936            }
 9937            None
 9938        }
 9939
 9940        let mut selected_larger_symbol = false;
 9941        let new_selections = old_selections
 9942            .iter()
 9943            .map(|selection| match update_selection(selection, &buffer) {
 9944                Some(new_selection) => {
 9945                    if new_selection.range() != selection.range() {
 9946                        selected_larger_symbol = true;
 9947                    }
 9948                    new_selection
 9949                }
 9950                None => selection.clone(),
 9951            })
 9952            .collect::<Vec<_>>();
 9953
 9954        if selected_larger_symbol {
 9955            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9956                s.select(new_selections);
 9957            });
 9958        }
 9959    }
 9960
 9961    pub fn select_larger_syntax_node(
 9962        &mut self,
 9963        _: &SelectLargerSyntaxNode,
 9964        window: &mut Window,
 9965        cx: &mut Context<Self>,
 9966    ) {
 9967        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9968        let buffer = self.buffer.read(cx).snapshot(cx);
 9969        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9970
 9971        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9972        let mut selected_larger_node = false;
 9973        let new_selections = old_selections
 9974            .iter()
 9975            .map(|selection| {
 9976                let old_range = selection.start..selection.end;
 9977                let mut new_range = old_range.clone();
 9978                let mut new_node = None;
 9979                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9980                {
 9981                    new_node = Some(node);
 9982                    new_range = containing_range;
 9983                    if !display_map.intersects_fold(new_range.start)
 9984                        && !display_map.intersects_fold(new_range.end)
 9985                    {
 9986                        break;
 9987                    }
 9988                }
 9989
 9990                if let Some(node) = new_node {
 9991                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9992                    // nodes. Parent and grandparent are also logged because this operation will not
 9993                    // visit nodes that have the same range as their parent.
 9994                    log::info!("Node: {node:?}");
 9995                    let parent = node.parent();
 9996                    log::info!("Parent: {parent:?}");
 9997                    let grandparent = parent.and_then(|x| x.parent());
 9998                    log::info!("Grandparent: {grandparent:?}");
 9999                }
10000
10001                selected_larger_node |= new_range != old_range;
10002                Selection {
10003                    id: selection.id,
10004                    start: new_range.start,
10005                    end: new_range.end,
10006                    goal: SelectionGoal::None,
10007                    reversed: selection.reversed,
10008                }
10009            })
10010            .collect::<Vec<_>>();
10011
10012        if selected_larger_node {
10013            stack.push(old_selections);
10014            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10015                s.select(new_selections);
10016            });
10017        }
10018        self.select_larger_syntax_node_stack = stack;
10019    }
10020
10021    pub fn select_smaller_syntax_node(
10022        &mut self,
10023        _: &SelectSmallerSyntaxNode,
10024        window: &mut Window,
10025        cx: &mut Context<Self>,
10026    ) {
10027        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10028        if let Some(selections) = stack.pop() {
10029            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10030                s.select(selections.to_vec());
10031            });
10032        }
10033        self.select_larger_syntax_node_stack = stack;
10034    }
10035
10036    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10037        if !EditorSettings::get_global(cx).gutter.runnables {
10038            self.clear_tasks();
10039            return Task::ready(());
10040        }
10041        let project = self.project.as_ref().map(Entity::downgrade);
10042        cx.spawn_in(window, |this, mut cx| async move {
10043            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10044            let Some(project) = project.and_then(|p| p.upgrade()) else {
10045                return;
10046            };
10047            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10048                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10049            }) else {
10050                return;
10051            };
10052
10053            let hide_runnables = project
10054                .update(&mut cx, |project, cx| {
10055                    // Do not display any test indicators in non-dev server remote projects.
10056                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10057                })
10058                .unwrap_or(true);
10059            if hide_runnables {
10060                return;
10061            }
10062            let new_rows =
10063                cx.background_executor()
10064                    .spawn({
10065                        let snapshot = display_snapshot.clone();
10066                        async move {
10067                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10068                        }
10069                    })
10070                    .await;
10071
10072            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10073            this.update(&mut cx, |this, _| {
10074                this.clear_tasks();
10075                for (key, value) in rows {
10076                    this.insert_tasks(key, value);
10077                }
10078            })
10079            .ok();
10080        })
10081    }
10082    fn fetch_runnable_ranges(
10083        snapshot: &DisplaySnapshot,
10084        range: Range<Anchor>,
10085    ) -> Vec<language::RunnableRange> {
10086        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10087    }
10088
10089    fn runnable_rows(
10090        project: Entity<Project>,
10091        snapshot: DisplaySnapshot,
10092        runnable_ranges: Vec<RunnableRange>,
10093        mut cx: AsyncWindowContext,
10094    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10095        runnable_ranges
10096            .into_iter()
10097            .filter_map(|mut runnable| {
10098                let tasks = cx
10099                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10100                    .ok()?;
10101                if tasks.is_empty() {
10102                    return None;
10103                }
10104
10105                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10106
10107                let row = snapshot
10108                    .buffer_snapshot
10109                    .buffer_line_for_row(MultiBufferRow(point.row))?
10110                    .1
10111                    .start
10112                    .row;
10113
10114                let context_range =
10115                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10116                Some((
10117                    (runnable.buffer_id, row),
10118                    RunnableTasks {
10119                        templates: tasks,
10120                        offset: MultiBufferOffset(runnable.run_range.start),
10121                        context_range,
10122                        column: point.column,
10123                        extra_variables: runnable.extra_captures,
10124                    },
10125                ))
10126            })
10127            .collect()
10128    }
10129
10130    fn templates_with_tags(
10131        project: &Entity<Project>,
10132        runnable: &mut Runnable,
10133        cx: &mut App,
10134    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10135        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10136            let (worktree_id, file) = project
10137                .buffer_for_id(runnable.buffer, cx)
10138                .and_then(|buffer| buffer.read(cx).file())
10139                .map(|file| (file.worktree_id(cx), file.clone()))
10140                .unzip();
10141
10142            (
10143                project.task_store().read(cx).task_inventory().cloned(),
10144                worktree_id,
10145                file,
10146            )
10147        });
10148
10149        let tags = mem::take(&mut runnable.tags);
10150        let mut tags: Vec<_> = tags
10151            .into_iter()
10152            .flat_map(|tag| {
10153                let tag = tag.0.clone();
10154                inventory
10155                    .as_ref()
10156                    .into_iter()
10157                    .flat_map(|inventory| {
10158                        inventory.read(cx).list_tasks(
10159                            file.clone(),
10160                            Some(runnable.language.clone()),
10161                            worktree_id,
10162                            cx,
10163                        )
10164                    })
10165                    .filter(move |(_, template)| {
10166                        template.tags.iter().any(|source_tag| source_tag == &tag)
10167                    })
10168            })
10169            .sorted_by_key(|(kind, _)| kind.to_owned())
10170            .collect();
10171        if let Some((leading_tag_source, _)) = tags.first() {
10172            // Strongest source wins; if we have worktree tag binding, prefer that to
10173            // global and language bindings;
10174            // if we have a global binding, prefer that to language binding.
10175            let first_mismatch = tags
10176                .iter()
10177                .position(|(tag_source, _)| tag_source != leading_tag_source);
10178            if let Some(index) = first_mismatch {
10179                tags.truncate(index);
10180            }
10181        }
10182
10183        tags
10184    }
10185
10186    pub fn move_to_enclosing_bracket(
10187        &mut self,
10188        _: &MoveToEnclosingBracket,
10189        window: &mut Window,
10190        cx: &mut Context<Self>,
10191    ) {
10192        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10193            s.move_offsets_with(|snapshot, selection| {
10194                let Some(enclosing_bracket_ranges) =
10195                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10196                else {
10197                    return;
10198                };
10199
10200                let mut best_length = usize::MAX;
10201                let mut best_inside = false;
10202                let mut best_in_bracket_range = false;
10203                let mut best_destination = None;
10204                for (open, close) in enclosing_bracket_ranges {
10205                    let close = close.to_inclusive();
10206                    let length = close.end() - open.start;
10207                    let inside = selection.start >= open.end && selection.end <= *close.start();
10208                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10209                        || close.contains(&selection.head());
10210
10211                    // If best is next to a bracket and current isn't, skip
10212                    if !in_bracket_range && best_in_bracket_range {
10213                        continue;
10214                    }
10215
10216                    // Prefer smaller lengths unless best is inside and current isn't
10217                    if length > best_length && (best_inside || !inside) {
10218                        continue;
10219                    }
10220
10221                    best_length = length;
10222                    best_inside = inside;
10223                    best_in_bracket_range = in_bracket_range;
10224                    best_destination = Some(
10225                        if close.contains(&selection.start) && close.contains(&selection.end) {
10226                            if inside {
10227                                open.end
10228                            } else {
10229                                open.start
10230                            }
10231                        } else if inside {
10232                            *close.start()
10233                        } else {
10234                            *close.end()
10235                        },
10236                    );
10237                }
10238
10239                if let Some(destination) = best_destination {
10240                    selection.collapse_to(destination, SelectionGoal::None);
10241                }
10242            })
10243        });
10244    }
10245
10246    pub fn undo_selection(
10247        &mut self,
10248        _: &UndoSelection,
10249        window: &mut Window,
10250        cx: &mut Context<Self>,
10251    ) {
10252        self.end_selection(window, cx);
10253        self.selection_history.mode = SelectionHistoryMode::Undoing;
10254        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10255            self.change_selections(None, window, cx, |s| {
10256                s.select_anchors(entry.selections.to_vec())
10257            });
10258            self.select_next_state = entry.select_next_state;
10259            self.select_prev_state = entry.select_prev_state;
10260            self.add_selections_state = entry.add_selections_state;
10261            self.request_autoscroll(Autoscroll::newest(), cx);
10262        }
10263        self.selection_history.mode = SelectionHistoryMode::Normal;
10264    }
10265
10266    pub fn redo_selection(
10267        &mut self,
10268        _: &RedoSelection,
10269        window: &mut Window,
10270        cx: &mut Context<Self>,
10271    ) {
10272        self.end_selection(window, cx);
10273        self.selection_history.mode = SelectionHistoryMode::Redoing;
10274        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10275            self.change_selections(None, window, cx, |s| {
10276                s.select_anchors(entry.selections.to_vec())
10277            });
10278            self.select_next_state = entry.select_next_state;
10279            self.select_prev_state = entry.select_prev_state;
10280            self.add_selections_state = entry.add_selections_state;
10281            self.request_autoscroll(Autoscroll::newest(), cx);
10282        }
10283        self.selection_history.mode = SelectionHistoryMode::Normal;
10284    }
10285
10286    pub fn expand_excerpts(
10287        &mut self,
10288        action: &ExpandExcerpts,
10289        _: &mut Window,
10290        cx: &mut Context<Self>,
10291    ) {
10292        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10293    }
10294
10295    pub fn expand_excerpts_down(
10296        &mut self,
10297        action: &ExpandExcerptsDown,
10298        _: &mut Window,
10299        cx: &mut Context<Self>,
10300    ) {
10301        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10302    }
10303
10304    pub fn expand_excerpts_up(
10305        &mut self,
10306        action: &ExpandExcerptsUp,
10307        _: &mut Window,
10308        cx: &mut Context<Self>,
10309    ) {
10310        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10311    }
10312
10313    pub fn expand_excerpts_for_direction(
10314        &mut self,
10315        lines: u32,
10316        direction: ExpandExcerptDirection,
10317
10318        cx: &mut Context<Self>,
10319    ) {
10320        let selections = self.selections.disjoint_anchors();
10321
10322        let lines = if lines == 0 {
10323            EditorSettings::get_global(cx).expand_excerpt_lines
10324        } else {
10325            lines
10326        };
10327
10328        self.buffer.update(cx, |buffer, cx| {
10329            let snapshot = buffer.snapshot(cx);
10330            let mut excerpt_ids = selections
10331                .iter()
10332                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10333                .collect::<Vec<_>>();
10334            excerpt_ids.sort();
10335            excerpt_ids.dedup();
10336            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10337        })
10338    }
10339
10340    pub fn expand_excerpt(
10341        &mut self,
10342        excerpt: ExcerptId,
10343        direction: ExpandExcerptDirection,
10344        cx: &mut Context<Self>,
10345    ) {
10346        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10347        self.buffer.update(cx, |buffer, cx| {
10348            buffer.expand_excerpts([excerpt], lines, direction, cx)
10349        })
10350    }
10351
10352    pub fn go_to_singleton_buffer_point(
10353        &mut self,
10354        point: Point,
10355        window: &mut Window,
10356        cx: &mut Context<Self>,
10357    ) {
10358        self.go_to_singleton_buffer_range(point..point, window, cx);
10359    }
10360
10361    pub fn go_to_singleton_buffer_range(
10362        &mut self,
10363        range: Range<Point>,
10364        window: &mut Window,
10365        cx: &mut Context<Self>,
10366    ) {
10367        let multibuffer = self.buffer().read(cx);
10368        let Some(buffer) = multibuffer.as_singleton() else {
10369            return;
10370        };
10371        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10372            return;
10373        };
10374        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10375            return;
10376        };
10377        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10378            s.select_anchor_ranges([start..end])
10379        });
10380    }
10381
10382    fn go_to_diagnostic(
10383        &mut self,
10384        _: &GoToDiagnostic,
10385        window: &mut Window,
10386        cx: &mut Context<Self>,
10387    ) {
10388        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10389    }
10390
10391    fn go_to_prev_diagnostic(
10392        &mut self,
10393        _: &GoToPrevDiagnostic,
10394        window: &mut Window,
10395        cx: &mut Context<Self>,
10396    ) {
10397        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10398    }
10399
10400    pub fn go_to_diagnostic_impl(
10401        &mut self,
10402        direction: Direction,
10403        window: &mut Window,
10404        cx: &mut Context<Self>,
10405    ) {
10406        let buffer = self.buffer.read(cx).snapshot(cx);
10407        let selection = self.selections.newest::<usize>(cx);
10408
10409        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10410        if direction == Direction::Next {
10411            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10412                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10413                    return;
10414                };
10415                self.activate_diagnostics(
10416                    buffer_id,
10417                    popover.local_diagnostic.diagnostic.group_id,
10418                    window,
10419                    cx,
10420                );
10421                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10422                    let primary_range_start = active_diagnostics.primary_range.start;
10423                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10424                        let mut new_selection = s.newest_anchor().clone();
10425                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10426                        s.select_anchors(vec![new_selection.clone()]);
10427                    });
10428                    self.refresh_inline_completion(false, true, window, cx);
10429                }
10430                return;
10431            }
10432        }
10433
10434        let active_group_id = self
10435            .active_diagnostics
10436            .as_ref()
10437            .map(|active_group| active_group.group_id);
10438        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10439            active_diagnostics
10440                .primary_range
10441                .to_offset(&buffer)
10442                .to_inclusive()
10443        });
10444        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10445            if active_primary_range.contains(&selection.head()) {
10446                *active_primary_range.start()
10447            } else {
10448                selection.head()
10449            }
10450        } else {
10451            selection.head()
10452        };
10453
10454        let snapshot = self.snapshot(window, cx);
10455        let primary_diagnostics_before = buffer
10456            .diagnostics_in_range::<usize>(0..search_start)
10457            .filter(|entry| entry.diagnostic.is_primary)
10458            .filter(|entry| entry.range.start != entry.range.end)
10459            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10460            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10461            .collect::<Vec<_>>();
10462        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10463            primary_diagnostics_before
10464                .iter()
10465                .position(|entry| entry.diagnostic.group_id == active_group_id)
10466        });
10467
10468        let primary_diagnostics_after = buffer
10469            .diagnostics_in_range::<usize>(search_start..buffer.len())
10470            .filter(|entry| entry.diagnostic.is_primary)
10471            .filter(|entry| entry.range.start != entry.range.end)
10472            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10473            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10474            .collect::<Vec<_>>();
10475        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10476            primary_diagnostics_after
10477                .iter()
10478                .enumerate()
10479                .rev()
10480                .find_map(|(i, entry)| {
10481                    if entry.diagnostic.group_id == active_group_id {
10482                        Some(i)
10483                    } else {
10484                        None
10485                    }
10486                })
10487        });
10488
10489        let next_primary_diagnostic = match direction {
10490            Direction::Prev => primary_diagnostics_before
10491                .iter()
10492                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10493                .rev()
10494                .next(),
10495            Direction::Next => primary_diagnostics_after
10496                .iter()
10497                .skip(
10498                    last_same_group_diagnostic_after
10499                        .map(|index| index + 1)
10500                        .unwrap_or(0),
10501                )
10502                .next(),
10503        };
10504
10505        // Cycle around to the start of the buffer, potentially moving back to the start of
10506        // the currently active diagnostic.
10507        let cycle_around = || match direction {
10508            Direction::Prev => primary_diagnostics_after
10509                .iter()
10510                .rev()
10511                .chain(primary_diagnostics_before.iter().rev())
10512                .next(),
10513            Direction::Next => primary_diagnostics_before
10514                .iter()
10515                .chain(primary_diagnostics_after.iter())
10516                .next(),
10517        };
10518
10519        if let Some((primary_range, group_id)) = next_primary_diagnostic
10520            .or_else(cycle_around)
10521            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10522        {
10523            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10524                return;
10525            };
10526            self.activate_diagnostics(buffer_id, group_id, window, cx);
10527            if self.active_diagnostics.is_some() {
10528                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10529                    s.select(vec![Selection {
10530                        id: selection.id,
10531                        start: primary_range.start,
10532                        end: primary_range.start,
10533                        reversed: false,
10534                        goal: SelectionGoal::None,
10535                    }]);
10536                });
10537                self.refresh_inline_completion(false, true, window, cx);
10538            }
10539        }
10540    }
10541
10542    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10543        let snapshot = self.snapshot(window, cx);
10544        let selection = self.selections.newest::<Point>(cx);
10545        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10546    }
10547
10548    fn go_to_hunk_after_position(
10549        &mut self,
10550        snapshot: &EditorSnapshot,
10551        position: Point,
10552        window: &mut Window,
10553        cx: &mut Context<Editor>,
10554    ) -> Option<MultiBufferDiffHunk> {
10555        let mut hunk = snapshot
10556            .buffer_snapshot
10557            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10558            .find(|hunk| hunk.row_range.start.0 > position.row);
10559        if hunk.is_none() {
10560            hunk = snapshot
10561                .buffer_snapshot
10562                .diff_hunks_in_range(Point::zero()..position)
10563                .find(|hunk| hunk.row_range.end.0 < position.row)
10564        }
10565        if let Some(hunk) = &hunk {
10566            let destination = Point::new(hunk.row_range.start.0, 0);
10567            self.unfold_ranges(&[destination..destination], false, false, cx);
10568            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10569                s.select_ranges(vec![destination..destination]);
10570            });
10571        }
10572
10573        hunk
10574    }
10575
10576    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10577        let snapshot = self.snapshot(window, cx);
10578        let selection = self.selections.newest::<Point>(cx);
10579        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10580    }
10581
10582    fn go_to_hunk_before_position(
10583        &mut self,
10584        snapshot: &EditorSnapshot,
10585        position: Point,
10586        window: &mut Window,
10587        cx: &mut Context<Editor>,
10588    ) -> Option<MultiBufferDiffHunk> {
10589        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10590        if hunk.is_none() {
10591            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10592        }
10593        if let Some(hunk) = &hunk {
10594            let destination = Point::new(hunk.row_range.start.0, 0);
10595            self.unfold_ranges(&[destination..destination], false, false, cx);
10596            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10597                s.select_ranges(vec![destination..destination]);
10598            });
10599        }
10600
10601        hunk
10602    }
10603
10604    pub fn go_to_definition(
10605        &mut self,
10606        _: &GoToDefinition,
10607        window: &mut Window,
10608        cx: &mut Context<Self>,
10609    ) -> Task<Result<Navigated>> {
10610        let definition =
10611            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10612        cx.spawn_in(window, |editor, mut cx| async move {
10613            if definition.await? == Navigated::Yes {
10614                return Ok(Navigated::Yes);
10615            }
10616            match editor.update_in(&mut cx, |editor, window, cx| {
10617                editor.find_all_references(&FindAllReferences, window, cx)
10618            })? {
10619                Some(references) => references.await,
10620                None => Ok(Navigated::No),
10621            }
10622        })
10623    }
10624
10625    pub fn go_to_declaration(
10626        &mut self,
10627        _: &GoToDeclaration,
10628        window: &mut Window,
10629        cx: &mut Context<Self>,
10630    ) -> Task<Result<Navigated>> {
10631        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10632    }
10633
10634    pub fn go_to_declaration_split(
10635        &mut self,
10636        _: &GoToDeclaration,
10637        window: &mut Window,
10638        cx: &mut Context<Self>,
10639    ) -> Task<Result<Navigated>> {
10640        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10641    }
10642
10643    pub fn go_to_implementation(
10644        &mut self,
10645        _: &GoToImplementation,
10646        window: &mut Window,
10647        cx: &mut Context<Self>,
10648    ) -> Task<Result<Navigated>> {
10649        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10650    }
10651
10652    pub fn go_to_implementation_split(
10653        &mut self,
10654        _: &GoToImplementationSplit,
10655        window: &mut Window,
10656        cx: &mut Context<Self>,
10657    ) -> Task<Result<Navigated>> {
10658        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10659    }
10660
10661    pub fn go_to_type_definition(
10662        &mut self,
10663        _: &GoToTypeDefinition,
10664        window: &mut Window,
10665        cx: &mut Context<Self>,
10666    ) -> Task<Result<Navigated>> {
10667        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10668    }
10669
10670    pub fn go_to_definition_split(
10671        &mut self,
10672        _: &GoToDefinitionSplit,
10673        window: &mut Window,
10674        cx: &mut Context<Self>,
10675    ) -> Task<Result<Navigated>> {
10676        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10677    }
10678
10679    pub fn go_to_type_definition_split(
10680        &mut self,
10681        _: &GoToTypeDefinitionSplit,
10682        window: &mut Window,
10683        cx: &mut Context<Self>,
10684    ) -> Task<Result<Navigated>> {
10685        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10686    }
10687
10688    fn go_to_definition_of_kind(
10689        &mut self,
10690        kind: GotoDefinitionKind,
10691        split: bool,
10692        window: &mut Window,
10693        cx: &mut Context<Self>,
10694    ) -> Task<Result<Navigated>> {
10695        let Some(provider) = self.semantics_provider.clone() else {
10696            return Task::ready(Ok(Navigated::No));
10697        };
10698        let head = self.selections.newest::<usize>(cx).head();
10699        let buffer = self.buffer.read(cx);
10700        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10701            text_anchor
10702        } else {
10703            return Task::ready(Ok(Navigated::No));
10704        };
10705
10706        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10707            return Task::ready(Ok(Navigated::No));
10708        };
10709
10710        cx.spawn_in(window, |editor, mut cx| async move {
10711            let definitions = definitions.await?;
10712            let navigated = editor
10713                .update_in(&mut cx, |editor, window, cx| {
10714                    editor.navigate_to_hover_links(
10715                        Some(kind),
10716                        definitions
10717                            .into_iter()
10718                            .filter(|location| {
10719                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10720                            })
10721                            .map(HoverLink::Text)
10722                            .collect::<Vec<_>>(),
10723                        split,
10724                        window,
10725                        cx,
10726                    )
10727                })?
10728                .await?;
10729            anyhow::Ok(navigated)
10730        })
10731    }
10732
10733    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10734        let selection = self.selections.newest_anchor();
10735        let head = selection.head();
10736        let tail = selection.tail();
10737
10738        let Some((buffer, start_position)) =
10739            self.buffer.read(cx).text_anchor_for_position(head, cx)
10740        else {
10741            return;
10742        };
10743
10744        let end_position = if head != tail {
10745            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10746                return;
10747            };
10748            Some(pos)
10749        } else {
10750            None
10751        };
10752
10753        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10754            let url = if let Some(end_pos) = end_position {
10755                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10756            } else {
10757                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10758            };
10759
10760            if let Some(url) = url {
10761                editor.update(&mut cx, |_, cx| {
10762                    cx.open_url(&url);
10763                })
10764            } else {
10765                Ok(())
10766            }
10767        });
10768
10769        url_finder.detach();
10770    }
10771
10772    pub fn open_selected_filename(
10773        &mut self,
10774        _: &OpenSelectedFilename,
10775        window: &mut Window,
10776        cx: &mut Context<Self>,
10777    ) {
10778        let Some(workspace) = self.workspace() else {
10779            return;
10780        };
10781
10782        let position = self.selections.newest_anchor().head();
10783
10784        let Some((buffer, buffer_position)) =
10785            self.buffer.read(cx).text_anchor_for_position(position, cx)
10786        else {
10787            return;
10788        };
10789
10790        let project = self.project.clone();
10791
10792        cx.spawn_in(window, |_, mut cx| async move {
10793            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10794
10795            if let Some((_, path)) = result {
10796                workspace
10797                    .update_in(&mut cx, |workspace, window, cx| {
10798                        workspace.open_resolved_path(path, window, cx)
10799                    })?
10800                    .await?;
10801            }
10802            anyhow::Ok(())
10803        })
10804        .detach();
10805    }
10806
10807    pub(crate) fn navigate_to_hover_links(
10808        &mut self,
10809        kind: Option<GotoDefinitionKind>,
10810        mut definitions: Vec<HoverLink>,
10811        split: bool,
10812        window: &mut Window,
10813        cx: &mut Context<Editor>,
10814    ) -> Task<Result<Navigated>> {
10815        // If there is one definition, just open it directly
10816        if definitions.len() == 1 {
10817            let definition = definitions.pop().unwrap();
10818
10819            enum TargetTaskResult {
10820                Location(Option<Location>),
10821                AlreadyNavigated,
10822            }
10823
10824            let target_task = match definition {
10825                HoverLink::Text(link) => {
10826                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10827                }
10828                HoverLink::InlayHint(lsp_location, server_id) => {
10829                    let computation =
10830                        self.compute_target_location(lsp_location, server_id, window, cx);
10831                    cx.background_executor().spawn(async move {
10832                        let location = computation.await?;
10833                        Ok(TargetTaskResult::Location(location))
10834                    })
10835                }
10836                HoverLink::Url(url) => {
10837                    cx.open_url(&url);
10838                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10839                }
10840                HoverLink::File(path) => {
10841                    if let Some(workspace) = self.workspace() {
10842                        cx.spawn_in(window, |_, mut cx| async move {
10843                            workspace
10844                                .update_in(&mut cx, |workspace, window, cx| {
10845                                    workspace.open_resolved_path(path, window, cx)
10846                                })?
10847                                .await
10848                                .map(|_| TargetTaskResult::AlreadyNavigated)
10849                        })
10850                    } else {
10851                        Task::ready(Ok(TargetTaskResult::Location(None)))
10852                    }
10853                }
10854            };
10855            cx.spawn_in(window, |editor, mut cx| async move {
10856                let target = match target_task.await.context("target resolution task")? {
10857                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10858                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10859                    TargetTaskResult::Location(Some(target)) => target,
10860                };
10861
10862                editor.update_in(&mut cx, |editor, window, cx| {
10863                    let Some(workspace) = editor.workspace() else {
10864                        return Navigated::No;
10865                    };
10866                    let pane = workspace.read(cx).active_pane().clone();
10867
10868                    let range = target.range.to_point(target.buffer.read(cx));
10869                    let range = editor.range_for_match(&range);
10870                    let range = collapse_multiline_range(range);
10871
10872                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10873                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10874                    } else {
10875                        window.defer(cx, move |window, cx| {
10876                            let target_editor: Entity<Self> =
10877                                workspace.update(cx, |workspace, cx| {
10878                                    let pane = if split {
10879                                        workspace.adjacent_pane(window, cx)
10880                                    } else {
10881                                        workspace.active_pane().clone()
10882                                    };
10883
10884                                    workspace.open_project_item(
10885                                        pane,
10886                                        target.buffer.clone(),
10887                                        true,
10888                                        true,
10889                                        window,
10890                                        cx,
10891                                    )
10892                                });
10893                            target_editor.update(cx, |target_editor, cx| {
10894                                // When selecting a definition in a different buffer, disable the nav history
10895                                // to avoid creating a history entry at the previous cursor location.
10896                                pane.update(cx, |pane, _| pane.disable_history());
10897                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10898                                pane.update(cx, |pane, _| pane.enable_history());
10899                            });
10900                        });
10901                    }
10902                    Navigated::Yes
10903                })
10904            })
10905        } else if !definitions.is_empty() {
10906            cx.spawn_in(window, |editor, mut cx| async move {
10907                let (title, location_tasks, workspace) = editor
10908                    .update_in(&mut cx, |editor, window, cx| {
10909                        let tab_kind = match kind {
10910                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10911                            _ => "Definitions",
10912                        };
10913                        let title = definitions
10914                            .iter()
10915                            .find_map(|definition| match definition {
10916                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10917                                    let buffer = origin.buffer.read(cx);
10918                                    format!(
10919                                        "{} for {}",
10920                                        tab_kind,
10921                                        buffer
10922                                            .text_for_range(origin.range.clone())
10923                                            .collect::<String>()
10924                                    )
10925                                }),
10926                                HoverLink::InlayHint(_, _) => None,
10927                                HoverLink::Url(_) => None,
10928                                HoverLink::File(_) => None,
10929                            })
10930                            .unwrap_or(tab_kind.to_string());
10931                        let location_tasks = definitions
10932                            .into_iter()
10933                            .map(|definition| match definition {
10934                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10935                                HoverLink::InlayHint(lsp_location, server_id) => editor
10936                                    .compute_target_location(lsp_location, server_id, window, cx),
10937                                HoverLink::Url(_) => Task::ready(Ok(None)),
10938                                HoverLink::File(_) => Task::ready(Ok(None)),
10939                            })
10940                            .collect::<Vec<_>>();
10941                        (title, location_tasks, editor.workspace().clone())
10942                    })
10943                    .context("location tasks preparation")?;
10944
10945                let locations = future::join_all(location_tasks)
10946                    .await
10947                    .into_iter()
10948                    .filter_map(|location| location.transpose())
10949                    .collect::<Result<_>>()
10950                    .context("location tasks")?;
10951
10952                let Some(workspace) = workspace else {
10953                    return Ok(Navigated::No);
10954                };
10955                let opened = workspace
10956                    .update_in(&mut cx, |workspace, window, cx| {
10957                        Self::open_locations_in_multibuffer(
10958                            workspace,
10959                            locations,
10960                            title,
10961                            split,
10962                            MultibufferSelectionMode::First,
10963                            window,
10964                            cx,
10965                        )
10966                    })
10967                    .ok();
10968
10969                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10970            })
10971        } else {
10972            Task::ready(Ok(Navigated::No))
10973        }
10974    }
10975
10976    fn compute_target_location(
10977        &self,
10978        lsp_location: lsp::Location,
10979        server_id: LanguageServerId,
10980        window: &mut Window,
10981        cx: &mut Context<Self>,
10982    ) -> Task<anyhow::Result<Option<Location>>> {
10983        let Some(project) = self.project.clone() else {
10984            return Task::ready(Ok(None));
10985        };
10986
10987        cx.spawn_in(window, move |editor, mut cx| async move {
10988            let location_task = editor.update(&mut cx, |_, cx| {
10989                project.update(cx, |project, cx| {
10990                    let language_server_name = project
10991                        .language_server_statuses(cx)
10992                        .find(|(id, _)| server_id == *id)
10993                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10994                    language_server_name.map(|language_server_name| {
10995                        project.open_local_buffer_via_lsp(
10996                            lsp_location.uri.clone(),
10997                            server_id,
10998                            language_server_name,
10999                            cx,
11000                        )
11001                    })
11002                })
11003            })?;
11004            let location = match location_task {
11005                Some(task) => Some({
11006                    let target_buffer_handle = task.await.context("open local buffer")?;
11007                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11008                        let target_start = target_buffer
11009                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11010                        let target_end = target_buffer
11011                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11012                        target_buffer.anchor_after(target_start)
11013                            ..target_buffer.anchor_before(target_end)
11014                    })?;
11015                    Location {
11016                        buffer: target_buffer_handle,
11017                        range,
11018                    }
11019                }),
11020                None => None,
11021            };
11022            Ok(location)
11023        })
11024    }
11025
11026    pub fn find_all_references(
11027        &mut self,
11028        _: &FindAllReferences,
11029        window: &mut Window,
11030        cx: &mut Context<Self>,
11031    ) -> Option<Task<Result<Navigated>>> {
11032        let selection = self.selections.newest::<usize>(cx);
11033        let multi_buffer = self.buffer.read(cx);
11034        let head = selection.head();
11035
11036        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11037        let head_anchor = multi_buffer_snapshot.anchor_at(
11038            head,
11039            if head < selection.tail() {
11040                Bias::Right
11041            } else {
11042                Bias::Left
11043            },
11044        );
11045
11046        match self
11047            .find_all_references_task_sources
11048            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11049        {
11050            Ok(_) => {
11051                log::info!(
11052                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11053                );
11054                return None;
11055            }
11056            Err(i) => {
11057                self.find_all_references_task_sources.insert(i, head_anchor);
11058            }
11059        }
11060
11061        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11062        let workspace = self.workspace()?;
11063        let project = workspace.read(cx).project().clone();
11064        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11065        Some(cx.spawn_in(window, |editor, mut cx| async move {
11066            let _cleanup = defer({
11067                let mut cx = cx.clone();
11068                move || {
11069                    let _ = editor.update(&mut cx, |editor, _| {
11070                        if let Ok(i) =
11071                            editor
11072                                .find_all_references_task_sources
11073                                .binary_search_by(|anchor| {
11074                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11075                                })
11076                        {
11077                            editor.find_all_references_task_sources.remove(i);
11078                        }
11079                    });
11080                }
11081            });
11082
11083            let locations = references.await?;
11084            if locations.is_empty() {
11085                return anyhow::Ok(Navigated::No);
11086            }
11087
11088            workspace.update_in(&mut cx, |workspace, window, cx| {
11089                let title = locations
11090                    .first()
11091                    .as_ref()
11092                    .map(|location| {
11093                        let buffer = location.buffer.read(cx);
11094                        format!(
11095                            "References to `{}`",
11096                            buffer
11097                                .text_for_range(location.range.clone())
11098                                .collect::<String>()
11099                        )
11100                    })
11101                    .unwrap();
11102                Self::open_locations_in_multibuffer(
11103                    workspace,
11104                    locations,
11105                    title,
11106                    false,
11107                    MultibufferSelectionMode::First,
11108                    window,
11109                    cx,
11110                );
11111                Navigated::Yes
11112            })
11113        }))
11114    }
11115
11116    /// Opens a multibuffer with the given project locations in it
11117    pub fn open_locations_in_multibuffer(
11118        workspace: &mut Workspace,
11119        mut locations: Vec<Location>,
11120        title: String,
11121        split: bool,
11122        multibuffer_selection_mode: MultibufferSelectionMode,
11123        window: &mut Window,
11124        cx: &mut Context<Workspace>,
11125    ) {
11126        // If there are multiple definitions, open them in a multibuffer
11127        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11128        let mut locations = locations.into_iter().peekable();
11129        let mut ranges = Vec::new();
11130        let capability = workspace.project().read(cx).capability();
11131
11132        let excerpt_buffer = cx.new(|cx| {
11133            let mut multibuffer = MultiBuffer::new(capability);
11134            while let Some(location) = locations.next() {
11135                let buffer = location.buffer.read(cx);
11136                let mut ranges_for_buffer = Vec::new();
11137                let range = location.range.to_offset(buffer);
11138                ranges_for_buffer.push(range.clone());
11139
11140                while let Some(next_location) = locations.peek() {
11141                    if next_location.buffer == location.buffer {
11142                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11143                        locations.next();
11144                    } else {
11145                        break;
11146                    }
11147                }
11148
11149                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11150                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11151                    location.buffer.clone(),
11152                    ranges_for_buffer,
11153                    DEFAULT_MULTIBUFFER_CONTEXT,
11154                    cx,
11155                ))
11156            }
11157
11158            multibuffer.with_title(title)
11159        });
11160
11161        let editor = cx.new(|cx| {
11162            Editor::for_multibuffer(
11163                excerpt_buffer,
11164                Some(workspace.project().clone()),
11165                true,
11166                window,
11167                cx,
11168            )
11169        });
11170        editor.update(cx, |editor, cx| {
11171            match multibuffer_selection_mode {
11172                MultibufferSelectionMode::First => {
11173                    if let Some(first_range) = ranges.first() {
11174                        editor.change_selections(None, window, cx, |selections| {
11175                            selections.clear_disjoint();
11176                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11177                        });
11178                    }
11179                    editor.highlight_background::<Self>(
11180                        &ranges,
11181                        |theme| theme.editor_highlighted_line_background,
11182                        cx,
11183                    );
11184                }
11185                MultibufferSelectionMode::All => {
11186                    editor.change_selections(None, window, cx, |selections| {
11187                        selections.clear_disjoint();
11188                        selections.select_anchor_ranges(ranges);
11189                    });
11190                }
11191            }
11192            editor.register_buffers_with_language_servers(cx);
11193        });
11194
11195        let item = Box::new(editor);
11196        let item_id = item.item_id();
11197
11198        if split {
11199            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11200        } else {
11201            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11202                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11203                    pane.close_current_preview_item(window, cx)
11204                } else {
11205                    None
11206                }
11207            });
11208            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11209        }
11210        workspace.active_pane().update(cx, |pane, cx| {
11211            pane.set_preview_item_id(Some(item_id), cx);
11212        });
11213    }
11214
11215    pub fn rename(
11216        &mut self,
11217        _: &Rename,
11218        window: &mut Window,
11219        cx: &mut Context<Self>,
11220    ) -> Option<Task<Result<()>>> {
11221        use language::ToOffset as _;
11222
11223        let provider = self.semantics_provider.clone()?;
11224        let selection = self.selections.newest_anchor().clone();
11225        let (cursor_buffer, cursor_buffer_position) = self
11226            .buffer
11227            .read(cx)
11228            .text_anchor_for_position(selection.head(), cx)?;
11229        let (tail_buffer, cursor_buffer_position_end) = self
11230            .buffer
11231            .read(cx)
11232            .text_anchor_for_position(selection.tail(), cx)?;
11233        if tail_buffer != cursor_buffer {
11234            return None;
11235        }
11236
11237        let snapshot = cursor_buffer.read(cx).snapshot();
11238        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11239        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11240        let prepare_rename = provider
11241            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11242            .unwrap_or_else(|| Task::ready(Ok(None)));
11243        drop(snapshot);
11244
11245        Some(cx.spawn_in(window, |this, mut cx| async move {
11246            let rename_range = if let Some(range) = prepare_rename.await? {
11247                Some(range)
11248            } else {
11249                this.update(&mut cx, |this, cx| {
11250                    let buffer = this.buffer.read(cx).snapshot(cx);
11251                    let mut buffer_highlights = this
11252                        .document_highlights_for_position(selection.head(), &buffer)
11253                        .filter(|highlight| {
11254                            highlight.start.excerpt_id == selection.head().excerpt_id
11255                                && highlight.end.excerpt_id == selection.head().excerpt_id
11256                        });
11257                    buffer_highlights
11258                        .next()
11259                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11260                })?
11261            };
11262            if let Some(rename_range) = rename_range {
11263                this.update_in(&mut cx, |this, window, cx| {
11264                    let snapshot = cursor_buffer.read(cx).snapshot();
11265                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11266                    let cursor_offset_in_rename_range =
11267                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11268                    let cursor_offset_in_rename_range_end =
11269                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11270
11271                    this.take_rename(false, window, cx);
11272                    let buffer = this.buffer.read(cx).read(cx);
11273                    let cursor_offset = selection.head().to_offset(&buffer);
11274                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11275                    let rename_end = rename_start + rename_buffer_range.len();
11276                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11277                    let mut old_highlight_id = None;
11278                    let old_name: Arc<str> = buffer
11279                        .chunks(rename_start..rename_end, true)
11280                        .map(|chunk| {
11281                            if old_highlight_id.is_none() {
11282                                old_highlight_id = chunk.syntax_highlight_id;
11283                            }
11284                            chunk.text
11285                        })
11286                        .collect::<String>()
11287                        .into();
11288
11289                    drop(buffer);
11290
11291                    // Position the selection in the rename editor so that it matches the current selection.
11292                    this.show_local_selections = false;
11293                    let rename_editor = cx.new(|cx| {
11294                        let mut editor = Editor::single_line(window, cx);
11295                        editor.buffer.update(cx, |buffer, cx| {
11296                            buffer.edit([(0..0, old_name.clone())], None, cx)
11297                        });
11298                        let rename_selection_range = match cursor_offset_in_rename_range
11299                            .cmp(&cursor_offset_in_rename_range_end)
11300                        {
11301                            Ordering::Equal => {
11302                                editor.select_all(&SelectAll, window, cx);
11303                                return editor;
11304                            }
11305                            Ordering::Less => {
11306                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11307                            }
11308                            Ordering::Greater => {
11309                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11310                            }
11311                        };
11312                        if rename_selection_range.end > old_name.len() {
11313                            editor.select_all(&SelectAll, window, cx);
11314                        } else {
11315                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11316                                s.select_ranges([rename_selection_range]);
11317                            });
11318                        }
11319                        editor
11320                    });
11321                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11322                        if e == &EditorEvent::Focused {
11323                            cx.emit(EditorEvent::FocusedIn)
11324                        }
11325                    })
11326                    .detach();
11327
11328                    let write_highlights =
11329                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11330                    let read_highlights =
11331                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11332                    let ranges = write_highlights
11333                        .iter()
11334                        .flat_map(|(_, ranges)| ranges.iter())
11335                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11336                        .cloned()
11337                        .collect();
11338
11339                    this.highlight_text::<Rename>(
11340                        ranges,
11341                        HighlightStyle {
11342                            fade_out: Some(0.6),
11343                            ..Default::default()
11344                        },
11345                        cx,
11346                    );
11347                    let rename_focus_handle = rename_editor.focus_handle(cx);
11348                    window.focus(&rename_focus_handle);
11349                    let block_id = this.insert_blocks(
11350                        [BlockProperties {
11351                            style: BlockStyle::Flex,
11352                            placement: BlockPlacement::Below(range.start),
11353                            height: 1,
11354                            render: Arc::new({
11355                                let rename_editor = rename_editor.clone();
11356                                move |cx: &mut BlockContext| {
11357                                    let mut text_style = cx.editor_style.text.clone();
11358                                    if let Some(highlight_style) = old_highlight_id
11359                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11360                                    {
11361                                        text_style = text_style.highlight(highlight_style);
11362                                    }
11363                                    div()
11364                                        .block_mouse_down()
11365                                        .pl(cx.anchor_x)
11366                                        .child(EditorElement::new(
11367                                            &rename_editor,
11368                                            EditorStyle {
11369                                                background: cx.theme().system().transparent,
11370                                                local_player: cx.editor_style.local_player,
11371                                                text: text_style,
11372                                                scrollbar_width: cx.editor_style.scrollbar_width,
11373                                                syntax: cx.editor_style.syntax.clone(),
11374                                                status: cx.editor_style.status.clone(),
11375                                                inlay_hints_style: HighlightStyle {
11376                                                    font_weight: Some(FontWeight::BOLD),
11377                                                    ..make_inlay_hints_style(cx.app)
11378                                                },
11379                                                inline_completion_styles: make_suggestion_styles(
11380                                                    cx.app,
11381                                                ),
11382                                                ..EditorStyle::default()
11383                                            },
11384                                        ))
11385                                        .into_any_element()
11386                                }
11387                            }),
11388                            priority: 0,
11389                        }],
11390                        Some(Autoscroll::fit()),
11391                        cx,
11392                    )[0];
11393                    this.pending_rename = Some(RenameState {
11394                        range,
11395                        old_name,
11396                        editor: rename_editor,
11397                        block_id,
11398                    });
11399                })?;
11400            }
11401
11402            Ok(())
11403        }))
11404    }
11405
11406    pub fn confirm_rename(
11407        &mut self,
11408        _: &ConfirmRename,
11409        window: &mut Window,
11410        cx: &mut Context<Self>,
11411    ) -> Option<Task<Result<()>>> {
11412        let rename = self.take_rename(false, window, cx)?;
11413        let workspace = self.workspace()?.downgrade();
11414        let (buffer, start) = self
11415            .buffer
11416            .read(cx)
11417            .text_anchor_for_position(rename.range.start, cx)?;
11418        let (end_buffer, _) = self
11419            .buffer
11420            .read(cx)
11421            .text_anchor_for_position(rename.range.end, cx)?;
11422        if buffer != end_buffer {
11423            return None;
11424        }
11425
11426        let old_name = rename.old_name;
11427        let new_name = rename.editor.read(cx).text(cx);
11428
11429        let rename = self.semantics_provider.as_ref()?.perform_rename(
11430            &buffer,
11431            start,
11432            new_name.clone(),
11433            cx,
11434        )?;
11435
11436        Some(cx.spawn_in(window, |editor, mut cx| async move {
11437            let project_transaction = rename.await?;
11438            Self::open_project_transaction(
11439                &editor,
11440                workspace,
11441                project_transaction,
11442                format!("Rename: {}{}", old_name, new_name),
11443                cx.clone(),
11444            )
11445            .await?;
11446
11447            editor.update(&mut cx, |editor, cx| {
11448                editor.refresh_document_highlights(cx);
11449            })?;
11450            Ok(())
11451        }))
11452    }
11453
11454    fn take_rename(
11455        &mut self,
11456        moving_cursor: bool,
11457        window: &mut Window,
11458        cx: &mut Context<Self>,
11459    ) -> Option<RenameState> {
11460        let rename = self.pending_rename.take()?;
11461        if rename.editor.focus_handle(cx).is_focused(window) {
11462            window.focus(&self.focus_handle);
11463        }
11464
11465        self.remove_blocks(
11466            [rename.block_id].into_iter().collect(),
11467            Some(Autoscroll::fit()),
11468            cx,
11469        );
11470        self.clear_highlights::<Rename>(cx);
11471        self.show_local_selections = true;
11472
11473        if moving_cursor {
11474            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11475                editor.selections.newest::<usize>(cx).head()
11476            });
11477
11478            // Update the selection to match the position of the selection inside
11479            // the rename editor.
11480            let snapshot = self.buffer.read(cx).read(cx);
11481            let rename_range = rename.range.to_offset(&snapshot);
11482            let cursor_in_editor = snapshot
11483                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11484                .min(rename_range.end);
11485            drop(snapshot);
11486
11487            self.change_selections(None, window, cx, |s| {
11488                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11489            });
11490        } else {
11491            self.refresh_document_highlights(cx);
11492        }
11493
11494        Some(rename)
11495    }
11496
11497    pub fn pending_rename(&self) -> Option<&RenameState> {
11498        self.pending_rename.as_ref()
11499    }
11500
11501    fn format(
11502        &mut self,
11503        _: &Format,
11504        window: &mut Window,
11505        cx: &mut Context<Self>,
11506    ) -> Option<Task<Result<()>>> {
11507        let project = match &self.project {
11508            Some(project) => project.clone(),
11509            None => return None,
11510        };
11511
11512        Some(self.perform_format(
11513            project,
11514            FormatTrigger::Manual,
11515            FormatTarget::Buffers,
11516            window,
11517            cx,
11518        ))
11519    }
11520
11521    fn format_selections(
11522        &mut self,
11523        _: &FormatSelections,
11524        window: &mut Window,
11525        cx: &mut Context<Self>,
11526    ) -> Option<Task<Result<()>>> {
11527        let project = match &self.project {
11528            Some(project) => project.clone(),
11529            None => return None,
11530        };
11531
11532        let ranges = self
11533            .selections
11534            .all_adjusted(cx)
11535            .into_iter()
11536            .map(|selection| selection.range())
11537            .collect_vec();
11538
11539        Some(self.perform_format(
11540            project,
11541            FormatTrigger::Manual,
11542            FormatTarget::Ranges(ranges),
11543            window,
11544            cx,
11545        ))
11546    }
11547
11548    fn perform_format(
11549        &mut self,
11550        project: Entity<Project>,
11551        trigger: FormatTrigger,
11552        target: FormatTarget,
11553        window: &mut Window,
11554        cx: &mut Context<Self>,
11555    ) -> Task<Result<()>> {
11556        let buffer = self.buffer.clone();
11557        let (buffers, target) = match target {
11558            FormatTarget::Buffers => {
11559                let mut buffers = buffer.read(cx).all_buffers();
11560                if trigger == FormatTrigger::Save {
11561                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11562                }
11563                (buffers, LspFormatTarget::Buffers)
11564            }
11565            FormatTarget::Ranges(selection_ranges) => {
11566                let multi_buffer = buffer.read(cx);
11567                let snapshot = multi_buffer.read(cx);
11568                let mut buffers = HashSet::default();
11569                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11570                    BTreeMap::new();
11571                for selection_range in selection_ranges {
11572                    for (buffer, buffer_range, _) in
11573                        snapshot.range_to_buffer_ranges(selection_range)
11574                    {
11575                        let buffer_id = buffer.remote_id();
11576                        let start = buffer.anchor_before(buffer_range.start);
11577                        let end = buffer.anchor_after(buffer_range.end);
11578                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11579                        buffer_id_to_ranges
11580                            .entry(buffer_id)
11581                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11582                            .or_insert_with(|| vec![start..end]);
11583                    }
11584                }
11585                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11586            }
11587        };
11588
11589        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11590        let format = project.update(cx, |project, cx| {
11591            project.format(buffers, target, true, trigger, cx)
11592        });
11593
11594        cx.spawn_in(window, |_, mut cx| async move {
11595            let transaction = futures::select_biased! {
11596                () = timeout => {
11597                    log::warn!("timed out waiting for formatting");
11598                    None
11599                }
11600                transaction = format.log_err().fuse() => transaction,
11601            };
11602
11603            buffer
11604                .update(&mut cx, |buffer, cx| {
11605                    if let Some(transaction) = transaction {
11606                        if !buffer.is_singleton() {
11607                            buffer.push_transaction(&transaction.0, cx);
11608                        }
11609                    }
11610
11611                    cx.notify();
11612                })
11613                .ok();
11614
11615            Ok(())
11616        })
11617    }
11618
11619    fn restart_language_server(
11620        &mut self,
11621        _: &RestartLanguageServer,
11622        _: &mut Window,
11623        cx: &mut Context<Self>,
11624    ) {
11625        if let Some(project) = self.project.clone() {
11626            self.buffer.update(cx, |multi_buffer, cx| {
11627                project.update(cx, |project, cx| {
11628                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11629                });
11630            })
11631        }
11632    }
11633
11634    fn cancel_language_server_work(
11635        workspace: &mut Workspace,
11636        _: &actions::CancelLanguageServerWork,
11637        _: &mut Window,
11638        cx: &mut Context<Workspace>,
11639    ) {
11640        let project = workspace.project();
11641        let buffers = workspace
11642            .active_item(cx)
11643            .and_then(|item| item.act_as::<Editor>(cx))
11644            .map_or(HashSet::default(), |editor| {
11645                editor.read(cx).buffer.read(cx).all_buffers()
11646            });
11647        project.update(cx, |project, cx| {
11648            project.cancel_language_server_work_for_buffers(buffers, cx);
11649        });
11650    }
11651
11652    fn show_character_palette(
11653        &mut self,
11654        _: &ShowCharacterPalette,
11655        window: &mut Window,
11656        _: &mut Context<Self>,
11657    ) {
11658        window.show_character_palette();
11659    }
11660
11661    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11662        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11663            let buffer = self.buffer.read(cx).snapshot(cx);
11664            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11665            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11666            let is_valid = buffer
11667                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11668                .any(|entry| {
11669                    entry.diagnostic.is_primary
11670                        && !entry.range.is_empty()
11671                        && entry.range.start == primary_range_start
11672                        && entry.diagnostic.message == active_diagnostics.primary_message
11673                });
11674
11675            if is_valid != active_diagnostics.is_valid {
11676                active_diagnostics.is_valid = is_valid;
11677                let mut new_styles = HashMap::default();
11678                for (block_id, diagnostic) in &active_diagnostics.blocks {
11679                    new_styles.insert(
11680                        *block_id,
11681                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11682                    );
11683                }
11684                self.display_map.update(cx, |display_map, _cx| {
11685                    display_map.replace_blocks(new_styles)
11686                });
11687            }
11688        }
11689    }
11690
11691    fn activate_diagnostics(
11692        &mut self,
11693        buffer_id: BufferId,
11694        group_id: usize,
11695        window: &mut Window,
11696        cx: &mut Context<Self>,
11697    ) {
11698        self.dismiss_diagnostics(cx);
11699        let snapshot = self.snapshot(window, cx);
11700        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11701            let buffer = self.buffer.read(cx).snapshot(cx);
11702
11703            let mut primary_range = None;
11704            let mut primary_message = None;
11705            let diagnostic_group = buffer
11706                .diagnostic_group(buffer_id, group_id)
11707                .filter_map(|entry| {
11708                    let start = entry.range.start;
11709                    let end = entry.range.end;
11710                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11711                        && (start.row == end.row
11712                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11713                    {
11714                        return None;
11715                    }
11716                    if entry.diagnostic.is_primary {
11717                        primary_range = Some(entry.range.clone());
11718                        primary_message = Some(entry.diagnostic.message.clone());
11719                    }
11720                    Some(entry)
11721                })
11722                .collect::<Vec<_>>();
11723            let primary_range = primary_range?;
11724            let primary_message = primary_message?;
11725
11726            let blocks = display_map
11727                .insert_blocks(
11728                    diagnostic_group.iter().map(|entry| {
11729                        let diagnostic = entry.diagnostic.clone();
11730                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11731                        BlockProperties {
11732                            style: BlockStyle::Fixed,
11733                            placement: BlockPlacement::Below(
11734                                buffer.anchor_after(entry.range.start),
11735                            ),
11736                            height: message_height,
11737                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11738                            priority: 0,
11739                        }
11740                    }),
11741                    cx,
11742                )
11743                .into_iter()
11744                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11745                .collect();
11746
11747            Some(ActiveDiagnosticGroup {
11748                primary_range: buffer.anchor_before(primary_range.start)
11749                    ..buffer.anchor_after(primary_range.end),
11750                primary_message,
11751                group_id,
11752                blocks,
11753                is_valid: true,
11754            })
11755        });
11756    }
11757
11758    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11759        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11760            self.display_map.update(cx, |display_map, cx| {
11761                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11762            });
11763            cx.notify();
11764        }
11765    }
11766
11767    pub fn set_selections_from_remote(
11768        &mut self,
11769        selections: Vec<Selection<Anchor>>,
11770        pending_selection: Option<Selection<Anchor>>,
11771        window: &mut Window,
11772        cx: &mut Context<Self>,
11773    ) {
11774        let old_cursor_position = self.selections.newest_anchor().head();
11775        self.selections.change_with(cx, |s| {
11776            s.select_anchors(selections);
11777            if let Some(pending_selection) = pending_selection {
11778                s.set_pending(pending_selection, SelectMode::Character);
11779            } else {
11780                s.clear_pending();
11781            }
11782        });
11783        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11784    }
11785
11786    fn push_to_selection_history(&mut self) {
11787        self.selection_history.push(SelectionHistoryEntry {
11788            selections: self.selections.disjoint_anchors(),
11789            select_next_state: self.select_next_state.clone(),
11790            select_prev_state: self.select_prev_state.clone(),
11791            add_selections_state: self.add_selections_state.clone(),
11792        });
11793    }
11794
11795    pub fn transact(
11796        &mut self,
11797        window: &mut Window,
11798        cx: &mut Context<Self>,
11799        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11800    ) -> Option<TransactionId> {
11801        self.start_transaction_at(Instant::now(), window, cx);
11802        update(self, window, cx);
11803        self.end_transaction_at(Instant::now(), cx)
11804    }
11805
11806    pub fn start_transaction_at(
11807        &mut self,
11808        now: Instant,
11809        window: &mut Window,
11810        cx: &mut Context<Self>,
11811    ) {
11812        self.end_selection(window, cx);
11813        if let Some(tx_id) = self
11814            .buffer
11815            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11816        {
11817            self.selection_history
11818                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11819            cx.emit(EditorEvent::TransactionBegun {
11820                transaction_id: tx_id,
11821            })
11822        }
11823    }
11824
11825    pub fn end_transaction_at(
11826        &mut self,
11827        now: Instant,
11828        cx: &mut Context<Self>,
11829    ) -> Option<TransactionId> {
11830        if let Some(transaction_id) = self
11831            .buffer
11832            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11833        {
11834            if let Some((_, end_selections)) =
11835                self.selection_history.transaction_mut(transaction_id)
11836            {
11837                *end_selections = Some(self.selections.disjoint_anchors());
11838            } else {
11839                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11840            }
11841
11842            cx.emit(EditorEvent::Edited { transaction_id });
11843            Some(transaction_id)
11844        } else {
11845            None
11846        }
11847    }
11848
11849    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11850        if self.selection_mark_mode {
11851            self.change_selections(None, window, cx, |s| {
11852                s.move_with(|_, sel| {
11853                    sel.collapse_to(sel.head(), SelectionGoal::None);
11854                });
11855            })
11856        }
11857        self.selection_mark_mode = true;
11858        cx.notify();
11859    }
11860
11861    pub fn swap_selection_ends(
11862        &mut self,
11863        _: &actions::SwapSelectionEnds,
11864        window: &mut Window,
11865        cx: &mut Context<Self>,
11866    ) {
11867        self.change_selections(None, window, cx, |s| {
11868            s.move_with(|_, sel| {
11869                if sel.start != sel.end {
11870                    sel.reversed = !sel.reversed
11871                }
11872            });
11873        });
11874        self.request_autoscroll(Autoscroll::newest(), cx);
11875        cx.notify();
11876    }
11877
11878    pub fn toggle_fold(
11879        &mut self,
11880        _: &actions::ToggleFold,
11881        window: &mut Window,
11882        cx: &mut Context<Self>,
11883    ) {
11884        if self.is_singleton(cx) {
11885            let selection = self.selections.newest::<Point>(cx);
11886
11887            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11888            let range = if selection.is_empty() {
11889                let point = selection.head().to_display_point(&display_map);
11890                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11891                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11892                    .to_point(&display_map);
11893                start..end
11894            } else {
11895                selection.range()
11896            };
11897            if display_map.folds_in_range(range).next().is_some() {
11898                self.unfold_lines(&Default::default(), window, cx)
11899            } else {
11900                self.fold(&Default::default(), window, cx)
11901            }
11902        } else {
11903            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11904            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11905                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11906                .map(|(snapshot, _, _)| snapshot.remote_id())
11907                .collect();
11908
11909            for buffer_id in buffer_ids {
11910                if self.is_buffer_folded(buffer_id, cx) {
11911                    self.unfold_buffer(buffer_id, cx);
11912                } else {
11913                    self.fold_buffer(buffer_id, cx);
11914                }
11915            }
11916        }
11917    }
11918
11919    pub fn toggle_fold_recursive(
11920        &mut self,
11921        _: &actions::ToggleFoldRecursive,
11922        window: &mut Window,
11923        cx: &mut Context<Self>,
11924    ) {
11925        let selection = self.selections.newest::<Point>(cx);
11926
11927        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11928        let range = if selection.is_empty() {
11929            let point = selection.head().to_display_point(&display_map);
11930            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11931            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11932                .to_point(&display_map);
11933            start..end
11934        } else {
11935            selection.range()
11936        };
11937        if display_map.folds_in_range(range).next().is_some() {
11938            self.unfold_recursive(&Default::default(), window, cx)
11939        } else {
11940            self.fold_recursive(&Default::default(), window, cx)
11941        }
11942    }
11943
11944    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11945        if self.is_singleton(cx) {
11946            let mut to_fold = Vec::new();
11947            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11948            let selections = self.selections.all_adjusted(cx);
11949
11950            for selection in selections {
11951                let range = selection.range().sorted();
11952                let buffer_start_row = range.start.row;
11953
11954                if range.start.row != range.end.row {
11955                    let mut found = false;
11956                    let mut row = range.start.row;
11957                    while row <= range.end.row {
11958                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11959                        {
11960                            found = true;
11961                            row = crease.range().end.row + 1;
11962                            to_fold.push(crease);
11963                        } else {
11964                            row += 1
11965                        }
11966                    }
11967                    if found {
11968                        continue;
11969                    }
11970                }
11971
11972                for row in (0..=range.start.row).rev() {
11973                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11974                        if crease.range().end.row >= buffer_start_row {
11975                            to_fold.push(crease);
11976                            if row <= range.start.row {
11977                                break;
11978                            }
11979                        }
11980                    }
11981                }
11982            }
11983
11984            self.fold_creases(to_fold, true, window, cx);
11985        } else {
11986            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11987
11988            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11989                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11990                .map(|(snapshot, _, _)| snapshot.remote_id())
11991                .collect();
11992            for buffer_id in buffer_ids {
11993                self.fold_buffer(buffer_id, cx);
11994            }
11995        }
11996    }
11997
11998    fn fold_at_level(
11999        &mut self,
12000        fold_at: &FoldAtLevel,
12001        window: &mut Window,
12002        cx: &mut Context<Self>,
12003    ) {
12004        if !self.buffer.read(cx).is_singleton() {
12005            return;
12006        }
12007
12008        let fold_at_level = fold_at.0;
12009        let snapshot = self.buffer.read(cx).snapshot(cx);
12010        let mut to_fold = Vec::new();
12011        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12012
12013        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12014            while start_row < end_row {
12015                match self
12016                    .snapshot(window, cx)
12017                    .crease_for_buffer_row(MultiBufferRow(start_row))
12018                {
12019                    Some(crease) => {
12020                        let nested_start_row = crease.range().start.row + 1;
12021                        let nested_end_row = crease.range().end.row;
12022
12023                        if current_level < fold_at_level {
12024                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12025                        } else if current_level == fold_at_level {
12026                            to_fold.push(crease);
12027                        }
12028
12029                        start_row = nested_end_row + 1;
12030                    }
12031                    None => start_row += 1,
12032                }
12033            }
12034        }
12035
12036        self.fold_creases(to_fold, true, window, cx);
12037    }
12038
12039    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12040        if self.buffer.read(cx).is_singleton() {
12041            let mut fold_ranges = Vec::new();
12042            let snapshot = self.buffer.read(cx).snapshot(cx);
12043
12044            for row in 0..snapshot.max_row().0 {
12045                if let Some(foldable_range) = self
12046                    .snapshot(window, cx)
12047                    .crease_for_buffer_row(MultiBufferRow(row))
12048                {
12049                    fold_ranges.push(foldable_range);
12050                }
12051            }
12052
12053            self.fold_creases(fold_ranges, true, window, cx);
12054        } else {
12055            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12056                editor
12057                    .update_in(&mut cx, |editor, _, cx| {
12058                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12059                            editor.fold_buffer(buffer_id, cx);
12060                        }
12061                    })
12062                    .ok();
12063            });
12064        }
12065    }
12066
12067    pub fn fold_function_bodies(
12068        &mut self,
12069        _: &actions::FoldFunctionBodies,
12070        window: &mut Window,
12071        cx: &mut Context<Self>,
12072    ) {
12073        let snapshot = self.buffer.read(cx).snapshot(cx);
12074
12075        let ranges = snapshot
12076            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12077            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12078            .collect::<Vec<_>>();
12079
12080        let creases = ranges
12081            .into_iter()
12082            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12083            .collect();
12084
12085        self.fold_creases(creases, true, window, cx);
12086    }
12087
12088    pub fn fold_recursive(
12089        &mut self,
12090        _: &actions::FoldRecursive,
12091        window: &mut Window,
12092        cx: &mut Context<Self>,
12093    ) {
12094        let mut to_fold = Vec::new();
12095        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12096        let selections = self.selections.all_adjusted(cx);
12097
12098        for selection in selections {
12099            let range = selection.range().sorted();
12100            let buffer_start_row = range.start.row;
12101
12102            if range.start.row != range.end.row {
12103                let mut found = false;
12104                for row in range.start.row..=range.end.row {
12105                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12106                        found = true;
12107                        to_fold.push(crease);
12108                    }
12109                }
12110                if found {
12111                    continue;
12112                }
12113            }
12114
12115            for row in (0..=range.start.row).rev() {
12116                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12117                    if crease.range().end.row >= buffer_start_row {
12118                        to_fold.push(crease);
12119                    } else {
12120                        break;
12121                    }
12122                }
12123            }
12124        }
12125
12126        self.fold_creases(to_fold, true, window, cx);
12127    }
12128
12129    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12130        let buffer_row = fold_at.buffer_row;
12131        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12132
12133        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12134            let autoscroll = self
12135                .selections
12136                .all::<Point>(cx)
12137                .iter()
12138                .any(|selection| crease.range().overlaps(&selection.range()));
12139
12140            self.fold_creases(vec![crease], autoscroll, window, cx);
12141        }
12142    }
12143
12144    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12145        if self.is_singleton(cx) {
12146            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12147            let buffer = &display_map.buffer_snapshot;
12148            let selections = self.selections.all::<Point>(cx);
12149            let ranges = selections
12150                .iter()
12151                .map(|s| {
12152                    let range = s.display_range(&display_map).sorted();
12153                    let mut start = range.start.to_point(&display_map);
12154                    let mut end = range.end.to_point(&display_map);
12155                    start.column = 0;
12156                    end.column = buffer.line_len(MultiBufferRow(end.row));
12157                    start..end
12158                })
12159                .collect::<Vec<_>>();
12160
12161            self.unfold_ranges(&ranges, true, true, cx);
12162        } else {
12163            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12164            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12165                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12166                .map(|(snapshot, _, _)| snapshot.remote_id())
12167                .collect();
12168            for buffer_id in buffer_ids {
12169                self.unfold_buffer(buffer_id, cx);
12170            }
12171        }
12172    }
12173
12174    pub fn unfold_recursive(
12175        &mut self,
12176        _: &UnfoldRecursive,
12177        _window: &mut Window,
12178        cx: &mut Context<Self>,
12179    ) {
12180        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12181        let selections = self.selections.all::<Point>(cx);
12182        let ranges = selections
12183            .iter()
12184            .map(|s| {
12185                let mut range = s.display_range(&display_map).sorted();
12186                *range.start.column_mut() = 0;
12187                *range.end.column_mut() = display_map.line_len(range.end.row());
12188                let start = range.start.to_point(&display_map);
12189                let end = range.end.to_point(&display_map);
12190                start..end
12191            })
12192            .collect::<Vec<_>>();
12193
12194        self.unfold_ranges(&ranges, true, true, cx);
12195    }
12196
12197    pub fn unfold_at(
12198        &mut self,
12199        unfold_at: &UnfoldAt,
12200        _window: &mut Window,
12201        cx: &mut Context<Self>,
12202    ) {
12203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12204
12205        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12206            ..Point::new(
12207                unfold_at.buffer_row.0,
12208                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12209            );
12210
12211        let autoscroll = self
12212            .selections
12213            .all::<Point>(cx)
12214            .iter()
12215            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12216
12217        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12218    }
12219
12220    pub fn unfold_all(
12221        &mut self,
12222        _: &actions::UnfoldAll,
12223        _window: &mut Window,
12224        cx: &mut Context<Self>,
12225    ) {
12226        if self.buffer.read(cx).is_singleton() {
12227            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12228            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12229        } else {
12230            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12231                editor
12232                    .update(&mut cx, |editor, cx| {
12233                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12234                            editor.unfold_buffer(buffer_id, cx);
12235                        }
12236                    })
12237                    .ok();
12238            });
12239        }
12240    }
12241
12242    pub fn fold_selected_ranges(
12243        &mut self,
12244        _: &FoldSelectedRanges,
12245        window: &mut Window,
12246        cx: &mut Context<Self>,
12247    ) {
12248        let selections = self.selections.all::<Point>(cx);
12249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12250        let line_mode = self.selections.line_mode;
12251        let ranges = selections
12252            .into_iter()
12253            .map(|s| {
12254                if line_mode {
12255                    let start = Point::new(s.start.row, 0);
12256                    let end = Point::new(
12257                        s.end.row,
12258                        display_map
12259                            .buffer_snapshot
12260                            .line_len(MultiBufferRow(s.end.row)),
12261                    );
12262                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12263                } else {
12264                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12265                }
12266            })
12267            .collect::<Vec<_>>();
12268        self.fold_creases(ranges, true, window, cx);
12269    }
12270
12271    pub fn fold_ranges<T: ToOffset + Clone>(
12272        &mut self,
12273        ranges: Vec<Range<T>>,
12274        auto_scroll: bool,
12275        window: &mut Window,
12276        cx: &mut Context<Self>,
12277    ) {
12278        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12279        let ranges = ranges
12280            .into_iter()
12281            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12282            .collect::<Vec<_>>();
12283        self.fold_creases(ranges, auto_scroll, window, cx);
12284    }
12285
12286    pub fn fold_creases<T: ToOffset + Clone>(
12287        &mut self,
12288        creases: Vec<Crease<T>>,
12289        auto_scroll: bool,
12290        window: &mut Window,
12291        cx: &mut Context<Self>,
12292    ) {
12293        if creases.is_empty() {
12294            return;
12295        }
12296
12297        let mut buffers_affected = HashSet::default();
12298        let multi_buffer = self.buffer().read(cx);
12299        for crease in &creases {
12300            if let Some((_, buffer, _)) =
12301                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12302            {
12303                buffers_affected.insert(buffer.read(cx).remote_id());
12304            };
12305        }
12306
12307        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12308
12309        if auto_scroll {
12310            self.request_autoscroll(Autoscroll::fit(), cx);
12311        }
12312
12313        cx.notify();
12314
12315        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12316            // Clear diagnostics block when folding a range that contains it.
12317            let snapshot = self.snapshot(window, cx);
12318            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12319                drop(snapshot);
12320                self.active_diagnostics = Some(active_diagnostics);
12321                self.dismiss_diagnostics(cx);
12322            } else {
12323                self.active_diagnostics = Some(active_diagnostics);
12324            }
12325        }
12326
12327        self.scrollbar_marker_state.dirty = true;
12328    }
12329
12330    /// Removes any folds whose ranges intersect any of the given ranges.
12331    pub fn unfold_ranges<T: ToOffset + Clone>(
12332        &mut self,
12333        ranges: &[Range<T>],
12334        inclusive: bool,
12335        auto_scroll: bool,
12336        cx: &mut Context<Self>,
12337    ) {
12338        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12339            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12340        });
12341    }
12342
12343    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12344        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12345            return;
12346        }
12347        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12348        self.display_map
12349            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12350        cx.emit(EditorEvent::BufferFoldToggled {
12351            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12352            folded: true,
12353        });
12354        cx.notify();
12355    }
12356
12357    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12358        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12359            return;
12360        }
12361        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12362        self.display_map.update(cx, |display_map, cx| {
12363            display_map.unfold_buffer(buffer_id, cx);
12364        });
12365        cx.emit(EditorEvent::BufferFoldToggled {
12366            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12367            folded: false,
12368        });
12369        cx.notify();
12370    }
12371
12372    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12373        self.display_map.read(cx).is_buffer_folded(buffer)
12374    }
12375
12376    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12377        self.display_map.read(cx).folded_buffers()
12378    }
12379
12380    /// Removes any folds with the given ranges.
12381    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12382        &mut self,
12383        ranges: &[Range<T>],
12384        type_id: TypeId,
12385        auto_scroll: bool,
12386        cx: &mut Context<Self>,
12387    ) {
12388        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12389            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12390        });
12391    }
12392
12393    fn remove_folds_with<T: ToOffset + Clone>(
12394        &mut self,
12395        ranges: &[Range<T>],
12396        auto_scroll: bool,
12397        cx: &mut Context<Self>,
12398        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12399    ) {
12400        if ranges.is_empty() {
12401            return;
12402        }
12403
12404        let mut buffers_affected = HashSet::default();
12405        let multi_buffer = self.buffer().read(cx);
12406        for range in ranges {
12407            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12408                buffers_affected.insert(buffer.read(cx).remote_id());
12409            };
12410        }
12411
12412        self.display_map.update(cx, update);
12413
12414        if auto_scroll {
12415            self.request_autoscroll(Autoscroll::fit(), cx);
12416        }
12417
12418        cx.notify();
12419        self.scrollbar_marker_state.dirty = true;
12420        self.active_indent_guides_state.dirty = true;
12421    }
12422
12423    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12424        self.display_map.read(cx).fold_placeholder.clone()
12425    }
12426
12427    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12428        self.buffer.update(cx, |buffer, cx| {
12429            buffer.set_all_diff_hunks_expanded(cx);
12430        });
12431    }
12432
12433    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12434        self.distinguish_unstaged_diff_hunks = true;
12435    }
12436
12437    pub fn expand_all_diff_hunks(
12438        &mut self,
12439        _: &ExpandAllHunkDiffs,
12440        _window: &mut Window,
12441        cx: &mut Context<Self>,
12442    ) {
12443        self.buffer.update(cx, |buffer, cx| {
12444            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12445        });
12446    }
12447
12448    pub fn toggle_selected_diff_hunks(
12449        &mut self,
12450        _: &ToggleSelectedDiffHunks,
12451        _window: &mut Window,
12452        cx: &mut Context<Self>,
12453    ) {
12454        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12455        self.toggle_diff_hunks_in_ranges(ranges, cx);
12456    }
12457
12458    fn diff_hunks_in_ranges<'a>(
12459        &'a self,
12460        ranges: &'a [Range<Anchor>],
12461        buffer: &'a MultiBufferSnapshot,
12462    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12463        ranges.iter().flat_map(move |range| {
12464            let end_excerpt_id = range.end.excerpt_id;
12465            let range = range.to_point(buffer);
12466            let mut peek_end = range.end;
12467            if range.end.row < buffer.max_row().0 {
12468                peek_end = Point::new(range.end.row + 1, 0);
12469            }
12470            buffer
12471                .diff_hunks_in_range(range.start..peek_end)
12472                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12473        })
12474    }
12475
12476    pub fn has_stageable_diff_hunks_in_ranges(
12477        &self,
12478        ranges: &[Range<Anchor>],
12479        snapshot: &MultiBufferSnapshot,
12480    ) -> bool {
12481        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12482        hunks.any(|hunk| {
12483            log::debug!("considering {hunk:?}");
12484            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12485        })
12486    }
12487
12488    pub fn toggle_staged_selected_diff_hunks(
12489        &mut self,
12490        _: &ToggleStagedSelectedDiffHunks,
12491        _window: &mut Window,
12492        cx: &mut Context<Self>,
12493    ) {
12494        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12495        self.stage_or_unstage_diff_hunks(&ranges, cx);
12496    }
12497
12498    pub fn stage_or_unstage_diff_hunks(
12499        &mut self,
12500        ranges: &[Range<Anchor>],
12501        cx: &mut Context<Self>,
12502    ) {
12503        let Some(project) = &self.project else {
12504            return;
12505        };
12506        let snapshot = self.buffer.read(cx).snapshot(cx);
12507        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12508
12509        let chunk_by = self
12510            .diff_hunks_in_ranges(&ranges, &snapshot)
12511            .chunk_by(|hunk| hunk.buffer_id);
12512        for (buffer_id, hunks) in &chunk_by {
12513            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12514                log::debug!("no buffer for id");
12515                continue;
12516            };
12517            let buffer = buffer.read(cx).snapshot();
12518            let Some((repo, path)) = project
12519                .read(cx)
12520                .repository_and_path_for_buffer_id(buffer_id, cx)
12521            else {
12522                log::debug!("no git repo for buffer id");
12523                continue;
12524            };
12525            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12526                log::debug!("no diff for buffer id");
12527                continue;
12528            };
12529            let Some(secondary_diff) = diff.secondary_diff() else {
12530                log::debug!("no secondary diff for buffer id");
12531                continue;
12532            };
12533
12534            let edits = diff.secondary_edits_for_stage_or_unstage(
12535                stage,
12536                hunks.map(|hunk| {
12537                    (
12538                        hunk.diff_base_byte_range.clone(),
12539                        hunk.secondary_diff_base_byte_range.clone(),
12540                        hunk.buffer_range.clone(),
12541                    )
12542                }),
12543                &buffer,
12544            );
12545
12546            let index_base = secondary_diff.base_text().map_or_else(
12547                || Rope::from(""),
12548                |snapshot| snapshot.text.as_rope().clone(),
12549            );
12550            let index_buffer = cx.new(|cx| {
12551                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12552            });
12553            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12554                index_buffer.edit(edits, None, cx);
12555                index_buffer.snapshot().as_rope().to_string()
12556            });
12557            let new_index_text = if new_index_text.is_empty()
12558                && (diff.is_single_insertion
12559                    || buffer
12560                        .file()
12561                        .map_or(false, |file| file.disk_state() == DiskState::New))
12562            {
12563                log::debug!("removing from index");
12564                None
12565            } else {
12566                Some(new_index_text)
12567            };
12568
12569            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12570        }
12571    }
12572
12573    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12574        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12575        self.buffer
12576            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12577    }
12578
12579    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12580        self.buffer.update(cx, |buffer, cx| {
12581            let ranges = vec![Anchor::min()..Anchor::max()];
12582            if !buffer.all_diff_hunks_expanded()
12583                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12584            {
12585                buffer.collapse_diff_hunks(ranges, cx);
12586                true
12587            } else {
12588                false
12589            }
12590        })
12591    }
12592
12593    fn toggle_diff_hunks_in_ranges(
12594        &mut self,
12595        ranges: Vec<Range<Anchor>>,
12596        cx: &mut Context<'_, Editor>,
12597    ) {
12598        self.buffer.update(cx, |buffer, cx| {
12599            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12600            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12601        })
12602    }
12603
12604    fn toggle_diff_hunks_in_ranges_narrow(
12605        &mut self,
12606        ranges: Vec<Range<Anchor>>,
12607        cx: &mut Context<'_, Editor>,
12608    ) {
12609        self.buffer.update(cx, |buffer, cx| {
12610            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12611            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12612        })
12613    }
12614
12615    pub(crate) fn apply_all_diff_hunks(
12616        &mut self,
12617        _: &ApplyAllDiffHunks,
12618        window: &mut Window,
12619        cx: &mut Context<Self>,
12620    ) {
12621        let buffers = self.buffer.read(cx).all_buffers();
12622        for branch_buffer in buffers {
12623            branch_buffer.update(cx, |branch_buffer, cx| {
12624                branch_buffer.merge_into_base(Vec::new(), cx);
12625            });
12626        }
12627
12628        if let Some(project) = self.project.clone() {
12629            self.save(true, project, window, cx).detach_and_log_err(cx);
12630        }
12631    }
12632
12633    pub(crate) fn apply_selected_diff_hunks(
12634        &mut self,
12635        _: &ApplyDiffHunk,
12636        window: &mut Window,
12637        cx: &mut Context<Self>,
12638    ) {
12639        let snapshot = self.snapshot(window, cx);
12640        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12641        let mut ranges_by_buffer = HashMap::default();
12642        self.transact(window, cx, |editor, _window, cx| {
12643            for hunk in hunks {
12644                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12645                    ranges_by_buffer
12646                        .entry(buffer.clone())
12647                        .or_insert_with(Vec::new)
12648                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12649                }
12650            }
12651
12652            for (buffer, ranges) in ranges_by_buffer {
12653                buffer.update(cx, |buffer, cx| {
12654                    buffer.merge_into_base(ranges, cx);
12655                });
12656            }
12657        });
12658
12659        if let Some(project) = self.project.clone() {
12660            self.save(true, project, window, cx).detach_and_log_err(cx);
12661        }
12662    }
12663
12664    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12665        if hovered != self.gutter_hovered {
12666            self.gutter_hovered = hovered;
12667            cx.notify();
12668        }
12669    }
12670
12671    pub fn insert_blocks(
12672        &mut self,
12673        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12674        autoscroll: Option<Autoscroll>,
12675        cx: &mut Context<Self>,
12676    ) -> Vec<CustomBlockId> {
12677        let blocks = self
12678            .display_map
12679            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12680        if let Some(autoscroll) = autoscroll {
12681            self.request_autoscroll(autoscroll, cx);
12682        }
12683        cx.notify();
12684        blocks
12685    }
12686
12687    pub fn resize_blocks(
12688        &mut self,
12689        heights: HashMap<CustomBlockId, u32>,
12690        autoscroll: Option<Autoscroll>,
12691        cx: &mut Context<Self>,
12692    ) {
12693        self.display_map
12694            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12695        if let Some(autoscroll) = autoscroll {
12696            self.request_autoscroll(autoscroll, cx);
12697        }
12698        cx.notify();
12699    }
12700
12701    pub fn replace_blocks(
12702        &mut self,
12703        renderers: HashMap<CustomBlockId, RenderBlock>,
12704        autoscroll: Option<Autoscroll>,
12705        cx: &mut Context<Self>,
12706    ) {
12707        self.display_map
12708            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12709        if let Some(autoscroll) = autoscroll {
12710            self.request_autoscroll(autoscroll, cx);
12711        }
12712        cx.notify();
12713    }
12714
12715    pub fn remove_blocks(
12716        &mut self,
12717        block_ids: HashSet<CustomBlockId>,
12718        autoscroll: Option<Autoscroll>,
12719        cx: &mut Context<Self>,
12720    ) {
12721        self.display_map.update(cx, |display_map, cx| {
12722            display_map.remove_blocks(block_ids, cx)
12723        });
12724        if let Some(autoscroll) = autoscroll {
12725            self.request_autoscroll(autoscroll, cx);
12726        }
12727        cx.notify();
12728    }
12729
12730    pub fn row_for_block(
12731        &self,
12732        block_id: CustomBlockId,
12733        cx: &mut Context<Self>,
12734    ) -> Option<DisplayRow> {
12735        self.display_map
12736            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12737    }
12738
12739    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12740        self.focused_block = Some(focused_block);
12741    }
12742
12743    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12744        self.focused_block.take()
12745    }
12746
12747    pub fn insert_creases(
12748        &mut self,
12749        creases: impl IntoIterator<Item = Crease<Anchor>>,
12750        cx: &mut Context<Self>,
12751    ) -> Vec<CreaseId> {
12752        self.display_map
12753            .update(cx, |map, cx| map.insert_creases(creases, cx))
12754    }
12755
12756    pub fn remove_creases(
12757        &mut self,
12758        ids: impl IntoIterator<Item = CreaseId>,
12759        cx: &mut Context<Self>,
12760    ) {
12761        self.display_map
12762            .update(cx, |map, cx| map.remove_creases(ids, cx));
12763    }
12764
12765    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12766        self.display_map
12767            .update(cx, |map, cx| map.snapshot(cx))
12768            .longest_row()
12769    }
12770
12771    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12772        self.display_map
12773            .update(cx, |map, cx| map.snapshot(cx))
12774            .max_point()
12775    }
12776
12777    pub fn text(&self, cx: &App) -> String {
12778        self.buffer.read(cx).read(cx).text()
12779    }
12780
12781    pub fn is_empty(&self, cx: &App) -> bool {
12782        self.buffer.read(cx).read(cx).is_empty()
12783    }
12784
12785    pub fn text_option(&self, cx: &App) -> Option<String> {
12786        let text = self.text(cx);
12787        let text = text.trim();
12788
12789        if text.is_empty() {
12790            return None;
12791        }
12792
12793        Some(text.to_string())
12794    }
12795
12796    pub fn set_text(
12797        &mut self,
12798        text: impl Into<Arc<str>>,
12799        window: &mut Window,
12800        cx: &mut Context<Self>,
12801    ) {
12802        self.transact(window, cx, |this, _, cx| {
12803            this.buffer
12804                .read(cx)
12805                .as_singleton()
12806                .expect("you can only call set_text on editors for singleton buffers")
12807                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12808        });
12809    }
12810
12811    pub fn display_text(&self, cx: &mut App) -> String {
12812        self.display_map
12813            .update(cx, |map, cx| map.snapshot(cx))
12814            .text()
12815    }
12816
12817    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12818        let mut wrap_guides = smallvec::smallvec![];
12819
12820        if self.show_wrap_guides == Some(false) {
12821            return wrap_guides;
12822        }
12823
12824        let settings = self.buffer.read(cx).settings_at(0, cx);
12825        if settings.show_wrap_guides {
12826            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12827                wrap_guides.push((soft_wrap as usize, true));
12828            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12829                wrap_guides.push((soft_wrap as usize, true));
12830            }
12831            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12832        }
12833
12834        wrap_guides
12835    }
12836
12837    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12838        let settings = self.buffer.read(cx).settings_at(0, cx);
12839        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12840        match mode {
12841            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12842                SoftWrap::None
12843            }
12844            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12845            language_settings::SoftWrap::PreferredLineLength => {
12846                SoftWrap::Column(settings.preferred_line_length)
12847            }
12848            language_settings::SoftWrap::Bounded => {
12849                SoftWrap::Bounded(settings.preferred_line_length)
12850            }
12851        }
12852    }
12853
12854    pub fn set_soft_wrap_mode(
12855        &mut self,
12856        mode: language_settings::SoftWrap,
12857
12858        cx: &mut Context<Self>,
12859    ) {
12860        self.soft_wrap_mode_override = Some(mode);
12861        cx.notify();
12862    }
12863
12864    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12865        self.text_style_refinement = Some(style);
12866    }
12867
12868    /// called by the Element so we know what style we were most recently rendered with.
12869    pub(crate) fn set_style(
12870        &mut self,
12871        style: EditorStyle,
12872        window: &mut Window,
12873        cx: &mut Context<Self>,
12874    ) {
12875        let rem_size = window.rem_size();
12876        self.display_map.update(cx, |map, cx| {
12877            map.set_font(
12878                style.text.font(),
12879                style.text.font_size.to_pixels(rem_size),
12880                cx,
12881            )
12882        });
12883        self.style = Some(style);
12884    }
12885
12886    pub fn style(&self) -> Option<&EditorStyle> {
12887        self.style.as_ref()
12888    }
12889
12890    // Called by the element. This method is not designed to be called outside of the editor
12891    // element's layout code because it does not notify when rewrapping is computed synchronously.
12892    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12893        self.display_map
12894            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12895    }
12896
12897    pub fn set_soft_wrap(&mut self) {
12898        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12899    }
12900
12901    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12902        if self.soft_wrap_mode_override.is_some() {
12903            self.soft_wrap_mode_override.take();
12904        } else {
12905            let soft_wrap = match self.soft_wrap_mode(cx) {
12906                SoftWrap::GitDiff => return,
12907                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12908                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12909                    language_settings::SoftWrap::None
12910                }
12911            };
12912            self.soft_wrap_mode_override = Some(soft_wrap);
12913        }
12914        cx.notify();
12915    }
12916
12917    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12918        let Some(workspace) = self.workspace() else {
12919            return;
12920        };
12921        let fs = workspace.read(cx).app_state().fs.clone();
12922        let current_show = TabBarSettings::get_global(cx).show;
12923        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12924            setting.show = Some(!current_show);
12925        });
12926    }
12927
12928    pub fn toggle_indent_guides(
12929        &mut self,
12930        _: &ToggleIndentGuides,
12931        _: &mut Window,
12932        cx: &mut Context<Self>,
12933    ) {
12934        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12935            self.buffer
12936                .read(cx)
12937                .settings_at(0, cx)
12938                .indent_guides
12939                .enabled
12940        });
12941        self.show_indent_guides = Some(!currently_enabled);
12942        cx.notify();
12943    }
12944
12945    fn should_show_indent_guides(&self) -> Option<bool> {
12946        self.show_indent_guides
12947    }
12948
12949    pub fn toggle_line_numbers(
12950        &mut self,
12951        _: &ToggleLineNumbers,
12952        _: &mut Window,
12953        cx: &mut Context<Self>,
12954    ) {
12955        let mut editor_settings = EditorSettings::get_global(cx).clone();
12956        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12957        EditorSettings::override_global(editor_settings, cx);
12958    }
12959
12960    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12961        self.use_relative_line_numbers
12962            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12963    }
12964
12965    pub fn toggle_relative_line_numbers(
12966        &mut self,
12967        _: &ToggleRelativeLineNumbers,
12968        _: &mut Window,
12969        cx: &mut Context<Self>,
12970    ) {
12971        let is_relative = self.should_use_relative_line_numbers(cx);
12972        self.set_relative_line_number(Some(!is_relative), cx)
12973    }
12974
12975    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12976        self.use_relative_line_numbers = is_relative;
12977        cx.notify();
12978    }
12979
12980    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12981        self.show_gutter = show_gutter;
12982        cx.notify();
12983    }
12984
12985    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12986        self.show_scrollbars = show_scrollbars;
12987        cx.notify();
12988    }
12989
12990    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12991        self.show_line_numbers = Some(show_line_numbers);
12992        cx.notify();
12993    }
12994
12995    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12996        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12997        cx.notify();
12998    }
12999
13000    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13001        self.show_code_actions = Some(show_code_actions);
13002        cx.notify();
13003    }
13004
13005    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13006        self.show_runnables = Some(show_runnables);
13007        cx.notify();
13008    }
13009
13010    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13011        if self.display_map.read(cx).masked != masked {
13012            self.display_map.update(cx, |map, _| map.masked = masked);
13013        }
13014        cx.notify()
13015    }
13016
13017    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13018        self.show_wrap_guides = Some(show_wrap_guides);
13019        cx.notify();
13020    }
13021
13022    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13023        self.show_indent_guides = Some(show_indent_guides);
13024        cx.notify();
13025    }
13026
13027    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13028        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13029            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13030                if let Some(dir) = file.abs_path(cx).parent() {
13031                    return Some(dir.to_owned());
13032                }
13033            }
13034
13035            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13036                return Some(project_path.path.to_path_buf());
13037            }
13038        }
13039
13040        None
13041    }
13042
13043    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13044        self.active_excerpt(cx)?
13045            .1
13046            .read(cx)
13047            .file()
13048            .and_then(|f| f.as_local())
13049    }
13050
13051    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13052        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13053            let buffer = buffer.read(cx);
13054            if let Some(project_path) = buffer.project_path(cx) {
13055                let project = self.project.as_ref()?.read(cx);
13056                project.absolute_path(&project_path, cx)
13057            } else {
13058                buffer
13059                    .file()
13060                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13061            }
13062        })
13063    }
13064
13065    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13066        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13067            let project_path = buffer.read(cx).project_path(cx)?;
13068            let project = self.project.as_ref()?.read(cx);
13069            let entry = project.entry_for_path(&project_path, cx)?;
13070            let path = entry.path.to_path_buf();
13071            Some(path)
13072        })
13073    }
13074
13075    pub fn reveal_in_finder(
13076        &mut self,
13077        _: &RevealInFileManager,
13078        _window: &mut Window,
13079        cx: &mut Context<Self>,
13080    ) {
13081        if let Some(target) = self.target_file(cx) {
13082            cx.reveal_path(&target.abs_path(cx));
13083        }
13084    }
13085
13086    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13087        if let Some(path) = self.target_file_abs_path(cx) {
13088            if let Some(path) = path.to_str() {
13089                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13090            }
13091        }
13092    }
13093
13094    pub fn copy_relative_path(
13095        &mut self,
13096        _: &CopyRelativePath,
13097        _window: &mut Window,
13098        cx: &mut Context<Self>,
13099    ) {
13100        if let Some(path) = self.target_file_path(cx) {
13101            if let Some(path) = path.to_str() {
13102                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13103            }
13104        }
13105    }
13106
13107    pub fn copy_file_name_without_extension(
13108        &mut self,
13109        _: &CopyFileNameWithoutExtension,
13110        _: &mut Window,
13111        cx: &mut Context<Self>,
13112    ) {
13113        if let Some(file) = self.target_file(cx) {
13114            if let Some(file_stem) = file.path().file_stem() {
13115                if let Some(name) = file_stem.to_str() {
13116                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13117                }
13118            }
13119        }
13120    }
13121
13122    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13123        if let Some(file) = self.target_file(cx) {
13124            if let Some(file_name) = file.path().file_name() {
13125                if let Some(name) = file_name.to_str() {
13126                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13127                }
13128            }
13129        }
13130    }
13131
13132    pub fn toggle_git_blame(
13133        &mut self,
13134        _: &ToggleGitBlame,
13135        window: &mut Window,
13136        cx: &mut Context<Self>,
13137    ) {
13138        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13139
13140        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13141            self.start_git_blame(true, window, cx);
13142        }
13143
13144        cx.notify();
13145    }
13146
13147    pub fn toggle_git_blame_inline(
13148        &mut self,
13149        _: &ToggleGitBlameInline,
13150        window: &mut Window,
13151        cx: &mut Context<Self>,
13152    ) {
13153        self.toggle_git_blame_inline_internal(true, window, cx);
13154        cx.notify();
13155    }
13156
13157    pub fn git_blame_inline_enabled(&self) -> bool {
13158        self.git_blame_inline_enabled
13159    }
13160
13161    pub fn toggle_selection_menu(
13162        &mut self,
13163        _: &ToggleSelectionMenu,
13164        _: &mut Window,
13165        cx: &mut Context<Self>,
13166    ) {
13167        self.show_selection_menu = self
13168            .show_selection_menu
13169            .map(|show_selections_menu| !show_selections_menu)
13170            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13171
13172        cx.notify();
13173    }
13174
13175    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13176        self.show_selection_menu
13177            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13178    }
13179
13180    fn start_git_blame(
13181        &mut self,
13182        user_triggered: bool,
13183        window: &mut Window,
13184        cx: &mut Context<Self>,
13185    ) {
13186        if let Some(project) = self.project.as_ref() {
13187            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13188                return;
13189            };
13190
13191            if buffer.read(cx).file().is_none() {
13192                return;
13193            }
13194
13195            let focused = self.focus_handle(cx).contains_focused(window, cx);
13196
13197            let project = project.clone();
13198            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13199            self.blame_subscription =
13200                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13201            self.blame = Some(blame);
13202        }
13203    }
13204
13205    fn toggle_git_blame_inline_internal(
13206        &mut self,
13207        user_triggered: bool,
13208        window: &mut Window,
13209        cx: &mut Context<Self>,
13210    ) {
13211        if self.git_blame_inline_enabled {
13212            self.git_blame_inline_enabled = false;
13213            self.show_git_blame_inline = false;
13214            self.show_git_blame_inline_delay_task.take();
13215        } else {
13216            self.git_blame_inline_enabled = true;
13217            self.start_git_blame_inline(user_triggered, window, cx);
13218        }
13219
13220        cx.notify();
13221    }
13222
13223    fn start_git_blame_inline(
13224        &mut self,
13225        user_triggered: bool,
13226        window: &mut Window,
13227        cx: &mut Context<Self>,
13228    ) {
13229        self.start_git_blame(user_triggered, window, cx);
13230
13231        if ProjectSettings::get_global(cx)
13232            .git
13233            .inline_blame_delay()
13234            .is_some()
13235        {
13236            self.start_inline_blame_timer(window, cx);
13237        } else {
13238            self.show_git_blame_inline = true
13239        }
13240    }
13241
13242    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13243        self.blame.as_ref()
13244    }
13245
13246    pub fn show_git_blame_gutter(&self) -> bool {
13247        self.show_git_blame_gutter
13248    }
13249
13250    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13251        self.show_git_blame_gutter && self.has_blame_entries(cx)
13252    }
13253
13254    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13255        self.show_git_blame_inline
13256            && self.focus_handle.is_focused(window)
13257            && !self.newest_selection_head_on_empty_line(cx)
13258            && self.has_blame_entries(cx)
13259    }
13260
13261    fn has_blame_entries(&self, cx: &App) -> bool {
13262        self.blame()
13263            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13264    }
13265
13266    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13267        let cursor_anchor = self.selections.newest_anchor().head();
13268
13269        let snapshot = self.buffer.read(cx).snapshot(cx);
13270        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13271
13272        snapshot.line_len(buffer_row) == 0
13273    }
13274
13275    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13276        let buffer_and_selection = maybe!({
13277            let selection = self.selections.newest::<Point>(cx);
13278            let selection_range = selection.range();
13279
13280            let multi_buffer = self.buffer().read(cx);
13281            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13282            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13283
13284            let (buffer, range, _) = if selection.reversed {
13285                buffer_ranges.first()
13286            } else {
13287                buffer_ranges.last()
13288            }?;
13289
13290            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13291                ..text::ToPoint::to_point(&range.end, &buffer).row;
13292            Some((
13293                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13294                selection,
13295            ))
13296        });
13297
13298        let Some((buffer, selection)) = buffer_and_selection else {
13299            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13300        };
13301
13302        let Some(project) = self.project.as_ref() else {
13303            return Task::ready(Err(anyhow!("editor does not have project")));
13304        };
13305
13306        project.update(cx, |project, cx| {
13307            project.get_permalink_to_line(&buffer, selection, cx)
13308        })
13309    }
13310
13311    pub fn copy_permalink_to_line(
13312        &mut self,
13313        _: &CopyPermalinkToLine,
13314        window: &mut Window,
13315        cx: &mut Context<Self>,
13316    ) {
13317        let permalink_task = self.get_permalink_to_line(cx);
13318        let workspace = self.workspace();
13319
13320        cx.spawn_in(window, |_, mut cx| async move {
13321            match permalink_task.await {
13322                Ok(permalink) => {
13323                    cx.update(|_, cx| {
13324                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13325                    })
13326                    .ok();
13327                }
13328                Err(err) => {
13329                    let message = format!("Failed to copy permalink: {err}");
13330
13331                    Err::<(), anyhow::Error>(err).log_err();
13332
13333                    if let Some(workspace) = workspace {
13334                        workspace
13335                            .update_in(&mut cx, |workspace, _, cx| {
13336                                struct CopyPermalinkToLine;
13337
13338                                workspace.show_toast(
13339                                    Toast::new(
13340                                        NotificationId::unique::<CopyPermalinkToLine>(),
13341                                        message,
13342                                    ),
13343                                    cx,
13344                                )
13345                            })
13346                            .ok();
13347                    }
13348                }
13349            }
13350        })
13351        .detach();
13352    }
13353
13354    pub fn copy_file_location(
13355        &mut self,
13356        _: &CopyFileLocation,
13357        _: &mut Window,
13358        cx: &mut Context<Self>,
13359    ) {
13360        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13361        if let Some(file) = self.target_file(cx) {
13362            if let Some(path) = file.path().to_str() {
13363                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13364            }
13365        }
13366    }
13367
13368    pub fn open_permalink_to_line(
13369        &mut self,
13370        _: &OpenPermalinkToLine,
13371        window: &mut Window,
13372        cx: &mut Context<Self>,
13373    ) {
13374        let permalink_task = self.get_permalink_to_line(cx);
13375        let workspace = self.workspace();
13376
13377        cx.spawn_in(window, |_, mut cx| async move {
13378            match permalink_task.await {
13379                Ok(permalink) => {
13380                    cx.update(|_, cx| {
13381                        cx.open_url(permalink.as_ref());
13382                    })
13383                    .ok();
13384                }
13385                Err(err) => {
13386                    let message = format!("Failed to open permalink: {err}");
13387
13388                    Err::<(), anyhow::Error>(err).log_err();
13389
13390                    if let Some(workspace) = workspace {
13391                        workspace
13392                            .update(&mut cx, |workspace, cx| {
13393                                struct OpenPermalinkToLine;
13394
13395                                workspace.show_toast(
13396                                    Toast::new(
13397                                        NotificationId::unique::<OpenPermalinkToLine>(),
13398                                        message,
13399                                    ),
13400                                    cx,
13401                                )
13402                            })
13403                            .ok();
13404                    }
13405                }
13406            }
13407        })
13408        .detach();
13409    }
13410
13411    pub fn insert_uuid_v4(
13412        &mut self,
13413        _: &InsertUuidV4,
13414        window: &mut Window,
13415        cx: &mut Context<Self>,
13416    ) {
13417        self.insert_uuid(UuidVersion::V4, window, cx);
13418    }
13419
13420    pub fn insert_uuid_v7(
13421        &mut self,
13422        _: &InsertUuidV7,
13423        window: &mut Window,
13424        cx: &mut Context<Self>,
13425    ) {
13426        self.insert_uuid(UuidVersion::V7, window, cx);
13427    }
13428
13429    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13430        self.transact(window, cx, |this, window, cx| {
13431            let edits = this
13432                .selections
13433                .all::<Point>(cx)
13434                .into_iter()
13435                .map(|selection| {
13436                    let uuid = match version {
13437                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13438                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13439                    };
13440
13441                    (selection.range(), uuid.to_string())
13442                });
13443            this.edit(edits, cx);
13444            this.refresh_inline_completion(true, false, window, cx);
13445        });
13446    }
13447
13448    pub fn open_selections_in_multibuffer(
13449        &mut self,
13450        _: &OpenSelectionsInMultibuffer,
13451        window: &mut Window,
13452        cx: &mut Context<Self>,
13453    ) {
13454        let multibuffer = self.buffer.read(cx);
13455
13456        let Some(buffer) = multibuffer.as_singleton() else {
13457            return;
13458        };
13459
13460        let Some(workspace) = self.workspace() else {
13461            return;
13462        };
13463
13464        let locations = self
13465            .selections
13466            .disjoint_anchors()
13467            .iter()
13468            .map(|range| Location {
13469                buffer: buffer.clone(),
13470                range: range.start.text_anchor..range.end.text_anchor,
13471            })
13472            .collect::<Vec<_>>();
13473
13474        let title = multibuffer.title(cx).to_string();
13475
13476        cx.spawn_in(window, |_, mut cx| async move {
13477            workspace.update_in(&mut cx, |workspace, window, cx| {
13478                Self::open_locations_in_multibuffer(
13479                    workspace,
13480                    locations,
13481                    format!("Selections for '{title}'"),
13482                    false,
13483                    MultibufferSelectionMode::All,
13484                    window,
13485                    cx,
13486                );
13487            })
13488        })
13489        .detach();
13490    }
13491
13492    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13493    /// last highlight added will be used.
13494    ///
13495    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13496    pub fn highlight_rows<T: 'static>(
13497        &mut self,
13498        range: Range<Anchor>,
13499        color: Hsla,
13500        should_autoscroll: bool,
13501        cx: &mut Context<Self>,
13502    ) {
13503        let snapshot = self.buffer().read(cx).snapshot(cx);
13504        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13505        let ix = row_highlights.binary_search_by(|highlight| {
13506            Ordering::Equal
13507                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13508                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13509        });
13510
13511        if let Err(mut ix) = ix {
13512            let index = post_inc(&mut self.highlight_order);
13513
13514            // If this range intersects with the preceding highlight, then merge it with
13515            // the preceding highlight. Otherwise insert a new highlight.
13516            let mut merged = false;
13517            if ix > 0 {
13518                let prev_highlight = &mut row_highlights[ix - 1];
13519                if prev_highlight
13520                    .range
13521                    .end
13522                    .cmp(&range.start, &snapshot)
13523                    .is_ge()
13524                {
13525                    ix -= 1;
13526                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13527                        prev_highlight.range.end = range.end;
13528                    }
13529                    merged = true;
13530                    prev_highlight.index = index;
13531                    prev_highlight.color = color;
13532                    prev_highlight.should_autoscroll = should_autoscroll;
13533                }
13534            }
13535
13536            if !merged {
13537                row_highlights.insert(
13538                    ix,
13539                    RowHighlight {
13540                        range: range.clone(),
13541                        index,
13542                        color,
13543                        should_autoscroll,
13544                    },
13545                );
13546            }
13547
13548            // If any of the following highlights intersect with this one, merge them.
13549            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13550                let highlight = &row_highlights[ix];
13551                if next_highlight
13552                    .range
13553                    .start
13554                    .cmp(&highlight.range.end, &snapshot)
13555                    .is_le()
13556                {
13557                    if next_highlight
13558                        .range
13559                        .end
13560                        .cmp(&highlight.range.end, &snapshot)
13561                        .is_gt()
13562                    {
13563                        row_highlights[ix].range.end = next_highlight.range.end;
13564                    }
13565                    row_highlights.remove(ix + 1);
13566                } else {
13567                    break;
13568                }
13569            }
13570        }
13571    }
13572
13573    /// Remove any highlighted row ranges of the given type that intersect the
13574    /// given ranges.
13575    pub fn remove_highlighted_rows<T: 'static>(
13576        &mut self,
13577        ranges_to_remove: Vec<Range<Anchor>>,
13578        cx: &mut Context<Self>,
13579    ) {
13580        let snapshot = self.buffer().read(cx).snapshot(cx);
13581        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13582        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13583        row_highlights.retain(|highlight| {
13584            while let Some(range_to_remove) = ranges_to_remove.peek() {
13585                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13586                    Ordering::Less | Ordering::Equal => {
13587                        ranges_to_remove.next();
13588                    }
13589                    Ordering::Greater => {
13590                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13591                            Ordering::Less | Ordering::Equal => {
13592                                return false;
13593                            }
13594                            Ordering::Greater => break,
13595                        }
13596                    }
13597                }
13598            }
13599
13600            true
13601        })
13602    }
13603
13604    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13605    pub fn clear_row_highlights<T: 'static>(&mut self) {
13606        self.highlighted_rows.remove(&TypeId::of::<T>());
13607    }
13608
13609    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13610    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13611        self.highlighted_rows
13612            .get(&TypeId::of::<T>())
13613            .map_or(&[] as &[_], |vec| vec.as_slice())
13614            .iter()
13615            .map(|highlight| (highlight.range.clone(), highlight.color))
13616    }
13617
13618    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13619    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13620    /// Allows to ignore certain kinds of highlights.
13621    pub fn highlighted_display_rows(
13622        &self,
13623        window: &mut Window,
13624        cx: &mut App,
13625    ) -> BTreeMap<DisplayRow, Background> {
13626        let snapshot = self.snapshot(window, cx);
13627        let mut used_highlight_orders = HashMap::default();
13628        self.highlighted_rows
13629            .iter()
13630            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13631            .fold(
13632                BTreeMap::<DisplayRow, Background>::new(),
13633                |mut unique_rows, highlight| {
13634                    let start = highlight.range.start.to_display_point(&snapshot);
13635                    let end = highlight.range.end.to_display_point(&snapshot);
13636                    let start_row = start.row().0;
13637                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13638                        && end.column() == 0
13639                    {
13640                        end.row().0.saturating_sub(1)
13641                    } else {
13642                        end.row().0
13643                    };
13644                    for row in start_row..=end_row {
13645                        let used_index =
13646                            used_highlight_orders.entry(row).or_insert(highlight.index);
13647                        if highlight.index >= *used_index {
13648                            *used_index = highlight.index;
13649                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13650                        }
13651                    }
13652                    unique_rows
13653                },
13654            )
13655    }
13656
13657    pub fn highlighted_display_row_for_autoscroll(
13658        &self,
13659        snapshot: &DisplaySnapshot,
13660    ) -> Option<DisplayRow> {
13661        self.highlighted_rows
13662            .values()
13663            .flat_map(|highlighted_rows| highlighted_rows.iter())
13664            .filter_map(|highlight| {
13665                if highlight.should_autoscroll {
13666                    Some(highlight.range.start.to_display_point(snapshot).row())
13667                } else {
13668                    None
13669                }
13670            })
13671            .min()
13672    }
13673
13674    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13675        self.highlight_background::<SearchWithinRange>(
13676            ranges,
13677            |colors| colors.editor_document_highlight_read_background,
13678            cx,
13679        )
13680    }
13681
13682    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13683        self.breadcrumb_header = Some(new_header);
13684    }
13685
13686    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13687        self.clear_background_highlights::<SearchWithinRange>(cx);
13688    }
13689
13690    pub fn highlight_background<T: 'static>(
13691        &mut self,
13692        ranges: &[Range<Anchor>],
13693        color_fetcher: fn(&ThemeColors) -> Hsla,
13694        cx: &mut Context<Self>,
13695    ) {
13696        self.background_highlights
13697            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13698        self.scrollbar_marker_state.dirty = true;
13699        cx.notify();
13700    }
13701
13702    pub fn clear_background_highlights<T: 'static>(
13703        &mut self,
13704        cx: &mut Context<Self>,
13705    ) -> Option<BackgroundHighlight> {
13706        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13707        if !text_highlights.1.is_empty() {
13708            self.scrollbar_marker_state.dirty = true;
13709            cx.notify();
13710        }
13711        Some(text_highlights)
13712    }
13713
13714    pub fn highlight_gutter<T: 'static>(
13715        &mut self,
13716        ranges: &[Range<Anchor>],
13717        color_fetcher: fn(&App) -> Hsla,
13718        cx: &mut Context<Self>,
13719    ) {
13720        self.gutter_highlights
13721            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13722        cx.notify();
13723    }
13724
13725    pub fn clear_gutter_highlights<T: 'static>(
13726        &mut self,
13727        cx: &mut Context<Self>,
13728    ) -> Option<GutterHighlight> {
13729        cx.notify();
13730        self.gutter_highlights.remove(&TypeId::of::<T>())
13731    }
13732
13733    #[cfg(feature = "test-support")]
13734    pub fn all_text_background_highlights(
13735        &self,
13736        window: &mut Window,
13737        cx: &mut Context<Self>,
13738    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13739        let snapshot = self.snapshot(window, cx);
13740        let buffer = &snapshot.buffer_snapshot;
13741        let start = buffer.anchor_before(0);
13742        let end = buffer.anchor_after(buffer.len());
13743        let theme = cx.theme().colors();
13744        self.background_highlights_in_range(start..end, &snapshot, theme)
13745    }
13746
13747    #[cfg(feature = "test-support")]
13748    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13749        let snapshot = self.buffer().read(cx).snapshot(cx);
13750
13751        let highlights = self
13752            .background_highlights
13753            .get(&TypeId::of::<items::BufferSearchHighlights>());
13754
13755        if let Some((_color, ranges)) = highlights {
13756            ranges
13757                .iter()
13758                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13759                .collect_vec()
13760        } else {
13761            vec![]
13762        }
13763    }
13764
13765    fn document_highlights_for_position<'a>(
13766        &'a self,
13767        position: Anchor,
13768        buffer: &'a MultiBufferSnapshot,
13769    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13770        let read_highlights = self
13771            .background_highlights
13772            .get(&TypeId::of::<DocumentHighlightRead>())
13773            .map(|h| &h.1);
13774        let write_highlights = self
13775            .background_highlights
13776            .get(&TypeId::of::<DocumentHighlightWrite>())
13777            .map(|h| &h.1);
13778        let left_position = position.bias_left(buffer);
13779        let right_position = position.bias_right(buffer);
13780        read_highlights
13781            .into_iter()
13782            .chain(write_highlights)
13783            .flat_map(move |ranges| {
13784                let start_ix = match ranges.binary_search_by(|probe| {
13785                    let cmp = probe.end.cmp(&left_position, buffer);
13786                    if cmp.is_ge() {
13787                        Ordering::Greater
13788                    } else {
13789                        Ordering::Less
13790                    }
13791                }) {
13792                    Ok(i) | Err(i) => i,
13793                };
13794
13795                ranges[start_ix..]
13796                    .iter()
13797                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13798            })
13799    }
13800
13801    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13802        self.background_highlights
13803            .get(&TypeId::of::<T>())
13804            .map_or(false, |(_, highlights)| !highlights.is_empty())
13805    }
13806
13807    pub fn background_highlights_in_range(
13808        &self,
13809        search_range: Range<Anchor>,
13810        display_snapshot: &DisplaySnapshot,
13811        theme: &ThemeColors,
13812    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13813        let mut results = Vec::new();
13814        for (color_fetcher, ranges) in self.background_highlights.values() {
13815            let color = color_fetcher(theme);
13816            let start_ix = match ranges.binary_search_by(|probe| {
13817                let cmp = probe
13818                    .end
13819                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13820                if cmp.is_gt() {
13821                    Ordering::Greater
13822                } else {
13823                    Ordering::Less
13824                }
13825            }) {
13826                Ok(i) | Err(i) => i,
13827            };
13828            for range in &ranges[start_ix..] {
13829                if range
13830                    .start
13831                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13832                    .is_ge()
13833                {
13834                    break;
13835                }
13836
13837                let start = range.start.to_display_point(display_snapshot);
13838                let end = range.end.to_display_point(display_snapshot);
13839                results.push((start..end, color))
13840            }
13841        }
13842        results
13843    }
13844
13845    pub fn background_highlight_row_ranges<T: 'static>(
13846        &self,
13847        search_range: Range<Anchor>,
13848        display_snapshot: &DisplaySnapshot,
13849        count: usize,
13850    ) -> Vec<RangeInclusive<DisplayPoint>> {
13851        let mut results = Vec::new();
13852        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13853            return vec![];
13854        };
13855
13856        let start_ix = match ranges.binary_search_by(|probe| {
13857            let cmp = probe
13858                .end
13859                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13860            if cmp.is_gt() {
13861                Ordering::Greater
13862            } else {
13863                Ordering::Less
13864            }
13865        }) {
13866            Ok(i) | Err(i) => i,
13867        };
13868        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13869            if let (Some(start_display), Some(end_display)) = (start, end) {
13870                results.push(
13871                    start_display.to_display_point(display_snapshot)
13872                        ..=end_display.to_display_point(display_snapshot),
13873                );
13874            }
13875        };
13876        let mut start_row: Option<Point> = None;
13877        let mut end_row: Option<Point> = None;
13878        if ranges.len() > count {
13879            return Vec::new();
13880        }
13881        for range in &ranges[start_ix..] {
13882            if range
13883                .start
13884                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13885                .is_ge()
13886            {
13887                break;
13888            }
13889            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13890            if let Some(current_row) = &end_row {
13891                if end.row == current_row.row {
13892                    continue;
13893                }
13894            }
13895            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13896            if start_row.is_none() {
13897                assert_eq!(end_row, None);
13898                start_row = Some(start);
13899                end_row = Some(end);
13900                continue;
13901            }
13902            if let Some(current_end) = end_row.as_mut() {
13903                if start.row > current_end.row + 1 {
13904                    push_region(start_row, end_row);
13905                    start_row = Some(start);
13906                    end_row = Some(end);
13907                } else {
13908                    // Merge two hunks.
13909                    *current_end = end;
13910                }
13911            } else {
13912                unreachable!();
13913            }
13914        }
13915        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13916        push_region(start_row, end_row);
13917        results
13918    }
13919
13920    pub fn gutter_highlights_in_range(
13921        &self,
13922        search_range: Range<Anchor>,
13923        display_snapshot: &DisplaySnapshot,
13924        cx: &App,
13925    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13926        let mut results = Vec::new();
13927        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13928            let color = color_fetcher(cx);
13929            let start_ix = match ranges.binary_search_by(|probe| {
13930                let cmp = probe
13931                    .end
13932                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13933                if cmp.is_gt() {
13934                    Ordering::Greater
13935                } else {
13936                    Ordering::Less
13937                }
13938            }) {
13939                Ok(i) | Err(i) => i,
13940            };
13941            for range in &ranges[start_ix..] {
13942                if range
13943                    .start
13944                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13945                    .is_ge()
13946                {
13947                    break;
13948                }
13949
13950                let start = range.start.to_display_point(display_snapshot);
13951                let end = range.end.to_display_point(display_snapshot);
13952                results.push((start..end, color))
13953            }
13954        }
13955        results
13956    }
13957
13958    /// Get the text ranges corresponding to the redaction query
13959    pub fn redacted_ranges(
13960        &self,
13961        search_range: Range<Anchor>,
13962        display_snapshot: &DisplaySnapshot,
13963        cx: &App,
13964    ) -> Vec<Range<DisplayPoint>> {
13965        display_snapshot
13966            .buffer_snapshot
13967            .redacted_ranges(search_range, |file| {
13968                if let Some(file) = file {
13969                    file.is_private()
13970                        && EditorSettings::get(
13971                            Some(SettingsLocation {
13972                                worktree_id: file.worktree_id(cx),
13973                                path: file.path().as_ref(),
13974                            }),
13975                            cx,
13976                        )
13977                        .redact_private_values
13978                } else {
13979                    false
13980                }
13981            })
13982            .map(|range| {
13983                range.start.to_display_point(display_snapshot)
13984                    ..range.end.to_display_point(display_snapshot)
13985            })
13986            .collect()
13987    }
13988
13989    pub fn highlight_text<T: 'static>(
13990        &mut self,
13991        ranges: Vec<Range<Anchor>>,
13992        style: HighlightStyle,
13993        cx: &mut Context<Self>,
13994    ) {
13995        self.display_map.update(cx, |map, _| {
13996            map.highlight_text(TypeId::of::<T>(), ranges, style)
13997        });
13998        cx.notify();
13999    }
14000
14001    pub(crate) fn highlight_inlays<T: 'static>(
14002        &mut self,
14003        highlights: Vec<InlayHighlight>,
14004        style: HighlightStyle,
14005        cx: &mut Context<Self>,
14006    ) {
14007        self.display_map.update(cx, |map, _| {
14008            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14009        });
14010        cx.notify();
14011    }
14012
14013    pub fn text_highlights<'a, T: 'static>(
14014        &'a self,
14015        cx: &'a App,
14016    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14017        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14018    }
14019
14020    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14021        let cleared = self
14022            .display_map
14023            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14024        if cleared {
14025            cx.notify();
14026        }
14027    }
14028
14029    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14030        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14031            && self.focus_handle.is_focused(window)
14032    }
14033
14034    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14035        self.show_cursor_when_unfocused = is_enabled;
14036        cx.notify();
14037    }
14038
14039    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14040        self.project
14041            .as_ref()
14042            .map(|project| project.read(cx).lsp_store())
14043    }
14044
14045    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14046        cx.notify();
14047    }
14048
14049    fn on_buffer_event(
14050        &mut self,
14051        multibuffer: &Entity<MultiBuffer>,
14052        event: &multi_buffer::Event,
14053        window: &mut Window,
14054        cx: &mut Context<Self>,
14055    ) {
14056        match event {
14057            multi_buffer::Event::Edited {
14058                singleton_buffer_edited,
14059                edited_buffer: buffer_edited,
14060            } => {
14061                self.scrollbar_marker_state.dirty = true;
14062                self.active_indent_guides_state.dirty = true;
14063                self.refresh_active_diagnostics(cx);
14064                self.refresh_code_actions(window, cx);
14065                if self.has_active_inline_completion() {
14066                    self.update_visible_inline_completion(window, cx);
14067                }
14068                if let Some(buffer) = buffer_edited {
14069                    let buffer_id = buffer.read(cx).remote_id();
14070                    if !self.registered_buffers.contains_key(&buffer_id) {
14071                        if let Some(lsp_store) = self.lsp_store(cx) {
14072                            lsp_store.update(cx, |lsp_store, cx| {
14073                                self.registered_buffers.insert(
14074                                    buffer_id,
14075                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14076                                );
14077                            })
14078                        }
14079                    }
14080                }
14081                cx.emit(EditorEvent::BufferEdited);
14082                cx.emit(SearchEvent::MatchesInvalidated);
14083                if *singleton_buffer_edited {
14084                    if let Some(project) = &self.project {
14085                        let project = project.read(cx);
14086                        #[allow(clippy::mutable_key_type)]
14087                        let languages_affected = multibuffer
14088                            .read(cx)
14089                            .all_buffers()
14090                            .into_iter()
14091                            .filter_map(|buffer| {
14092                                let buffer = buffer.read(cx);
14093                                let language = buffer.language()?;
14094                                if project.is_local()
14095                                    && project
14096                                        .language_servers_for_local_buffer(buffer, cx)
14097                                        .count()
14098                                        == 0
14099                                {
14100                                    None
14101                                } else {
14102                                    Some(language)
14103                                }
14104                            })
14105                            .cloned()
14106                            .collect::<HashSet<_>>();
14107                        if !languages_affected.is_empty() {
14108                            self.refresh_inlay_hints(
14109                                InlayHintRefreshReason::BufferEdited(languages_affected),
14110                                cx,
14111                            );
14112                        }
14113                    }
14114                }
14115
14116                let Some(project) = &self.project else { return };
14117                let (telemetry, is_via_ssh) = {
14118                    let project = project.read(cx);
14119                    let telemetry = project.client().telemetry().clone();
14120                    let is_via_ssh = project.is_via_ssh();
14121                    (telemetry, is_via_ssh)
14122                };
14123                refresh_linked_ranges(self, window, cx);
14124                telemetry.log_edit_event("editor", is_via_ssh);
14125            }
14126            multi_buffer::Event::ExcerptsAdded {
14127                buffer,
14128                predecessor,
14129                excerpts,
14130            } => {
14131                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14132                let buffer_id = buffer.read(cx).remote_id();
14133                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14134                    if let Some(project) = &self.project {
14135                        get_uncommitted_diff_for_buffer(
14136                            project,
14137                            [buffer.clone()],
14138                            self.buffer.clone(),
14139                            cx,
14140                        );
14141                    }
14142                }
14143                cx.emit(EditorEvent::ExcerptsAdded {
14144                    buffer: buffer.clone(),
14145                    predecessor: *predecessor,
14146                    excerpts: excerpts.clone(),
14147                });
14148                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14149            }
14150            multi_buffer::Event::ExcerptsRemoved { ids } => {
14151                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14152                let buffer = self.buffer.read(cx);
14153                self.registered_buffers
14154                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14155                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14156            }
14157            multi_buffer::Event::ExcerptsEdited { ids } => {
14158                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14159            }
14160            multi_buffer::Event::ExcerptsExpanded { ids } => {
14161                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14162                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14163            }
14164            multi_buffer::Event::Reparsed(buffer_id) => {
14165                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14166
14167                cx.emit(EditorEvent::Reparsed(*buffer_id));
14168            }
14169            multi_buffer::Event::DiffHunksToggled => {
14170                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14171            }
14172            multi_buffer::Event::LanguageChanged(buffer_id) => {
14173                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14174                cx.emit(EditorEvent::Reparsed(*buffer_id));
14175                cx.notify();
14176            }
14177            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14178            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14179            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14180                cx.emit(EditorEvent::TitleChanged)
14181            }
14182            // multi_buffer::Event::DiffBaseChanged => {
14183            //     self.scrollbar_marker_state.dirty = true;
14184            //     cx.emit(EditorEvent::DiffBaseChanged);
14185            //     cx.notify();
14186            // }
14187            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14188            multi_buffer::Event::DiagnosticsUpdated => {
14189                self.refresh_active_diagnostics(cx);
14190                self.scrollbar_marker_state.dirty = true;
14191                cx.notify();
14192            }
14193            _ => {}
14194        };
14195    }
14196
14197    fn on_display_map_changed(
14198        &mut self,
14199        _: Entity<DisplayMap>,
14200        _: &mut Window,
14201        cx: &mut Context<Self>,
14202    ) {
14203        cx.notify();
14204    }
14205
14206    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14207        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14208        self.refresh_inline_completion(true, false, window, cx);
14209        self.refresh_inlay_hints(
14210            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14211                self.selections.newest_anchor().head(),
14212                &self.buffer.read(cx).snapshot(cx),
14213                cx,
14214            )),
14215            cx,
14216        );
14217
14218        let old_cursor_shape = self.cursor_shape;
14219
14220        {
14221            let editor_settings = EditorSettings::get_global(cx);
14222            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14223            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14224            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14225        }
14226
14227        if old_cursor_shape != self.cursor_shape {
14228            cx.emit(EditorEvent::CursorShapeChanged);
14229        }
14230
14231        let project_settings = ProjectSettings::get_global(cx);
14232        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14233
14234        if self.mode == EditorMode::Full {
14235            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14236            if self.git_blame_inline_enabled != inline_blame_enabled {
14237                self.toggle_git_blame_inline_internal(false, window, cx);
14238            }
14239        }
14240
14241        cx.notify();
14242    }
14243
14244    pub fn set_searchable(&mut self, searchable: bool) {
14245        self.searchable = searchable;
14246    }
14247
14248    pub fn searchable(&self) -> bool {
14249        self.searchable
14250    }
14251
14252    fn open_proposed_changes_editor(
14253        &mut self,
14254        _: &OpenProposedChangesEditor,
14255        window: &mut Window,
14256        cx: &mut Context<Self>,
14257    ) {
14258        let Some(workspace) = self.workspace() else {
14259            cx.propagate();
14260            return;
14261        };
14262
14263        let selections = self.selections.all::<usize>(cx);
14264        let multi_buffer = self.buffer.read(cx);
14265        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14266        let mut new_selections_by_buffer = HashMap::default();
14267        for selection in selections {
14268            for (buffer, range, _) in
14269                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14270            {
14271                let mut range = range.to_point(buffer);
14272                range.start.column = 0;
14273                range.end.column = buffer.line_len(range.end.row);
14274                new_selections_by_buffer
14275                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14276                    .or_insert(Vec::new())
14277                    .push(range)
14278            }
14279        }
14280
14281        let proposed_changes_buffers = new_selections_by_buffer
14282            .into_iter()
14283            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14284            .collect::<Vec<_>>();
14285        let proposed_changes_editor = cx.new(|cx| {
14286            ProposedChangesEditor::new(
14287                "Proposed changes",
14288                proposed_changes_buffers,
14289                self.project.clone(),
14290                window,
14291                cx,
14292            )
14293        });
14294
14295        window.defer(cx, move |window, cx| {
14296            workspace.update(cx, |workspace, cx| {
14297                workspace.active_pane().update(cx, |pane, cx| {
14298                    pane.add_item(
14299                        Box::new(proposed_changes_editor),
14300                        true,
14301                        true,
14302                        None,
14303                        window,
14304                        cx,
14305                    );
14306                });
14307            });
14308        });
14309    }
14310
14311    pub fn open_excerpts_in_split(
14312        &mut self,
14313        _: &OpenExcerptsSplit,
14314        window: &mut Window,
14315        cx: &mut Context<Self>,
14316    ) {
14317        self.open_excerpts_common(None, true, window, cx)
14318    }
14319
14320    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14321        self.open_excerpts_common(None, false, window, cx)
14322    }
14323
14324    fn open_excerpts_common(
14325        &mut self,
14326        jump_data: Option<JumpData>,
14327        split: bool,
14328        window: &mut Window,
14329        cx: &mut Context<Self>,
14330    ) {
14331        let Some(workspace) = self.workspace() else {
14332            cx.propagate();
14333            return;
14334        };
14335
14336        if self.buffer.read(cx).is_singleton() {
14337            cx.propagate();
14338            return;
14339        }
14340
14341        let mut new_selections_by_buffer = HashMap::default();
14342        match &jump_data {
14343            Some(JumpData::MultiBufferPoint {
14344                excerpt_id,
14345                position,
14346                anchor,
14347                line_offset_from_top,
14348            }) => {
14349                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14350                if let Some(buffer) = multi_buffer_snapshot
14351                    .buffer_id_for_excerpt(*excerpt_id)
14352                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14353                {
14354                    let buffer_snapshot = buffer.read(cx).snapshot();
14355                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14356                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14357                    } else {
14358                        buffer_snapshot.clip_point(*position, Bias::Left)
14359                    };
14360                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14361                    new_selections_by_buffer.insert(
14362                        buffer,
14363                        (
14364                            vec![jump_to_offset..jump_to_offset],
14365                            Some(*line_offset_from_top),
14366                        ),
14367                    );
14368                }
14369            }
14370            Some(JumpData::MultiBufferRow {
14371                row,
14372                line_offset_from_top,
14373            }) => {
14374                let point = MultiBufferPoint::new(row.0, 0);
14375                if let Some((buffer, buffer_point, _)) =
14376                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14377                {
14378                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14379                    new_selections_by_buffer
14380                        .entry(buffer)
14381                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14382                        .0
14383                        .push(buffer_offset..buffer_offset)
14384                }
14385            }
14386            None => {
14387                let selections = self.selections.all::<usize>(cx);
14388                let multi_buffer = self.buffer.read(cx);
14389                for selection in selections {
14390                    for (buffer, mut range, _) in multi_buffer
14391                        .snapshot(cx)
14392                        .range_to_buffer_ranges(selection.range())
14393                    {
14394                        // When editing branch buffers, jump to the corresponding location
14395                        // in their base buffer.
14396                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14397                        let buffer = buffer_handle.read(cx);
14398                        if let Some(base_buffer) = buffer.base_buffer() {
14399                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14400                            buffer_handle = base_buffer;
14401                        }
14402
14403                        if selection.reversed {
14404                            mem::swap(&mut range.start, &mut range.end);
14405                        }
14406                        new_selections_by_buffer
14407                            .entry(buffer_handle)
14408                            .or_insert((Vec::new(), None))
14409                            .0
14410                            .push(range)
14411                    }
14412                }
14413            }
14414        }
14415
14416        if new_selections_by_buffer.is_empty() {
14417            return;
14418        }
14419
14420        // We defer the pane interaction because we ourselves are a workspace item
14421        // and activating a new item causes the pane to call a method on us reentrantly,
14422        // which panics if we're on the stack.
14423        window.defer(cx, move |window, cx| {
14424            workspace.update(cx, |workspace, cx| {
14425                let pane = if split {
14426                    workspace.adjacent_pane(window, cx)
14427                } else {
14428                    workspace.active_pane().clone()
14429                };
14430
14431                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14432                    let editor = buffer
14433                        .read(cx)
14434                        .file()
14435                        .is_none()
14436                        .then(|| {
14437                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14438                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14439                            // Instead, we try to activate the existing editor in the pane first.
14440                            let (editor, pane_item_index) =
14441                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14442                                    let editor = item.downcast::<Editor>()?;
14443                                    let singleton_buffer =
14444                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14445                                    if singleton_buffer == buffer {
14446                                        Some((editor, i))
14447                                    } else {
14448                                        None
14449                                    }
14450                                })?;
14451                            pane.update(cx, |pane, cx| {
14452                                pane.activate_item(pane_item_index, true, true, window, cx)
14453                            });
14454                            Some(editor)
14455                        })
14456                        .flatten()
14457                        .unwrap_or_else(|| {
14458                            workspace.open_project_item::<Self>(
14459                                pane.clone(),
14460                                buffer,
14461                                true,
14462                                true,
14463                                window,
14464                                cx,
14465                            )
14466                        });
14467
14468                    editor.update(cx, |editor, cx| {
14469                        let autoscroll = match scroll_offset {
14470                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14471                            None => Autoscroll::newest(),
14472                        };
14473                        let nav_history = editor.nav_history.take();
14474                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14475                            s.select_ranges(ranges);
14476                        });
14477                        editor.nav_history = nav_history;
14478                    });
14479                }
14480            })
14481        });
14482    }
14483
14484    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14485        let snapshot = self.buffer.read(cx).read(cx);
14486        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14487        Some(
14488            ranges
14489                .iter()
14490                .map(move |range| {
14491                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14492                })
14493                .collect(),
14494        )
14495    }
14496
14497    fn selection_replacement_ranges(
14498        &self,
14499        range: Range<OffsetUtf16>,
14500        cx: &mut App,
14501    ) -> Vec<Range<OffsetUtf16>> {
14502        let selections = self.selections.all::<OffsetUtf16>(cx);
14503        let newest_selection = selections
14504            .iter()
14505            .max_by_key(|selection| selection.id)
14506            .unwrap();
14507        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14508        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14509        let snapshot = self.buffer.read(cx).read(cx);
14510        selections
14511            .into_iter()
14512            .map(|mut selection| {
14513                selection.start.0 =
14514                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14515                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14516                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14517                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14518            })
14519            .collect()
14520    }
14521
14522    fn report_editor_event(
14523        &self,
14524        event_type: &'static str,
14525        file_extension: Option<String>,
14526        cx: &App,
14527    ) {
14528        if cfg!(any(test, feature = "test-support")) {
14529            return;
14530        }
14531
14532        let Some(project) = &self.project else { return };
14533
14534        // If None, we are in a file without an extension
14535        let file = self
14536            .buffer
14537            .read(cx)
14538            .as_singleton()
14539            .and_then(|b| b.read(cx).file());
14540        let file_extension = file_extension.or(file
14541            .as_ref()
14542            .and_then(|file| Path::new(file.file_name(cx)).extension())
14543            .and_then(|e| e.to_str())
14544            .map(|a| a.to_string()));
14545
14546        let vim_mode = cx
14547            .global::<SettingsStore>()
14548            .raw_user_settings()
14549            .get("vim_mode")
14550            == Some(&serde_json::Value::Bool(true));
14551
14552        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14553        let copilot_enabled = edit_predictions_provider
14554            == language::language_settings::EditPredictionProvider::Copilot;
14555        let copilot_enabled_for_language = self
14556            .buffer
14557            .read(cx)
14558            .settings_at(0, cx)
14559            .show_edit_predictions;
14560
14561        let project = project.read(cx);
14562        telemetry::event!(
14563            event_type,
14564            file_extension,
14565            vim_mode,
14566            copilot_enabled,
14567            copilot_enabled_for_language,
14568            edit_predictions_provider,
14569            is_via_ssh = project.is_via_ssh(),
14570        );
14571    }
14572
14573    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14574    /// with each line being an array of {text, highlight} objects.
14575    fn copy_highlight_json(
14576        &mut self,
14577        _: &CopyHighlightJson,
14578        window: &mut Window,
14579        cx: &mut Context<Self>,
14580    ) {
14581        #[derive(Serialize)]
14582        struct Chunk<'a> {
14583            text: String,
14584            highlight: Option<&'a str>,
14585        }
14586
14587        let snapshot = self.buffer.read(cx).snapshot(cx);
14588        let range = self
14589            .selected_text_range(false, window, cx)
14590            .and_then(|selection| {
14591                if selection.range.is_empty() {
14592                    None
14593                } else {
14594                    Some(selection.range)
14595                }
14596            })
14597            .unwrap_or_else(|| 0..snapshot.len());
14598
14599        let chunks = snapshot.chunks(range, true);
14600        let mut lines = Vec::new();
14601        let mut line: VecDeque<Chunk> = VecDeque::new();
14602
14603        let Some(style) = self.style.as_ref() else {
14604            return;
14605        };
14606
14607        for chunk in chunks {
14608            let highlight = chunk
14609                .syntax_highlight_id
14610                .and_then(|id| id.name(&style.syntax));
14611            let mut chunk_lines = chunk.text.split('\n').peekable();
14612            while let Some(text) = chunk_lines.next() {
14613                let mut merged_with_last_token = false;
14614                if let Some(last_token) = line.back_mut() {
14615                    if last_token.highlight == highlight {
14616                        last_token.text.push_str(text);
14617                        merged_with_last_token = true;
14618                    }
14619                }
14620
14621                if !merged_with_last_token {
14622                    line.push_back(Chunk {
14623                        text: text.into(),
14624                        highlight,
14625                    });
14626                }
14627
14628                if chunk_lines.peek().is_some() {
14629                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14630                        line.pop_front();
14631                    }
14632                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14633                        line.pop_back();
14634                    }
14635
14636                    lines.push(mem::take(&mut line));
14637                }
14638            }
14639        }
14640
14641        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14642            return;
14643        };
14644        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14645    }
14646
14647    pub fn open_context_menu(
14648        &mut self,
14649        _: &OpenContextMenu,
14650        window: &mut Window,
14651        cx: &mut Context<Self>,
14652    ) {
14653        self.request_autoscroll(Autoscroll::newest(), cx);
14654        let position = self.selections.newest_display(cx).start;
14655        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14656    }
14657
14658    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14659        &self.inlay_hint_cache
14660    }
14661
14662    pub fn replay_insert_event(
14663        &mut self,
14664        text: &str,
14665        relative_utf16_range: Option<Range<isize>>,
14666        window: &mut Window,
14667        cx: &mut Context<Self>,
14668    ) {
14669        if !self.input_enabled {
14670            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14671            return;
14672        }
14673        if let Some(relative_utf16_range) = relative_utf16_range {
14674            let selections = self.selections.all::<OffsetUtf16>(cx);
14675            self.change_selections(None, window, cx, |s| {
14676                let new_ranges = selections.into_iter().map(|range| {
14677                    let start = OffsetUtf16(
14678                        range
14679                            .head()
14680                            .0
14681                            .saturating_add_signed(relative_utf16_range.start),
14682                    );
14683                    let end = OffsetUtf16(
14684                        range
14685                            .head()
14686                            .0
14687                            .saturating_add_signed(relative_utf16_range.end),
14688                    );
14689                    start..end
14690                });
14691                s.select_ranges(new_ranges);
14692            });
14693        }
14694
14695        self.handle_input(text, window, cx);
14696    }
14697
14698    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14699        let Some(provider) = self.semantics_provider.as_ref() else {
14700            return false;
14701        };
14702
14703        let mut supports = false;
14704        self.buffer().read(cx).for_each_buffer(|buffer| {
14705            supports |= provider.supports_inlay_hints(buffer, cx);
14706        });
14707        supports
14708    }
14709
14710    pub fn is_focused(&self, window: &Window) -> bool {
14711        self.focus_handle.is_focused(window)
14712    }
14713
14714    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14715        cx.emit(EditorEvent::Focused);
14716
14717        if let Some(descendant) = self
14718            .last_focused_descendant
14719            .take()
14720            .and_then(|descendant| descendant.upgrade())
14721        {
14722            window.focus(&descendant);
14723        } else {
14724            if let Some(blame) = self.blame.as_ref() {
14725                blame.update(cx, GitBlame::focus)
14726            }
14727
14728            self.blink_manager.update(cx, BlinkManager::enable);
14729            self.show_cursor_names(window, cx);
14730            self.buffer.update(cx, |buffer, cx| {
14731                buffer.finalize_last_transaction(cx);
14732                if self.leader_peer_id.is_none() {
14733                    buffer.set_active_selections(
14734                        &self.selections.disjoint_anchors(),
14735                        self.selections.line_mode,
14736                        self.cursor_shape,
14737                        cx,
14738                    );
14739                }
14740            });
14741        }
14742    }
14743
14744    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14745        cx.emit(EditorEvent::FocusedIn)
14746    }
14747
14748    fn handle_focus_out(
14749        &mut self,
14750        event: FocusOutEvent,
14751        _window: &mut Window,
14752        _cx: &mut Context<Self>,
14753    ) {
14754        if event.blurred != self.focus_handle {
14755            self.last_focused_descendant = Some(event.blurred);
14756        }
14757    }
14758
14759    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14760        self.blink_manager.update(cx, BlinkManager::disable);
14761        self.buffer
14762            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14763
14764        if let Some(blame) = self.blame.as_ref() {
14765            blame.update(cx, GitBlame::blur)
14766        }
14767        if !self.hover_state.focused(window, cx) {
14768            hide_hover(self, cx);
14769        }
14770
14771        self.hide_context_menu(window, cx);
14772        self.discard_inline_completion(false, cx);
14773        cx.emit(EditorEvent::Blurred);
14774        cx.notify();
14775    }
14776
14777    pub fn register_action<A: Action>(
14778        &mut self,
14779        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14780    ) -> Subscription {
14781        let id = self.next_editor_action_id.post_inc();
14782        let listener = Arc::new(listener);
14783        self.editor_actions.borrow_mut().insert(
14784            id,
14785            Box::new(move |window, _| {
14786                let listener = listener.clone();
14787                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14788                    let action = action.downcast_ref().unwrap();
14789                    if phase == DispatchPhase::Bubble {
14790                        listener(action, window, cx)
14791                    }
14792                })
14793            }),
14794        );
14795
14796        let editor_actions = self.editor_actions.clone();
14797        Subscription::new(move || {
14798            editor_actions.borrow_mut().remove(&id);
14799        })
14800    }
14801
14802    pub fn file_header_size(&self) -> u32 {
14803        FILE_HEADER_HEIGHT
14804    }
14805
14806    pub fn revert(
14807        &mut self,
14808        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14809        window: &mut Window,
14810        cx: &mut Context<Self>,
14811    ) {
14812        self.buffer().update(cx, |multi_buffer, cx| {
14813            for (buffer_id, changes) in revert_changes {
14814                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14815                    buffer.update(cx, |buffer, cx| {
14816                        buffer.edit(
14817                            changes.into_iter().map(|(range, text)| {
14818                                (range, text.to_string().map(Arc::<str>::from))
14819                            }),
14820                            None,
14821                            cx,
14822                        );
14823                    });
14824                }
14825            }
14826        });
14827        self.change_selections(None, window, cx, |selections| selections.refresh());
14828    }
14829
14830    pub fn to_pixel_point(
14831        &self,
14832        source: multi_buffer::Anchor,
14833        editor_snapshot: &EditorSnapshot,
14834        window: &mut Window,
14835    ) -> Option<gpui::Point<Pixels>> {
14836        let source_point = source.to_display_point(editor_snapshot);
14837        self.display_to_pixel_point(source_point, editor_snapshot, window)
14838    }
14839
14840    pub fn display_to_pixel_point(
14841        &self,
14842        source: DisplayPoint,
14843        editor_snapshot: &EditorSnapshot,
14844        window: &mut Window,
14845    ) -> Option<gpui::Point<Pixels>> {
14846        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14847        let text_layout_details = self.text_layout_details(window);
14848        let scroll_top = text_layout_details
14849            .scroll_anchor
14850            .scroll_position(editor_snapshot)
14851            .y;
14852
14853        if source.row().as_f32() < scroll_top.floor() {
14854            return None;
14855        }
14856        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14857        let source_y = line_height * (source.row().as_f32() - scroll_top);
14858        Some(gpui::Point::new(source_x, source_y))
14859    }
14860
14861    pub fn has_visible_completions_menu(&self) -> bool {
14862        !self.edit_prediction_preview_is_active()
14863            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14864                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14865            })
14866    }
14867
14868    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14869        self.addons
14870            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14871    }
14872
14873    pub fn unregister_addon<T: Addon>(&mut self) {
14874        self.addons.remove(&std::any::TypeId::of::<T>());
14875    }
14876
14877    pub fn addon<T: Addon>(&self) -> Option<&T> {
14878        let type_id = std::any::TypeId::of::<T>();
14879        self.addons
14880            .get(&type_id)
14881            .and_then(|item| item.to_any().downcast_ref::<T>())
14882    }
14883
14884    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14885        let text_layout_details = self.text_layout_details(window);
14886        let style = &text_layout_details.editor_style;
14887        let font_id = window.text_system().resolve_font(&style.text.font());
14888        let font_size = style.text.font_size.to_pixels(window.rem_size());
14889        let line_height = style.text.line_height_in_pixels(window.rem_size());
14890        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14891
14892        gpui::Size::new(em_width, line_height)
14893    }
14894}
14895
14896fn get_uncommitted_diff_for_buffer(
14897    project: &Entity<Project>,
14898    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14899    buffer: Entity<MultiBuffer>,
14900    cx: &mut App,
14901) {
14902    let mut tasks = Vec::new();
14903    project.update(cx, |project, cx| {
14904        for buffer in buffers {
14905            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14906        }
14907    });
14908    cx.spawn(|mut cx| async move {
14909        let diffs = futures::future::join_all(tasks).await;
14910        buffer
14911            .update(&mut cx, |buffer, cx| {
14912                for diff in diffs.into_iter().flatten() {
14913                    buffer.add_diff(diff, cx);
14914                }
14915            })
14916            .ok();
14917    })
14918    .detach();
14919}
14920
14921fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14922    let tab_size = tab_size.get() as usize;
14923    let mut width = offset;
14924
14925    for ch in text.chars() {
14926        width += if ch == '\t' {
14927            tab_size - (width % tab_size)
14928        } else {
14929            1
14930        };
14931    }
14932
14933    width - offset
14934}
14935
14936#[cfg(test)]
14937mod tests {
14938    use super::*;
14939
14940    #[test]
14941    fn test_string_size_with_expanded_tabs() {
14942        let nz = |val| NonZeroU32::new(val).unwrap();
14943        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14944        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14945        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14946        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14947        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14948        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14949        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14950        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14951    }
14952}
14953
14954/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14955struct WordBreakingTokenizer<'a> {
14956    input: &'a str,
14957}
14958
14959impl<'a> WordBreakingTokenizer<'a> {
14960    fn new(input: &'a str) -> Self {
14961        Self { input }
14962    }
14963}
14964
14965fn is_char_ideographic(ch: char) -> bool {
14966    use unicode_script::Script::*;
14967    use unicode_script::UnicodeScript;
14968    matches!(ch.script(), Han | Tangut | Yi)
14969}
14970
14971fn is_grapheme_ideographic(text: &str) -> bool {
14972    text.chars().any(is_char_ideographic)
14973}
14974
14975fn is_grapheme_whitespace(text: &str) -> bool {
14976    text.chars().any(|x| x.is_whitespace())
14977}
14978
14979fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14980    text.chars().next().map_or(false, |ch| {
14981        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14982    })
14983}
14984
14985#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14986struct WordBreakToken<'a> {
14987    token: &'a str,
14988    grapheme_len: usize,
14989    is_whitespace: bool,
14990}
14991
14992impl<'a> Iterator for WordBreakingTokenizer<'a> {
14993    /// Yields a span, the count of graphemes in the token, and whether it was
14994    /// whitespace. Note that it also breaks at word boundaries.
14995    type Item = WordBreakToken<'a>;
14996
14997    fn next(&mut self) -> Option<Self::Item> {
14998        use unicode_segmentation::UnicodeSegmentation;
14999        if self.input.is_empty() {
15000            return None;
15001        }
15002
15003        let mut iter = self.input.graphemes(true).peekable();
15004        let mut offset = 0;
15005        let mut graphemes = 0;
15006        if let Some(first_grapheme) = iter.next() {
15007            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15008            offset += first_grapheme.len();
15009            graphemes += 1;
15010            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15011                if let Some(grapheme) = iter.peek().copied() {
15012                    if should_stay_with_preceding_ideograph(grapheme) {
15013                        offset += grapheme.len();
15014                        graphemes += 1;
15015                    }
15016                }
15017            } else {
15018                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15019                let mut next_word_bound = words.peek().copied();
15020                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15021                    next_word_bound = words.next();
15022                }
15023                while let Some(grapheme) = iter.peek().copied() {
15024                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15025                        break;
15026                    };
15027                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15028                        break;
15029                    };
15030                    offset += grapheme.len();
15031                    graphemes += 1;
15032                    iter.next();
15033                }
15034            }
15035            let token = &self.input[..offset];
15036            self.input = &self.input[offset..];
15037            if is_whitespace {
15038                Some(WordBreakToken {
15039                    token: " ",
15040                    grapheme_len: 1,
15041                    is_whitespace: true,
15042                })
15043            } else {
15044                Some(WordBreakToken {
15045                    token,
15046                    grapheme_len: graphemes,
15047                    is_whitespace: false,
15048                })
15049            }
15050        } else {
15051            None
15052        }
15053    }
15054}
15055
15056#[test]
15057fn test_word_breaking_tokenizer() {
15058    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15059        ("", &[]),
15060        ("  ", &[(" ", 1, true)]),
15061        ("Ʒ", &[("Ʒ", 1, false)]),
15062        ("Ǽ", &[("Ǽ", 1, false)]),
15063        ("", &[("", 1, false)]),
15064        ("⋑⋑", &[("⋑⋑", 2, false)]),
15065        (
15066            "原理,进而",
15067            &[
15068                ("", 1, false),
15069                ("理,", 2, false),
15070                ("", 1, false),
15071                ("", 1, false),
15072            ],
15073        ),
15074        (
15075            "hello world",
15076            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15077        ),
15078        (
15079            "hello, world",
15080            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15081        ),
15082        (
15083            "  hello world",
15084            &[
15085                (" ", 1, true),
15086                ("hello", 5, false),
15087                (" ", 1, true),
15088                ("world", 5, false),
15089            ],
15090        ),
15091        (
15092            "这是什么 \n 钢笔",
15093            &[
15094                ("", 1, false),
15095                ("", 1, false),
15096                ("", 1, false),
15097                ("", 1, false),
15098                (" ", 1, true),
15099                ("", 1, false),
15100                ("", 1, false),
15101            ],
15102        ),
15103        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15104    ];
15105
15106    for (input, result) in tests {
15107        assert_eq!(
15108            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15109            result
15110                .iter()
15111                .copied()
15112                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15113                    token,
15114                    grapheme_len,
15115                    is_whitespace,
15116                })
15117                .collect::<Vec<_>>()
15118        );
15119    }
15120}
15121
15122fn wrap_with_prefix(
15123    line_prefix: String,
15124    unwrapped_text: String,
15125    wrap_column: usize,
15126    tab_size: NonZeroU32,
15127) -> String {
15128    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15129    let mut wrapped_text = String::new();
15130    let mut current_line = line_prefix.clone();
15131
15132    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15133    let mut current_line_len = line_prefix_len;
15134    for WordBreakToken {
15135        token,
15136        grapheme_len,
15137        is_whitespace,
15138    } in tokenizer
15139    {
15140        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15141            wrapped_text.push_str(current_line.trim_end());
15142            wrapped_text.push('\n');
15143            current_line.truncate(line_prefix.len());
15144            current_line_len = line_prefix_len;
15145            if !is_whitespace {
15146                current_line.push_str(token);
15147                current_line_len += grapheme_len;
15148            }
15149        } else if !is_whitespace {
15150            current_line.push_str(token);
15151            current_line_len += grapheme_len;
15152        } else if current_line_len != line_prefix_len {
15153            current_line.push(' ');
15154            current_line_len += 1;
15155        }
15156    }
15157
15158    if !current_line.is_empty() {
15159        wrapped_text.push_str(&current_line);
15160    }
15161    wrapped_text
15162}
15163
15164#[test]
15165fn test_wrap_with_prefix() {
15166    assert_eq!(
15167        wrap_with_prefix(
15168            "# ".to_string(),
15169            "abcdefg".to_string(),
15170            4,
15171            NonZeroU32::new(4).unwrap()
15172        ),
15173        "# abcdefg"
15174    );
15175    assert_eq!(
15176        wrap_with_prefix(
15177            "".to_string(),
15178            "\thello world".to_string(),
15179            8,
15180            NonZeroU32::new(4).unwrap()
15181        ),
15182        "hello\nworld"
15183    );
15184    assert_eq!(
15185        wrap_with_prefix(
15186            "// ".to_string(),
15187            "xx \nyy zz aa bb cc".to_string(),
15188            12,
15189            NonZeroU32::new(4).unwrap()
15190        ),
15191        "// xx yy zz\n// aa bb cc"
15192    );
15193    assert_eq!(
15194        wrap_with_prefix(
15195            String::new(),
15196            "这是什么 \n 钢笔".to_string(),
15197            3,
15198            NonZeroU32::new(4).unwrap()
15199        ),
15200        "这是什\n么 钢\n"
15201    );
15202}
15203
15204pub trait CollaborationHub {
15205    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15206    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15207    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15208}
15209
15210impl CollaborationHub for Entity<Project> {
15211    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15212        self.read(cx).collaborators()
15213    }
15214
15215    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15216        self.read(cx).user_store().read(cx).participant_indices()
15217    }
15218
15219    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15220        let this = self.read(cx);
15221        let user_ids = this.collaborators().values().map(|c| c.user_id);
15222        this.user_store().read_with(cx, |user_store, cx| {
15223            user_store.participant_names(user_ids, cx)
15224        })
15225    }
15226}
15227
15228pub trait SemanticsProvider {
15229    fn hover(
15230        &self,
15231        buffer: &Entity<Buffer>,
15232        position: text::Anchor,
15233        cx: &mut App,
15234    ) -> Option<Task<Vec<project::Hover>>>;
15235
15236    fn inlay_hints(
15237        &self,
15238        buffer_handle: Entity<Buffer>,
15239        range: Range<text::Anchor>,
15240        cx: &mut App,
15241    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15242
15243    fn resolve_inlay_hint(
15244        &self,
15245        hint: InlayHint,
15246        buffer_handle: Entity<Buffer>,
15247        server_id: LanguageServerId,
15248        cx: &mut App,
15249    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15250
15251    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15252
15253    fn document_highlights(
15254        &self,
15255        buffer: &Entity<Buffer>,
15256        position: text::Anchor,
15257        cx: &mut App,
15258    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15259
15260    fn definitions(
15261        &self,
15262        buffer: &Entity<Buffer>,
15263        position: text::Anchor,
15264        kind: GotoDefinitionKind,
15265        cx: &mut App,
15266    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15267
15268    fn range_for_rename(
15269        &self,
15270        buffer: &Entity<Buffer>,
15271        position: text::Anchor,
15272        cx: &mut App,
15273    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15274
15275    fn perform_rename(
15276        &self,
15277        buffer: &Entity<Buffer>,
15278        position: text::Anchor,
15279        new_name: String,
15280        cx: &mut App,
15281    ) -> Option<Task<Result<ProjectTransaction>>>;
15282}
15283
15284pub trait CompletionProvider {
15285    fn completions(
15286        &self,
15287        buffer: &Entity<Buffer>,
15288        buffer_position: text::Anchor,
15289        trigger: CompletionContext,
15290        window: &mut Window,
15291        cx: &mut Context<Editor>,
15292    ) -> Task<Result<Vec<Completion>>>;
15293
15294    fn resolve_completions(
15295        &self,
15296        buffer: Entity<Buffer>,
15297        completion_indices: Vec<usize>,
15298        completions: Rc<RefCell<Box<[Completion]>>>,
15299        cx: &mut Context<Editor>,
15300    ) -> Task<Result<bool>>;
15301
15302    fn apply_additional_edits_for_completion(
15303        &self,
15304        _buffer: Entity<Buffer>,
15305        _completions: Rc<RefCell<Box<[Completion]>>>,
15306        _completion_index: usize,
15307        _push_to_history: bool,
15308        _cx: &mut Context<Editor>,
15309    ) -> Task<Result<Option<language::Transaction>>> {
15310        Task::ready(Ok(None))
15311    }
15312
15313    fn is_completion_trigger(
15314        &self,
15315        buffer: &Entity<Buffer>,
15316        position: language::Anchor,
15317        text: &str,
15318        trigger_in_words: bool,
15319        cx: &mut Context<Editor>,
15320    ) -> bool;
15321
15322    fn sort_completions(&self) -> bool {
15323        true
15324    }
15325}
15326
15327pub trait CodeActionProvider {
15328    fn id(&self) -> Arc<str>;
15329
15330    fn code_actions(
15331        &self,
15332        buffer: &Entity<Buffer>,
15333        range: Range<text::Anchor>,
15334        window: &mut Window,
15335        cx: &mut App,
15336    ) -> Task<Result<Vec<CodeAction>>>;
15337
15338    fn apply_code_action(
15339        &self,
15340        buffer_handle: Entity<Buffer>,
15341        action: CodeAction,
15342        excerpt_id: ExcerptId,
15343        push_to_history: bool,
15344        window: &mut Window,
15345        cx: &mut App,
15346    ) -> Task<Result<ProjectTransaction>>;
15347}
15348
15349impl CodeActionProvider for Entity<Project> {
15350    fn id(&self) -> Arc<str> {
15351        "project".into()
15352    }
15353
15354    fn code_actions(
15355        &self,
15356        buffer: &Entity<Buffer>,
15357        range: Range<text::Anchor>,
15358        _window: &mut Window,
15359        cx: &mut App,
15360    ) -> Task<Result<Vec<CodeAction>>> {
15361        self.update(cx, |project, cx| {
15362            project.code_actions(buffer, range, None, cx)
15363        })
15364    }
15365
15366    fn apply_code_action(
15367        &self,
15368        buffer_handle: Entity<Buffer>,
15369        action: CodeAction,
15370        _excerpt_id: ExcerptId,
15371        push_to_history: bool,
15372        _window: &mut Window,
15373        cx: &mut App,
15374    ) -> Task<Result<ProjectTransaction>> {
15375        self.update(cx, |project, cx| {
15376            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15377        })
15378    }
15379}
15380
15381fn snippet_completions(
15382    project: &Project,
15383    buffer: &Entity<Buffer>,
15384    buffer_position: text::Anchor,
15385    cx: &mut App,
15386) -> Task<Result<Vec<Completion>>> {
15387    let language = buffer.read(cx).language_at(buffer_position);
15388    let language_name = language.as_ref().map(|language| language.lsp_id());
15389    let snippet_store = project.snippets().read(cx);
15390    let snippets = snippet_store.snippets_for(language_name, cx);
15391
15392    if snippets.is_empty() {
15393        return Task::ready(Ok(vec![]));
15394    }
15395    let snapshot = buffer.read(cx).text_snapshot();
15396    let chars: String = snapshot
15397        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15398        .collect();
15399
15400    let scope = language.map(|language| language.default_scope());
15401    let executor = cx.background_executor().clone();
15402
15403    cx.background_executor().spawn(async move {
15404        let classifier = CharClassifier::new(scope).for_completion(true);
15405        let mut last_word = chars
15406            .chars()
15407            .take_while(|c| classifier.is_word(*c))
15408            .collect::<String>();
15409        last_word = last_word.chars().rev().collect();
15410
15411        if last_word.is_empty() {
15412            return Ok(vec![]);
15413        }
15414
15415        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15416        let to_lsp = |point: &text::Anchor| {
15417            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15418            point_to_lsp(end)
15419        };
15420        let lsp_end = to_lsp(&buffer_position);
15421
15422        let candidates = snippets
15423            .iter()
15424            .enumerate()
15425            .flat_map(|(ix, snippet)| {
15426                snippet
15427                    .prefix
15428                    .iter()
15429                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15430            })
15431            .collect::<Vec<StringMatchCandidate>>();
15432
15433        let mut matches = fuzzy::match_strings(
15434            &candidates,
15435            &last_word,
15436            last_word.chars().any(|c| c.is_uppercase()),
15437            100,
15438            &Default::default(),
15439            executor,
15440        )
15441        .await;
15442
15443        // Remove all candidates where the query's start does not match the start of any word in the candidate
15444        if let Some(query_start) = last_word.chars().next() {
15445            matches.retain(|string_match| {
15446                split_words(&string_match.string).any(|word| {
15447                    // Check that the first codepoint of the word as lowercase matches the first
15448                    // codepoint of the query as lowercase
15449                    word.chars()
15450                        .flat_map(|codepoint| codepoint.to_lowercase())
15451                        .zip(query_start.to_lowercase())
15452                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15453                })
15454            });
15455        }
15456
15457        let matched_strings = matches
15458            .into_iter()
15459            .map(|m| m.string)
15460            .collect::<HashSet<_>>();
15461
15462        let result: Vec<Completion> = snippets
15463            .into_iter()
15464            .filter_map(|snippet| {
15465                let matching_prefix = snippet
15466                    .prefix
15467                    .iter()
15468                    .find(|prefix| matched_strings.contains(*prefix))?;
15469                let start = as_offset - last_word.len();
15470                let start = snapshot.anchor_before(start);
15471                let range = start..buffer_position;
15472                let lsp_start = to_lsp(&start);
15473                let lsp_range = lsp::Range {
15474                    start: lsp_start,
15475                    end: lsp_end,
15476                };
15477                Some(Completion {
15478                    old_range: range,
15479                    new_text: snippet.body.clone(),
15480                    resolved: false,
15481                    label: CodeLabel {
15482                        text: matching_prefix.clone(),
15483                        runs: vec![],
15484                        filter_range: 0..matching_prefix.len(),
15485                    },
15486                    server_id: LanguageServerId(usize::MAX),
15487                    documentation: snippet
15488                        .description
15489                        .clone()
15490                        .map(CompletionDocumentation::SingleLine),
15491                    lsp_completion: lsp::CompletionItem {
15492                        label: snippet.prefix.first().unwrap().clone(),
15493                        kind: Some(CompletionItemKind::SNIPPET),
15494                        label_details: snippet.description.as_ref().map(|description| {
15495                            lsp::CompletionItemLabelDetails {
15496                                detail: Some(description.clone()),
15497                                description: None,
15498                            }
15499                        }),
15500                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15501                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15502                            lsp::InsertReplaceEdit {
15503                                new_text: snippet.body.clone(),
15504                                insert: lsp_range,
15505                                replace: lsp_range,
15506                            },
15507                        )),
15508                        filter_text: Some(snippet.body.clone()),
15509                        sort_text: Some(char::MAX.to_string()),
15510                        ..Default::default()
15511                    },
15512                    confirm: None,
15513                })
15514            })
15515            .collect();
15516
15517        Ok(result)
15518    })
15519}
15520
15521impl CompletionProvider for Entity<Project> {
15522    fn completions(
15523        &self,
15524        buffer: &Entity<Buffer>,
15525        buffer_position: text::Anchor,
15526        options: CompletionContext,
15527        _window: &mut Window,
15528        cx: &mut Context<Editor>,
15529    ) -> Task<Result<Vec<Completion>>> {
15530        self.update(cx, |project, cx| {
15531            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15532            let project_completions = project.completions(buffer, buffer_position, options, cx);
15533            cx.background_executor().spawn(async move {
15534                let mut completions = project_completions.await?;
15535                let snippets_completions = snippets.await?;
15536                completions.extend(snippets_completions);
15537                Ok(completions)
15538            })
15539        })
15540    }
15541
15542    fn resolve_completions(
15543        &self,
15544        buffer: Entity<Buffer>,
15545        completion_indices: Vec<usize>,
15546        completions: Rc<RefCell<Box<[Completion]>>>,
15547        cx: &mut Context<Editor>,
15548    ) -> Task<Result<bool>> {
15549        self.update(cx, |project, cx| {
15550            project.lsp_store().update(cx, |lsp_store, cx| {
15551                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15552            })
15553        })
15554    }
15555
15556    fn apply_additional_edits_for_completion(
15557        &self,
15558        buffer: Entity<Buffer>,
15559        completions: Rc<RefCell<Box<[Completion]>>>,
15560        completion_index: usize,
15561        push_to_history: bool,
15562        cx: &mut Context<Editor>,
15563    ) -> Task<Result<Option<language::Transaction>>> {
15564        self.update(cx, |project, cx| {
15565            project.lsp_store().update(cx, |lsp_store, cx| {
15566                lsp_store.apply_additional_edits_for_completion(
15567                    buffer,
15568                    completions,
15569                    completion_index,
15570                    push_to_history,
15571                    cx,
15572                )
15573            })
15574        })
15575    }
15576
15577    fn is_completion_trigger(
15578        &self,
15579        buffer: &Entity<Buffer>,
15580        position: language::Anchor,
15581        text: &str,
15582        trigger_in_words: bool,
15583        cx: &mut Context<Editor>,
15584    ) -> bool {
15585        let mut chars = text.chars();
15586        let char = if let Some(char) = chars.next() {
15587            char
15588        } else {
15589            return false;
15590        };
15591        if chars.next().is_some() {
15592            return false;
15593        }
15594
15595        let buffer = buffer.read(cx);
15596        let snapshot = buffer.snapshot();
15597        if !snapshot.settings_at(position, cx).show_completions_on_input {
15598            return false;
15599        }
15600        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15601        if trigger_in_words && classifier.is_word(char) {
15602            return true;
15603        }
15604
15605        buffer.completion_triggers().contains(text)
15606    }
15607}
15608
15609impl SemanticsProvider for Entity<Project> {
15610    fn hover(
15611        &self,
15612        buffer: &Entity<Buffer>,
15613        position: text::Anchor,
15614        cx: &mut App,
15615    ) -> Option<Task<Vec<project::Hover>>> {
15616        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15617    }
15618
15619    fn document_highlights(
15620        &self,
15621        buffer: &Entity<Buffer>,
15622        position: text::Anchor,
15623        cx: &mut App,
15624    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15625        Some(self.update(cx, |project, cx| {
15626            project.document_highlights(buffer, position, cx)
15627        }))
15628    }
15629
15630    fn definitions(
15631        &self,
15632        buffer: &Entity<Buffer>,
15633        position: text::Anchor,
15634        kind: GotoDefinitionKind,
15635        cx: &mut App,
15636    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15637        Some(self.update(cx, |project, cx| match kind {
15638            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15639            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15640            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15641            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15642        }))
15643    }
15644
15645    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15646        // TODO: make this work for remote projects
15647        self.read(cx)
15648            .language_servers_for_local_buffer(buffer.read(cx), cx)
15649            .any(
15650                |(_, server)| match server.capabilities().inlay_hint_provider {
15651                    Some(lsp::OneOf::Left(enabled)) => enabled,
15652                    Some(lsp::OneOf::Right(_)) => true,
15653                    None => false,
15654                },
15655            )
15656    }
15657
15658    fn inlay_hints(
15659        &self,
15660        buffer_handle: Entity<Buffer>,
15661        range: Range<text::Anchor>,
15662        cx: &mut App,
15663    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15664        Some(self.update(cx, |project, cx| {
15665            project.inlay_hints(buffer_handle, range, cx)
15666        }))
15667    }
15668
15669    fn resolve_inlay_hint(
15670        &self,
15671        hint: InlayHint,
15672        buffer_handle: Entity<Buffer>,
15673        server_id: LanguageServerId,
15674        cx: &mut App,
15675    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15676        Some(self.update(cx, |project, cx| {
15677            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15678        }))
15679    }
15680
15681    fn range_for_rename(
15682        &self,
15683        buffer: &Entity<Buffer>,
15684        position: text::Anchor,
15685        cx: &mut App,
15686    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15687        Some(self.update(cx, |project, cx| {
15688            let buffer = buffer.clone();
15689            let task = project.prepare_rename(buffer.clone(), position, cx);
15690            cx.spawn(|_, mut cx| async move {
15691                Ok(match task.await? {
15692                    PrepareRenameResponse::Success(range) => Some(range),
15693                    PrepareRenameResponse::InvalidPosition => None,
15694                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15695                        // Fallback on using TreeSitter info to determine identifier range
15696                        buffer.update(&mut cx, |buffer, _| {
15697                            let snapshot = buffer.snapshot();
15698                            let (range, kind) = snapshot.surrounding_word(position);
15699                            if kind != Some(CharKind::Word) {
15700                                return None;
15701                            }
15702                            Some(
15703                                snapshot.anchor_before(range.start)
15704                                    ..snapshot.anchor_after(range.end),
15705                            )
15706                        })?
15707                    }
15708                })
15709            })
15710        }))
15711    }
15712
15713    fn perform_rename(
15714        &self,
15715        buffer: &Entity<Buffer>,
15716        position: text::Anchor,
15717        new_name: String,
15718        cx: &mut App,
15719    ) -> Option<Task<Result<ProjectTransaction>>> {
15720        Some(self.update(cx, |project, cx| {
15721            project.perform_rename(buffer.clone(), position, new_name, cx)
15722        }))
15723    }
15724}
15725
15726fn inlay_hint_settings(
15727    location: Anchor,
15728    snapshot: &MultiBufferSnapshot,
15729    cx: &mut Context<Editor>,
15730) -> InlayHintSettings {
15731    let file = snapshot.file_at(location);
15732    let language = snapshot.language_at(location).map(|l| l.name());
15733    language_settings(language, file, cx).inlay_hints
15734}
15735
15736fn consume_contiguous_rows(
15737    contiguous_row_selections: &mut Vec<Selection<Point>>,
15738    selection: &Selection<Point>,
15739    display_map: &DisplaySnapshot,
15740    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15741) -> (MultiBufferRow, MultiBufferRow) {
15742    contiguous_row_selections.push(selection.clone());
15743    let start_row = MultiBufferRow(selection.start.row);
15744    let mut end_row = ending_row(selection, display_map);
15745
15746    while let Some(next_selection) = selections.peek() {
15747        if next_selection.start.row <= end_row.0 {
15748            end_row = ending_row(next_selection, display_map);
15749            contiguous_row_selections.push(selections.next().unwrap().clone());
15750        } else {
15751            break;
15752        }
15753    }
15754    (start_row, end_row)
15755}
15756
15757fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15758    if next_selection.end.column > 0 || next_selection.is_empty() {
15759        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15760    } else {
15761        MultiBufferRow(next_selection.end.row)
15762    }
15763}
15764
15765impl EditorSnapshot {
15766    pub fn remote_selections_in_range<'a>(
15767        &'a self,
15768        range: &'a Range<Anchor>,
15769        collaboration_hub: &dyn CollaborationHub,
15770        cx: &'a App,
15771    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15772        let participant_names = collaboration_hub.user_names(cx);
15773        let participant_indices = collaboration_hub.user_participant_indices(cx);
15774        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15775        let collaborators_by_replica_id = collaborators_by_peer_id
15776            .iter()
15777            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15778            .collect::<HashMap<_, _>>();
15779        self.buffer_snapshot
15780            .selections_in_range(range, false)
15781            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15782                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15783                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15784                let user_name = participant_names.get(&collaborator.user_id).cloned();
15785                Some(RemoteSelection {
15786                    replica_id,
15787                    selection,
15788                    cursor_shape,
15789                    line_mode,
15790                    participant_index,
15791                    peer_id: collaborator.peer_id,
15792                    user_name,
15793                })
15794            })
15795    }
15796
15797    pub fn hunks_for_ranges(
15798        &self,
15799        ranges: impl Iterator<Item = Range<Point>>,
15800    ) -> Vec<MultiBufferDiffHunk> {
15801        let mut hunks = Vec::new();
15802        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15803            HashMap::default();
15804        for query_range in ranges {
15805            let query_rows =
15806                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15807            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15808                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15809            ) {
15810                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15811                // when the caret is just above or just below the deleted hunk.
15812                let allow_adjacent = hunk.status().is_removed();
15813                let related_to_selection = if allow_adjacent {
15814                    hunk.row_range.overlaps(&query_rows)
15815                        || hunk.row_range.start == query_rows.end
15816                        || hunk.row_range.end == query_rows.start
15817                } else {
15818                    hunk.row_range.overlaps(&query_rows)
15819                };
15820                if related_to_selection {
15821                    if !processed_buffer_rows
15822                        .entry(hunk.buffer_id)
15823                        .or_default()
15824                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15825                    {
15826                        continue;
15827                    }
15828                    hunks.push(hunk);
15829                }
15830            }
15831        }
15832
15833        hunks
15834    }
15835
15836    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15837        self.display_snapshot.buffer_snapshot.language_at(position)
15838    }
15839
15840    pub fn is_focused(&self) -> bool {
15841        self.is_focused
15842    }
15843
15844    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15845        self.placeholder_text.as_ref()
15846    }
15847
15848    pub fn scroll_position(&self) -> gpui::Point<f32> {
15849        self.scroll_anchor.scroll_position(&self.display_snapshot)
15850    }
15851
15852    fn gutter_dimensions(
15853        &self,
15854        font_id: FontId,
15855        font_size: Pixels,
15856        max_line_number_width: Pixels,
15857        cx: &App,
15858    ) -> Option<GutterDimensions> {
15859        if !self.show_gutter {
15860            return None;
15861        }
15862
15863        let descent = cx.text_system().descent(font_id, font_size);
15864        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15865        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15866
15867        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15868            matches!(
15869                ProjectSettings::get_global(cx).git.git_gutter,
15870                Some(GitGutterSetting::TrackedFiles)
15871            )
15872        });
15873        let gutter_settings = EditorSettings::get_global(cx).gutter;
15874        let show_line_numbers = self
15875            .show_line_numbers
15876            .unwrap_or(gutter_settings.line_numbers);
15877        let line_gutter_width = if show_line_numbers {
15878            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15879            let min_width_for_number_on_gutter = em_advance * 4.0;
15880            max_line_number_width.max(min_width_for_number_on_gutter)
15881        } else {
15882            0.0.into()
15883        };
15884
15885        let show_code_actions = self
15886            .show_code_actions
15887            .unwrap_or(gutter_settings.code_actions);
15888
15889        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15890
15891        let git_blame_entries_width =
15892            self.git_blame_gutter_max_author_length
15893                .map(|max_author_length| {
15894                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15895
15896                    /// The number of characters to dedicate to gaps and margins.
15897                    const SPACING_WIDTH: usize = 4;
15898
15899                    let max_char_count = max_author_length
15900                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15901                        + ::git::SHORT_SHA_LENGTH
15902                        + MAX_RELATIVE_TIMESTAMP.len()
15903                        + SPACING_WIDTH;
15904
15905                    em_advance * max_char_count
15906                });
15907
15908        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15909        left_padding += if show_code_actions || show_runnables {
15910            em_width * 3.0
15911        } else if show_git_gutter && show_line_numbers {
15912            em_width * 2.0
15913        } else if show_git_gutter || show_line_numbers {
15914            em_width
15915        } else {
15916            px(0.)
15917        };
15918
15919        let right_padding = if gutter_settings.folds && show_line_numbers {
15920            em_width * 4.0
15921        } else if gutter_settings.folds {
15922            em_width * 3.0
15923        } else if show_line_numbers {
15924            em_width
15925        } else {
15926            px(0.)
15927        };
15928
15929        Some(GutterDimensions {
15930            left_padding,
15931            right_padding,
15932            width: line_gutter_width + left_padding + right_padding,
15933            margin: -descent,
15934            git_blame_entries_width,
15935        })
15936    }
15937
15938    pub fn render_crease_toggle(
15939        &self,
15940        buffer_row: MultiBufferRow,
15941        row_contains_cursor: bool,
15942        editor: Entity<Editor>,
15943        window: &mut Window,
15944        cx: &mut App,
15945    ) -> Option<AnyElement> {
15946        let folded = self.is_line_folded(buffer_row);
15947        let mut is_foldable = false;
15948
15949        if let Some(crease) = self
15950            .crease_snapshot
15951            .query_row(buffer_row, &self.buffer_snapshot)
15952        {
15953            is_foldable = true;
15954            match crease {
15955                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15956                    if let Some(render_toggle) = render_toggle {
15957                        let toggle_callback =
15958                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15959                                if folded {
15960                                    editor.update(cx, |editor, cx| {
15961                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15962                                    });
15963                                } else {
15964                                    editor.update(cx, |editor, cx| {
15965                                        editor.unfold_at(
15966                                            &crate::UnfoldAt { buffer_row },
15967                                            window,
15968                                            cx,
15969                                        )
15970                                    });
15971                                }
15972                            });
15973                        return Some((render_toggle)(
15974                            buffer_row,
15975                            folded,
15976                            toggle_callback,
15977                            window,
15978                            cx,
15979                        ));
15980                    }
15981                }
15982            }
15983        }
15984
15985        is_foldable |= self.starts_indent(buffer_row);
15986
15987        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15988            Some(
15989                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15990                    .toggle_state(folded)
15991                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15992                        if folded {
15993                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15994                        } else {
15995                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15996                        }
15997                    }))
15998                    .into_any_element(),
15999            )
16000        } else {
16001            None
16002        }
16003    }
16004
16005    pub fn render_crease_trailer(
16006        &self,
16007        buffer_row: MultiBufferRow,
16008        window: &mut Window,
16009        cx: &mut App,
16010    ) -> Option<AnyElement> {
16011        let folded = self.is_line_folded(buffer_row);
16012        if let Crease::Inline { render_trailer, .. } = self
16013            .crease_snapshot
16014            .query_row(buffer_row, &self.buffer_snapshot)?
16015        {
16016            let render_trailer = render_trailer.as_ref()?;
16017            Some(render_trailer(buffer_row, folded, window, cx))
16018        } else {
16019            None
16020        }
16021    }
16022}
16023
16024impl Deref for EditorSnapshot {
16025    type Target = DisplaySnapshot;
16026
16027    fn deref(&self) -> &Self::Target {
16028        &self.display_snapshot
16029    }
16030}
16031
16032#[derive(Clone, Debug, PartialEq, Eq)]
16033pub enum EditorEvent {
16034    InputIgnored {
16035        text: Arc<str>,
16036    },
16037    InputHandled {
16038        utf16_range_to_replace: Option<Range<isize>>,
16039        text: Arc<str>,
16040    },
16041    ExcerptsAdded {
16042        buffer: Entity<Buffer>,
16043        predecessor: ExcerptId,
16044        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16045    },
16046    ExcerptsRemoved {
16047        ids: Vec<ExcerptId>,
16048    },
16049    BufferFoldToggled {
16050        ids: Vec<ExcerptId>,
16051        folded: bool,
16052    },
16053    ExcerptsEdited {
16054        ids: Vec<ExcerptId>,
16055    },
16056    ExcerptsExpanded {
16057        ids: Vec<ExcerptId>,
16058    },
16059    BufferEdited,
16060    Edited {
16061        transaction_id: clock::Lamport,
16062    },
16063    Reparsed(BufferId),
16064    Focused,
16065    FocusedIn,
16066    Blurred,
16067    DirtyChanged,
16068    Saved,
16069    TitleChanged,
16070    DiffBaseChanged,
16071    SelectionsChanged {
16072        local: bool,
16073    },
16074    ScrollPositionChanged {
16075        local: bool,
16076        autoscroll: bool,
16077    },
16078    Closed,
16079    TransactionUndone {
16080        transaction_id: clock::Lamport,
16081    },
16082    TransactionBegun {
16083        transaction_id: clock::Lamport,
16084    },
16085    Reloaded,
16086    CursorShapeChanged,
16087}
16088
16089impl EventEmitter<EditorEvent> for Editor {}
16090
16091impl Focusable for Editor {
16092    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16093        self.focus_handle.clone()
16094    }
16095}
16096
16097impl Render for Editor {
16098    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16099        let settings = ThemeSettings::get_global(cx);
16100
16101        let mut text_style = match self.mode {
16102            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16103                color: cx.theme().colors().editor_foreground,
16104                font_family: settings.ui_font.family.clone(),
16105                font_features: settings.ui_font.features.clone(),
16106                font_fallbacks: settings.ui_font.fallbacks.clone(),
16107                font_size: rems(0.875).into(),
16108                font_weight: settings.ui_font.weight,
16109                line_height: relative(settings.buffer_line_height.value()),
16110                ..Default::default()
16111            },
16112            EditorMode::Full => TextStyle {
16113                color: cx.theme().colors().editor_foreground,
16114                font_family: settings.buffer_font.family.clone(),
16115                font_features: settings.buffer_font.features.clone(),
16116                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16117                font_size: settings.buffer_font_size().into(),
16118                font_weight: settings.buffer_font.weight,
16119                line_height: relative(settings.buffer_line_height.value()),
16120                ..Default::default()
16121            },
16122        };
16123        if let Some(text_style_refinement) = &self.text_style_refinement {
16124            text_style.refine(text_style_refinement)
16125        }
16126
16127        let background = match self.mode {
16128            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16129            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16130            EditorMode::Full => cx.theme().colors().editor_background,
16131        };
16132
16133        EditorElement::new(
16134            &cx.entity(),
16135            EditorStyle {
16136                background,
16137                local_player: cx.theme().players().local(),
16138                text: text_style,
16139                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16140                syntax: cx.theme().syntax().clone(),
16141                status: cx.theme().status().clone(),
16142                inlay_hints_style: make_inlay_hints_style(cx),
16143                inline_completion_styles: make_suggestion_styles(cx),
16144                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16145            },
16146        )
16147    }
16148}
16149
16150impl EntityInputHandler for Editor {
16151    fn text_for_range(
16152        &mut self,
16153        range_utf16: Range<usize>,
16154        adjusted_range: &mut Option<Range<usize>>,
16155        _: &mut Window,
16156        cx: &mut Context<Self>,
16157    ) -> Option<String> {
16158        let snapshot = self.buffer.read(cx).read(cx);
16159        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16160        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16161        if (start.0..end.0) != range_utf16 {
16162            adjusted_range.replace(start.0..end.0);
16163        }
16164        Some(snapshot.text_for_range(start..end).collect())
16165    }
16166
16167    fn selected_text_range(
16168        &mut self,
16169        ignore_disabled_input: bool,
16170        _: &mut Window,
16171        cx: &mut Context<Self>,
16172    ) -> Option<UTF16Selection> {
16173        // Prevent the IME menu from appearing when holding down an alphabetic key
16174        // while input is disabled.
16175        if !ignore_disabled_input && !self.input_enabled {
16176            return None;
16177        }
16178
16179        let selection = self.selections.newest::<OffsetUtf16>(cx);
16180        let range = selection.range();
16181
16182        Some(UTF16Selection {
16183            range: range.start.0..range.end.0,
16184            reversed: selection.reversed,
16185        })
16186    }
16187
16188    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16189        let snapshot = self.buffer.read(cx).read(cx);
16190        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16191        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16192    }
16193
16194    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16195        self.clear_highlights::<InputComposition>(cx);
16196        self.ime_transaction.take();
16197    }
16198
16199    fn replace_text_in_range(
16200        &mut self,
16201        range_utf16: Option<Range<usize>>,
16202        text: &str,
16203        window: &mut Window,
16204        cx: &mut Context<Self>,
16205    ) {
16206        if !self.input_enabled {
16207            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16208            return;
16209        }
16210
16211        self.transact(window, cx, |this, window, cx| {
16212            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16213                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16214                Some(this.selection_replacement_ranges(range_utf16, cx))
16215            } else {
16216                this.marked_text_ranges(cx)
16217            };
16218
16219            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16220                let newest_selection_id = this.selections.newest_anchor().id;
16221                this.selections
16222                    .all::<OffsetUtf16>(cx)
16223                    .iter()
16224                    .zip(ranges_to_replace.iter())
16225                    .find_map(|(selection, range)| {
16226                        if selection.id == newest_selection_id {
16227                            Some(
16228                                (range.start.0 as isize - selection.head().0 as isize)
16229                                    ..(range.end.0 as isize - selection.head().0 as isize),
16230                            )
16231                        } else {
16232                            None
16233                        }
16234                    })
16235            });
16236
16237            cx.emit(EditorEvent::InputHandled {
16238                utf16_range_to_replace: range_to_replace,
16239                text: text.into(),
16240            });
16241
16242            if let Some(new_selected_ranges) = new_selected_ranges {
16243                this.change_selections(None, window, cx, |selections| {
16244                    selections.select_ranges(new_selected_ranges)
16245                });
16246                this.backspace(&Default::default(), window, cx);
16247            }
16248
16249            this.handle_input(text, window, cx);
16250        });
16251
16252        if let Some(transaction) = self.ime_transaction {
16253            self.buffer.update(cx, |buffer, cx| {
16254                buffer.group_until_transaction(transaction, cx);
16255            });
16256        }
16257
16258        self.unmark_text(window, cx);
16259    }
16260
16261    fn replace_and_mark_text_in_range(
16262        &mut self,
16263        range_utf16: Option<Range<usize>>,
16264        text: &str,
16265        new_selected_range_utf16: Option<Range<usize>>,
16266        window: &mut Window,
16267        cx: &mut Context<Self>,
16268    ) {
16269        if !self.input_enabled {
16270            return;
16271        }
16272
16273        let transaction = self.transact(window, cx, |this, window, cx| {
16274            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16275                let snapshot = this.buffer.read(cx).read(cx);
16276                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16277                    for marked_range in &mut marked_ranges {
16278                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16279                        marked_range.start.0 += relative_range_utf16.start;
16280                        marked_range.start =
16281                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16282                        marked_range.end =
16283                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16284                    }
16285                }
16286                Some(marked_ranges)
16287            } else if let Some(range_utf16) = range_utf16 {
16288                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16289                Some(this.selection_replacement_ranges(range_utf16, cx))
16290            } else {
16291                None
16292            };
16293
16294            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16295                let newest_selection_id = this.selections.newest_anchor().id;
16296                this.selections
16297                    .all::<OffsetUtf16>(cx)
16298                    .iter()
16299                    .zip(ranges_to_replace.iter())
16300                    .find_map(|(selection, range)| {
16301                        if selection.id == newest_selection_id {
16302                            Some(
16303                                (range.start.0 as isize - selection.head().0 as isize)
16304                                    ..(range.end.0 as isize - selection.head().0 as isize),
16305                            )
16306                        } else {
16307                            None
16308                        }
16309                    })
16310            });
16311
16312            cx.emit(EditorEvent::InputHandled {
16313                utf16_range_to_replace: range_to_replace,
16314                text: text.into(),
16315            });
16316
16317            if let Some(ranges) = ranges_to_replace {
16318                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16319            }
16320
16321            let marked_ranges = {
16322                let snapshot = this.buffer.read(cx).read(cx);
16323                this.selections
16324                    .disjoint_anchors()
16325                    .iter()
16326                    .map(|selection| {
16327                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16328                    })
16329                    .collect::<Vec<_>>()
16330            };
16331
16332            if text.is_empty() {
16333                this.unmark_text(window, cx);
16334            } else {
16335                this.highlight_text::<InputComposition>(
16336                    marked_ranges.clone(),
16337                    HighlightStyle {
16338                        underline: Some(UnderlineStyle {
16339                            thickness: px(1.),
16340                            color: None,
16341                            wavy: false,
16342                        }),
16343                        ..Default::default()
16344                    },
16345                    cx,
16346                );
16347            }
16348
16349            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16350            let use_autoclose = this.use_autoclose;
16351            let use_auto_surround = this.use_auto_surround;
16352            this.set_use_autoclose(false);
16353            this.set_use_auto_surround(false);
16354            this.handle_input(text, window, cx);
16355            this.set_use_autoclose(use_autoclose);
16356            this.set_use_auto_surround(use_auto_surround);
16357
16358            if let Some(new_selected_range) = new_selected_range_utf16 {
16359                let snapshot = this.buffer.read(cx).read(cx);
16360                let new_selected_ranges = marked_ranges
16361                    .into_iter()
16362                    .map(|marked_range| {
16363                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16364                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16365                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16366                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16367                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16368                    })
16369                    .collect::<Vec<_>>();
16370
16371                drop(snapshot);
16372                this.change_selections(None, window, cx, |selections| {
16373                    selections.select_ranges(new_selected_ranges)
16374                });
16375            }
16376        });
16377
16378        self.ime_transaction = self.ime_transaction.or(transaction);
16379        if let Some(transaction) = self.ime_transaction {
16380            self.buffer.update(cx, |buffer, cx| {
16381                buffer.group_until_transaction(transaction, cx);
16382            });
16383        }
16384
16385        if self.text_highlights::<InputComposition>(cx).is_none() {
16386            self.ime_transaction.take();
16387        }
16388    }
16389
16390    fn bounds_for_range(
16391        &mut self,
16392        range_utf16: Range<usize>,
16393        element_bounds: gpui::Bounds<Pixels>,
16394        window: &mut Window,
16395        cx: &mut Context<Self>,
16396    ) -> Option<gpui::Bounds<Pixels>> {
16397        let text_layout_details = self.text_layout_details(window);
16398        let gpui::Size {
16399            width: em_width,
16400            height: line_height,
16401        } = self.character_size(window);
16402
16403        let snapshot = self.snapshot(window, cx);
16404        let scroll_position = snapshot.scroll_position();
16405        let scroll_left = scroll_position.x * em_width;
16406
16407        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16408        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16409            + self.gutter_dimensions.width
16410            + self.gutter_dimensions.margin;
16411        let y = line_height * (start.row().as_f32() - scroll_position.y);
16412
16413        Some(Bounds {
16414            origin: element_bounds.origin + point(x, y),
16415            size: size(em_width, line_height),
16416        })
16417    }
16418
16419    fn character_index_for_point(
16420        &mut self,
16421        point: gpui::Point<Pixels>,
16422        _window: &mut Window,
16423        _cx: &mut Context<Self>,
16424    ) -> Option<usize> {
16425        let position_map = self.last_position_map.as_ref()?;
16426        if !position_map.text_hitbox.contains(&point) {
16427            return None;
16428        }
16429        let display_point = position_map.point_for_position(point).previous_valid;
16430        let anchor = position_map
16431            .snapshot
16432            .display_point_to_anchor(display_point, Bias::Left);
16433        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16434        Some(utf16_offset.0)
16435    }
16436}
16437
16438trait SelectionExt {
16439    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16440    fn spanned_rows(
16441        &self,
16442        include_end_if_at_line_start: bool,
16443        map: &DisplaySnapshot,
16444    ) -> Range<MultiBufferRow>;
16445}
16446
16447impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16448    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16449        let start = self
16450            .start
16451            .to_point(&map.buffer_snapshot)
16452            .to_display_point(map);
16453        let end = self
16454            .end
16455            .to_point(&map.buffer_snapshot)
16456            .to_display_point(map);
16457        if self.reversed {
16458            end..start
16459        } else {
16460            start..end
16461        }
16462    }
16463
16464    fn spanned_rows(
16465        &self,
16466        include_end_if_at_line_start: bool,
16467        map: &DisplaySnapshot,
16468    ) -> Range<MultiBufferRow> {
16469        let start = self.start.to_point(&map.buffer_snapshot);
16470        let mut end = self.end.to_point(&map.buffer_snapshot);
16471        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16472            end.row -= 1;
16473        }
16474
16475        let buffer_start = map.prev_line_boundary(start).0;
16476        let buffer_end = map.next_line_boundary(end).0;
16477        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16478    }
16479}
16480
16481impl<T: InvalidationRegion> InvalidationStack<T> {
16482    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16483    where
16484        S: Clone + ToOffset,
16485    {
16486        while let Some(region) = self.last() {
16487            let all_selections_inside_invalidation_ranges =
16488                if selections.len() == region.ranges().len() {
16489                    selections
16490                        .iter()
16491                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16492                        .all(|(selection, invalidation_range)| {
16493                            let head = selection.head().to_offset(buffer);
16494                            invalidation_range.start <= head && invalidation_range.end >= head
16495                        })
16496                } else {
16497                    false
16498                };
16499
16500            if all_selections_inside_invalidation_ranges {
16501                break;
16502            } else {
16503                self.pop();
16504            }
16505        }
16506    }
16507}
16508
16509impl<T> Default for InvalidationStack<T> {
16510    fn default() -> Self {
16511        Self(Default::default())
16512    }
16513}
16514
16515impl<T> Deref for InvalidationStack<T> {
16516    type Target = Vec<T>;
16517
16518    fn deref(&self) -> &Self::Target {
16519        &self.0
16520    }
16521}
16522
16523impl<T> DerefMut for InvalidationStack<T> {
16524    fn deref_mut(&mut self) -> &mut Self::Target {
16525        &mut self.0
16526    }
16527}
16528
16529impl InvalidationRegion for SnippetState {
16530    fn ranges(&self) -> &[Range<Anchor>] {
16531        &self.ranges[self.active_index]
16532    }
16533}
16534
16535pub fn diagnostic_block_renderer(
16536    diagnostic: Diagnostic,
16537    max_message_rows: Option<u8>,
16538    allow_closing: bool,
16539    _is_valid: bool,
16540) -> RenderBlock {
16541    let (text_without_backticks, code_ranges) =
16542        highlight_diagnostic_message(&diagnostic, max_message_rows);
16543
16544    Arc::new(move |cx: &mut BlockContext| {
16545        let group_id: SharedString = cx.block_id.to_string().into();
16546
16547        let mut text_style = cx.window.text_style().clone();
16548        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16549        let theme_settings = ThemeSettings::get_global(cx);
16550        text_style.font_family = theme_settings.buffer_font.family.clone();
16551        text_style.font_style = theme_settings.buffer_font.style;
16552        text_style.font_features = theme_settings.buffer_font.features.clone();
16553        text_style.font_weight = theme_settings.buffer_font.weight;
16554
16555        let multi_line_diagnostic = diagnostic.message.contains('\n');
16556
16557        let buttons = |diagnostic: &Diagnostic| {
16558            if multi_line_diagnostic {
16559                v_flex()
16560            } else {
16561                h_flex()
16562            }
16563            .when(allow_closing, |div| {
16564                div.children(diagnostic.is_primary.then(|| {
16565                    IconButton::new("close-block", IconName::XCircle)
16566                        .icon_color(Color::Muted)
16567                        .size(ButtonSize::Compact)
16568                        .style(ButtonStyle::Transparent)
16569                        .visible_on_hover(group_id.clone())
16570                        .on_click(move |_click, window, cx| {
16571                            window.dispatch_action(Box::new(Cancel), cx)
16572                        })
16573                        .tooltip(|window, cx| {
16574                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16575                        })
16576                }))
16577            })
16578            .child(
16579                IconButton::new("copy-block", IconName::Copy)
16580                    .icon_color(Color::Muted)
16581                    .size(ButtonSize::Compact)
16582                    .style(ButtonStyle::Transparent)
16583                    .visible_on_hover(group_id.clone())
16584                    .on_click({
16585                        let message = diagnostic.message.clone();
16586                        move |_click, _, cx| {
16587                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16588                        }
16589                    })
16590                    .tooltip(Tooltip::text("Copy diagnostic message")),
16591            )
16592        };
16593
16594        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16595            AvailableSpace::min_size(),
16596            cx.window,
16597            cx.app,
16598        );
16599
16600        h_flex()
16601            .id(cx.block_id)
16602            .group(group_id.clone())
16603            .relative()
16604            .size_full()
16605            .block_mouse_down()
16606            .pl(cx.gutter_dimensions.width)
16607            .w(cx.max_width - cx.gutter_dimensions.full_width())
16608            .child(
16609                div()
16610                    .flex()
16611                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16612                    .flex_shrink(),
16613            )
16614            .child(buttons(&diagnostic))
16615            .child(div().flex().flex_shrink_0().child(
16616                StyledText::new(text_without_backticks.clone()).with_highlights(
16617                    &text_style,
16618                    code_ranges.iter().map(|range| {
16619                        (
16620                            range.clone(),
16621                            HighlightStyle {
16622                                font_weight: Some(FontWeight::BOLD),
16623                                ..Default::default()
16624                            },
16625                        )
16626                    }),
16627                ),
16628            ))
16629            .into_any_element()
16630    })
16631}
16632
16633fn inline_completion_edit_text(
16634    current_snapshot: &BufferSnapshot,
16635    edits: &[(Range<Anchor>, String)],
16636    edit_preview: &EditPreview,
16637    include_deletions: bool,
16638    cx: &App,
16639) -> HighlightedText {
16640    let edits = edits
16641        .iter()
16642        .map(|(anchor, text)| {
16643            (
16644                anchor.start.text_anchor..anchor.end.text_anchor,
16645                text.clone(),
16646            )
16647        })
16648        .collect::<Vec<_>>();
16649
16650    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16651}
16652
16653pub fn highlight_diagnostic_message(
16654    diagnostic: &Diagnostic,
16655    mut max_message_rows: Option<u8>,
16656) -> (SharedString, Vec<Range<usize>>) {
16657    let mut text_without_backticks = String::new();
16658    let mut code_ranges = Vec::new();
16659
16660    if let Some(source) = &diagnostic.source {
16661        text_without_backticks.push_str(source);
16662        code_ranges.push(0..source.len());
16663        text_without_backticks.push_str(": ");
16664    }
16665
16666    let mut prev_offset = 0;
16667    let mut in_code_block = false;
16668    let has_row_limit = max_message_rows.is_some();
16669    let mut newline_indices = diagnostic
16670        .message
16671        .match_indices('\n')
16672        .filter(|_| has_row_limit)
16673        .map(|(ix, _)| ix)
16674        .fuse()
16675        .peekable();
16676
16677    for (quote_ix, _) in diagnostic
16678        .message
16679        .match_indices('`')
16680        .chain([(diagnostic.message.len(), "")])
16681    {
16682        let mut first_newline_ix = None;
16683        let mut last_newline_ix = None;
16684        while let Some(newline_ix) = newline_indices.peek() {
16685            if *newline_ix < quote_ix {
16686                if first_newline_ix.is_none() {
16687                    first_newline_ix = Some(*newline_ix);
16688                }
16689                last_newline_ix = Some(*newline_ix);
16690
16691                if let Some(rows_left) = &mut max_message_rows {
16692                    if *rows_left == 0 {
16693                        break;
16694                    } else {
16695                        *rows_left -= 1;
16696                    }
16697                }
16698                let _ = newline_indices.next();
16699            } else {
16700                break;
16701            }
16702        }
16703        let prev_len = text_without_backticks.len();
16704        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16705        text_without_backticks.push_str(new_text);
16706        if in_code_block {
16707            code_ranges.push(prev_len..text_without_backticks.len());
16708        }
16709        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16710        in_code_block = !in_code_block;
16711        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16712            text_without_backticks.push_str("...");
16713            break;
16714        }
16715    }
16716
16717    (text_without_backticks.into(), code_ranges)
16718}
16719
16720fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16721    match severity {
16722        DiagnosticSeverity::ERROR => colors.error,
16723        DiagnosticSeverity::WARNING => colors.warning,
16724        DiagnosticSeverity::INFORMATION => colors.info,
16725        DiagnosticSeverity::HINT => colors.info,
16726        _ => colors.ignored,
16727    }
16728}
16729
16730pub fn styled_runs_for_code_label<'a>(
16731    label: &'a CodeLabel,
16732    syntax_theme: &'a theme::SyntaxTheme,
16733) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16734    let fade_out = HighlightStyle {
16735        fade_out: Some(0.35),
16736        ..Default::default()
16737    };
16738
16739    let mut prev_end = label.filter_range.end;
16740    label
16741        .runs
16742        .iter()
16743        .enumerate()
16744        .flat_map(move |(ix, (range, highlight_id))| {
16745            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16746                style
16747            } else {
16748                return Default::default();
16749            };
16750            let mut muted_style = style;
16751            muted_style.highlight(fade_out);
16752
16753            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16754            if range.start >= label.filter_range.end {
16755                if range.start > prev_end {
16756                    runs.push((prev_end..range.start, fade_out));
16757                }
16758                runs.push((range.clone(), muted_style));
16759            } else if range.end <= label.filter_range.end {
16760                runs.push((range.clone(), style));
16761            } else {
16762                runs.push((range.start..label.filter_range.end, style));
16763                runs.push((label.filter_range.end..range.end, muted_style));
16764            }
16765            prev_end = cmp::max(prev_end, range.end);
16766
16767            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16768                runs.push((prev_end..label.text.len(), fade_out));
16769            }
16770
16771            runs
16772        })
16773}
16774
16775pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16776    let mut prev_index = 0;
16777    let mut prev_codepoint: Option<char> = None;
16778    text.char_indices()
16779        .chain([(text.len(), '\0')])
16780        .filter_map(move |(index, codepoint)| {
16781            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16782            let is_boundary = index == text.len()
16783                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16784                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16785            if is_boundary {
16786                let chunk = &text[prev_index..index];
16787                prev_index = index;
16788                Some(chunk)
16789            } else {
16790                None
16791            }
16792        })
16793}
16794
16795pub trait RangeToAnchorExt: Sized {
16796    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16797
16798    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16799        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16800        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16801    }
16802}
16803
16804impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16805    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16806        let start_offset = self.start.to_offset(snapshot);
16807        let end_offset = self.end.to_offset(snapshot);
16808        if start_offset == end_offset {
16809            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16810        } else {
16811            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16812        }
16813    }
16814}
16815
16816pub trait RowExt {
16817    fn as_f32(&self) -> f32;
16818
16819    fn next_row(&self) -> Self;
16820
16821    fn previous_row(&self) -> Self;
16822
16823    fn minus(&self, other: Self) -> u32;
16824}
16825
16826impl RowExt for DisplayRow {
16827    fn as_f32(&self) -> f32 {
16828        self.0 as f32
16829    }
16830
16831    fn next_row(&self) -> Self {
16832        Self(self.0 + 1)
16833    }
16834
16835    fn previous_row(&self) -> Self {
16836        Self(self.0.saturating_sub(1))
16837    }
16838
16839    fn minus(&self, other: Self) -> u32 {
16840        self.0 - other.0
16841    }
16842}
16843
16844impl RowExt for MultiBufferRow {
16845    fn as_f32(&self) -> f32 {
16846        self.0 as f32
16847    }
16848
16849    fn next_row(&self) -> Self {
16850        Self(self.0 + 1)
16851    }
16852
16853    fn previous_row(&self) -> Self {
16854        Self(self.0.saturating_sub(1))
16855    }
16856
16857    fn minus(&self, other: Self) -> u32 {
16858        self.0 - other.0
16859    }
16860}
16861
16862trait RowRangeExt {
16863    type Row;
16864
16865    fn len(&self) -> usize;
16866
16867    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16868}
16869
16870impl RowRangeExt for Range<MultiBufferRow> {
16871    type Row = MultiBufferRow;
16872
16873    fn len(&self) -> usize {
16874        (self.end.0 - self.start.0) as usize
16875    }
16876
16877    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16878        (self.start.0..self.end.0).map(MultiBufferRow)
16879    }
16880}
16881
16882impl RowRangeExt for Range<DisplayRow> {
16883    type Row = DisplayRow;
16884
16885    fn len(&self) -> usize {
16886        (self.end.0 - self.start.0) as usize
16887    }
16888
16889    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16890        (self.start.0..self.end.0).map(DisplayRow)
16891    }
16892}
16893
16894/// If select range has more than one line, we
16895/// just point the cursor to range.start.
16896fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16897    if range.start.row == range.end.row {
16898        range
16899    } else {
16900        range.start..range.start
16901    }
16902}
16903pub struct KillRing(ClipboardItem);
16904impl Global for KillRing {}
16905
16906const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16907
16908fn all_edits_insertions_or_deletions(
16909    edits: &Vec<(Range<Anchor>, String)>,
16910    snapshot: &MultiBufferSnapshot,
16911) -> bool {
16912    let mut all_insertions = true;
16913    let mut all_deletions = true;
16914
16915    for (range, new_text) in edits.iter() {
16916        let range_is_empty = range.to_offset(&snapshot).is_empty();
16917        let text_is_empty = new_text.is_empty();
16918
16919        if range_is_empty != text_is_empty {
16920            if range_is_empty {
16921                all_deletions = false;
16922            } else {
16923                all_insertions = false;
16924            }
16925        } else {
16926            return false;
16927        }
16928
16929        if !all_insertions && !all_deletions {
16930            return false;
16931        }
16932    }
16933    all_insertions || all_deletions
16934}